diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ea4ab2..2c3e7f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,56 @@ All notable changes to `workflow-engine-core` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## v3.0.0 - 2026-11-26 + +Workflows can now wait for people and for time without holding a PHP process, and two +processes can no longer overwrite each other's progress. Breaking; see [UPGRADE.md](UPGRADE.md). + +### Added + +- **`ActionResult::suspend($for, $resumeAt = null, $data = [])`.** A step that has to wait (an + approval, a task someone else does, a deadline) returns it. The instance becomes `WAITING` + with a `Wait` (`getWait()`: step, signal name, resume time) and the next steps do not run. +- **`WorkflowEngine::signal($id, $signal, $payload = [])`** finishes the waiting step and carries + on. The payload is kept under `steps.` (`resumed_by`, `payload`, `resumed_at`), so + transitions can branch on it: `steps.approve.payload.decision === "approved"`. +- **`WorkflowEngine::resumeDue($now = null, $limit = 100)`** ends waits whose time has passed + (`resumed_by` = `Wait::TIMER`). Run it from a scheduler. +- **Optimistic locking.** `WorkflowInstance::getRevision()`; `StorageAdapter::save()` is a + compare-and-swap on it and throws the new `ConcurrentModificationException` when someone else + saved first. A conflict is not recorded as a workflow failure. +- `WorkflowDefinition::fingerprint()` (SHA-256 of the content, key order ignored); instances + record it in `toArray()['definition_fingerprint']`. +- Events `WorkflowSuspendedEvent` and `WorkflowResumedEvent`. +- `WorkflowEngine` takes an optional `Logger` and `signalTimeouts` flag. +- `StorageAdapter::findInstances()` criterion `due_before`. + +### Changed (breaking) + +- **`DelayAction` suspends instead of `usleep()`.** `->delay(hours: 2)` used to block the process + for two hours; it now waits until `resumeDue()` runs after the time. A zero delay completes at once. +- **Step timeouts are no longer enforced with SIGALRM by default.** `pcntl_alarm()` interrupts + whatever runs in the process, which is unsafe in web requests and long-running workers + (FrankenPHP, Octane). Pass `signalTimeouts: true` in a CLI worker that runs one workflow at a + time, or let your queue enforce the timeout. +- **`resume()` refuses a suspended instance**: running it again would run the waiting step's + action twice. Use `signal()`. +- **`StorageAdapter::save()` must check and bump the revision**, and persist `getWait()`. +- `InMemoryStorage` keeps snapshots: every `load()` returns a fresh copy, like a database, and a + save from a stale copy is refused. +- `ActionResult::isFailure()` is false for a suspended result (it is neither success nor failure). +- **Malformed input is rejected instead of coerced** (PHPStan level 9, was 6, no ignores): + - `DefinitionParser` and `WorkflowDefinition::fromArray()` throw `InvalidWorkflowDefinitionException` + for a missing or non-string `name`, a non-string `version`, step id or condition, a non-integer + `retry_attempts` (`"3"` is rejected), wrongly typed `metadata`, `steps`, `transitions` or step + fields, a transition that is not an array, and JSON that is not an object. + - `WorkflowInstance::fromArray()` throws `InvalidWorkflowStateException` for malformed + `failed_steps`, `data`, `error_message` or timestamps. + - `ConditionAction`, `LogAction` and `HttpAction` fail the step with a clear message for wrongly + typed config (for example an `HttpAction` timeout of `"abc"` used to become 0). `HttpAction` fails + when the URL is empty after templating or the body cannot be JSON-encoded; a template value that + is an array renders as JSON instead of `Array`. + ## v2.0.0 - 2026-09-12 Fixes several cases where the engine silently did the wrong thing and still diff --git a/CLAUDE.md b/CLAUDE.md index d14054c..206b9c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ Project context for Claude Code and AI-assisted development. **workflow-engine-core** is a framework-agnostic PHP workflow engine. Zero production dependencies. PHP 8.3+. MIT licensed. -Status: **v2.0.0** — stable. Breaking changes follow semver and are documented in CHANGELOG.md. +Status: **v3.0.0** — stable. Breaking changes follow semver and are documented in CHANGELOG.md. Related package: `solution-forest/workflow-engine-laravel` (Laravel integration layer). @@ -19,7 +19,7 @@ composer test # Run tests with coverage composer test:coverage -# Static analysis (PHPStan level 6) +# Static analysis (PHPStan level 9) composer analyze # Code formatting (Laravel Pint) @@ -49,12 +49,12 @@ WorkflowBuilder → WorkflowDefinition → WorkflowEngine → Executor → Actio | Namespace | Purpose | |-----------|---------| -| `Core\` | WorkflowEngine, WorkflowBuilder, Executor, StateManager, WorkflowInstance, WorkflowDefinition, WorkflowContext, ActionResult, Step, DefinitionParser, ActionResolver | +| `Core\` | WorkflowEngine, WorkflowBuilder, Executor, StateManager, WorkflowInstance, WorkflowDefinition, WorkflowContext, ActionResult, Suspension, Wait, Step, DefinitionParser, ActionResolver | | `Actions\` | BaseAction, LogAction, FakeEmailAction, HttpAction, DelayAction, ConditionAction | | `Contracts\` | WorkflowAction, StorageAdapter, EventDispatcher, Logger | | `Attributes\` | WorkflowStep, Retry, Timeout, Condition | -| `Events\` | WorkflowStartedEvent, WorkflowCompletedEvent, WorkflowFailedEvent, WorkflowCancelledEvent, StepCompletedEvent, StepFailedEvent, StepRetriedEvent | -| `Exceptions\` | WorkflowException (base), InvalidWorkflowDefinitionException, InvalidWorkflowStateException, ActionNotFoundException, StepExecutionException, WorkflowInstanceNotFoundException | +| `Events\` | WorkflowStartedEvent, WorkflowCompletedEvent, WorkflowFailedEvent, WorkflowCancelledEvent, WorkflowSuspendedEvent, WorkflowResumedEvent, StepCompletedEvent, StepFailedEvent, StepRetriedEvent | +| `Exceptions\` | WorkflowException (base), InvalidWorkflowDefinitionException, InvalidWorkflowStateException, ActionNotFoundException, StepExecutionException, WorkflowInstanceNotFoundException, ConcurrentModificationException | | `Support\` | NullLogger, NullEventDispatcher, SimpleWorkflow, Uuid, Timeout, ConditionEvaluator, Arr | | `Storage\` | InMemoryStorage (ships with the package; non-durable) | @@ -81,6 +81,18 @@ PENDING ──→ RUNNING ──→ COMPLETED (terminal) `FAILED` is recoverable: `resume()` returns the instance to `RUNNING` and retries the step that failed. A workflow blocked on unmet prerequisites parks in `WAITING`. +A step that returns `ActionResult::suspend($for, $resumeAt)` also parks the instance in +`WAITING`, with a `Wait` (`getWait()`). Only `signal($id, $for, $payload)` or `resumeDue()` +(once `resumeAt` has passed) finish that step; `resume()` refuses, so the step never runs twice. +What resumed it is stored under `steps.` in the data. + +### Storage and concurrency + +`StorageAdapter::save()` is a compare-and-swap on `WorkflowInstance::getRevision()`: a save from a +stale copy throws `ConcurrentModificationException` and writes nothing. `InMemoryStorage` keeps +snapshots (every `load()` is a fresh copy) and is the reference implementation. Never sleep in the +engine: delays suspend, and SIGALRM timeouts only run with `signalTimeouts: true`. + Invalid transitions throw `InvalidWorkflowStateException`. ### Key Contracts @@ -94,7 +106,7 @@ Every custom integration implements one of these: ### How Actions Work -Actions are instantiated by `Executor` with `new $actionClass($config, $logger)`. They receive a `WorkflowContext` containing workflowId, stepId, data, config, and the instance reference. They return `ActionResult::success($data)` or `ActionResult::failure($message)`. +Actions are instantiated by `Executor` with `new $actionClass($config, $logger)`. They receive a `WorkflowContext` containing workflowId, stepId, data, config, and the instance reference. They return `ActionResult::success($data)`, `ActionResult::failure($message)` or `ActionResult::suspend($for, $resumeAt, $data)`. ## Conventions @@ -154,6 +166,8 @@ $engine = new WorkflowEngine($storageAdapter, $eventDispatcher); $instanceId = $engine->start('my-workflow', $definition->toArray(), ['key' => 'value']); $instance = $engine->getInstance($instanceId); $engine->cancel($instanceId, 'reason'); +$engine->signal($instanceId, 'approved', ['by' => 'ada']); // finish a suspended step +$engine->resumeDue(); // from a scheduler: end timed waits ``` ## CI/CD @@ -167,7 +181,7 @@ GitHub Actions workflows: ## File Counts -- 47 source files in `src/` -- 27 test files in `tests/` -- 161 tests, 363+ assertions -- PHPStan level 6 compliance +- 52 source files in `src/` +- 26 test files in `tests/` +- 222 tests, 515+ assertions +- PHPStan level 9 compliance diff --git a/README.md b/README.md index dd16e6f..8063c9b 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,6 @@ A powerful, framework-agnostic workflow engine for PHP applications. This core library provides comprehensive workflow definition, execution, and state management capabilities without any framework dependencies. -> ⚠️ **WARNING: DEVELOPMENT STATUS**⚠️ -> -> This package is currently under active development and is **NOT READY FOR PRODUCTION USE**. -> -> Features may be incomplete, APIs might change, and there could be breaking changes. Use at your own risk in development environments only. - - ## 📋 Requirements - **PHP 8.3+** - Leverages modern PHP features for type safety and performance @@ -108,6 +101,45 @@ $instance = $engine->getInstance($instanceId); echo $instance->getState()->value; // "completed" ``` +### Waiting for people and time + +A step that has to wait (an approval, a task someone else does, a deadline) returns +`ActionResult::suspend()`. The workflow stops in `WAITING` without holding a process, and +resumes when a signal arrives or the time passes. + +```php +class RequestApprovalAction extends BaseAction +{ + protected function doExecute(WorkflowContext $context): ActionResult + { + // notify the approvers, then wait for "decided", for at most three days + return ActionResult::suspend('decided', new \DateTimeImmutable('+3 days')); + } +} + +$engine->start('po-42', $definition, ['amount' => 25_000]); // stops in WAITING at the approval + +// When someone decides: +$engine->signal('po-42', 'decided', ['decision' => 'approved']); + +// From a scheduler, every minute: ends waits whose time has passed (resumed_by = "timer"). +$engine->resumeDue(); +``` + +- What resumed a step is kept in the data under `steps.` (`resumed_by`, `payload`, + `resumed_at`), so transitions can branch on it: + `['from' => 'approve', 'to' => 'order', 'condition' => 'steps.approve.payload.decision === "approved"']`. +- `DelayAction` / `->delay()` suspends the same way (`Wait::TIMER`); nothing sleeps. +- `resume()` refuses an instance that waits for a signal, so a waiting step never runs twice. +- Every save is a compare-and-swap on the instance revision. If two processes advance the same + instance, the second gets `ConcurrentModificationException` and writes nothing; load it again + and repeat. +- Step timeouts are enforced with SIGALRM only with `new WorkflowEngine(..., signalTimeouts: true)` + in a CLI worker; otherwise let your queue enforce them. +- Events: `WorkflowSuspendedEvent`, `WorkflowResumedEvent`. + +Upgrading from v2: see [UPGRADE.md](UPGRADE.md). + ### Advanced Workflow Builder ```php @@ -544,7 +576,7 @@ composer pint && composer analyze && composer test We maintain high code quality through: -- **100% PHPStan Level 6** - Static analysis with zero errors across 46 source files +- **100% PHPStan Level 9** - Static analysis with zero errors across 46 source files - **Laravel Pint** - Consistent code formatting following Laravel standards - **Comprehensive Testing** - 93 tests with 224+ assertions covering unit, integration, and real-world scenarios - **Architecture Tests** - Automated checks preventing debug functions in source code diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000..b2da824 --- /dev/null +++ b/UPGRADE.md @@ -0,0 +1,37 @@ +# Upgrading + +## From v2 to v3 + +Most code keeps working. Check these: + +1. **Delays.** `DelayAction` / `WorkflowBuilder::delay()` no longer sleep. The workflow ends the + call in `WAITING`; call `$engine->resumeDue()` regularly (a cron job or scheduler, every minute) + to continue workflows whose delay has passed. With workflow-engine-laravel v2 the + `workflow:resume-due` command is scheduled for you. +2. **Timeouts.** Step timeouts (`timeout`, `#[Timeout]`) are no longer enforced with SIGALRM. + Enforce them in your queue worker, or, in a CLI worker that runs one workflow at a time: + + ```php + $engine = new WorkflowEngine($storage, $events, $logger, signalTimeouts: true); + ``` +3. **Your own `StorageAdapter`.** `save()` must be a compare-and-swap on the revision: + + ```php + public function save(WorkflowInstance $instance): void + { + $expected = $instance->getRevision(); // 0: never saved + // write only if the stored revision is $expected (UPDATE ... WHERE revision = ?), + // otherwise: throw new ConcurrentModificationException($id, $expected, $stored); + // store $instance->toArray() (it now includes `wait` and `revision`) and the definition + $instance->setRevision($expected + 1); + } + ``` + + `findInstances()` should support `due_before` (WAITING instances whose + `getWait()->resumeAt` is at or before it). `InMemoryStorage` is a reference implementation. +4. **Conflicts.** Code that saves instances can now get `ConcurrentModificationException`. Load the + instance again and repeat; `signal()` and `resumeDue()` are safe to repeat. +5. **Suspended instances.** `resume()` throws for an instance waiting for a signal; deliver it with + `signal()`. `ActionResult::isFailure()` is false for a suspended result. +6. **In-memory tests.** `InMemoryStorage::load()` returns a new copy each time; do not rely on + getting the same object back. diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 9f6ff17..50bce9c 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,9 +1,5 @@ parameters: - level: 6 + level: 9 paths: - src tmpDir: build/phpstan - ignoreErrors: - - '#has no value type specified in iterable type array#' - - '#PHPDoc tag @param for parameter .+ with type .+ is not subtype of native type#' - - '#Parameter .+ has invalid type#' diff --git a/src/Actions/ConditionAction.php b/src/Actions/ConditionAction.php index bf3ab9f..62a6566 100644 --- a/src/Actions/ConditionAction.php +++ b/src/Actions/ConditionAction.php @@ -51,6 +51,10 @@ protected function doExecute(WorkflowContext $context): ActionResult return ActionResult::failure('Condition is required'); } + if (! is_string($condition)) { + return ActionResult::failure('Condition must be a string expression'); + } + try { $result = $this->evaluateCondition($condition, $context->getData()); @@ -67,11 +71,6 @@ protected function doExecute(WorkflowContext $context): ActionResult } } - /** - * Enhanced condition evaluation with PHP 8.3+ match expressions - * - * @param array $data - */ /** * Evaluate a condition expression against workflow data. * diff --git a/src/Actions/DelayAction.php b/src/Actions/DelayAction.php index c9a9fe4..4c6a063 100644 --- a/src/Actions/DelayAction.php +++ b/src/Actions/DelayAction.php @@ -3,10 +3,12 @@ namespace SolutionForest\WorkflowEngine\Actions; use SolutionForest\WorkflowEngine\Core\ActionResult; +use SolutionForest\WorkflowEngine\Core\Wait; use SolutionForest\WorkflowEngine\Core\WorkflowContext; /** - * A delay action that can be used to pause workflow execution + * Pauses the workflow for a time without holding a process: it suspends until + * WorkflowEngine::resumeDue() runs after the time has passed */ class DelayAction extends BaseAction { @@ -17,7 +19,7 @@ public function getName(): string public function getDescription(): string { - return 'Adds a delay to workflow execution'; + return 'Waits for a time, then continues'; } protected function doExecute(WorkflowContext $context): ActionResult @@ -55,14 +57,22 @@ protected function doExecute(WorkflowContext $context): ActionResult $totalMicroseconds = $units['seconds']; } - if ($totalMicroseconds > 0) { - usleep((int) $totalMicroseconds); - } - - return ActionResult::success([ + // v3: a delay no longer sleeps in the process. The workflow suspends and + // WorkflowEngine::resumeDue() resumes it once the time has passed. A zero delay + // completes at once. + $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + $data = [ 'delayed_seconds' => $totalMicroseconds / 1_000_000, 'delayed_microseconds' => (int) $totalMicroseconds, - 'delayed_at' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('c'), - ]); + 'delayed_at' => $now->format('c'), + ]; + + if ($totalMicroseconds <= 0) { + return ActionResult::success($data); + } + + $resumeAt = $now->modify('+'.(int) $totalMicroseconds.' microseconds'); + + return ActionResult::suspend(Wait::TIMER, $resumeAt, $data + ['resume_at' => $resumeAt->format('c')]); } } diff --git a/src/Actions/HttpAction.php b/src/Actions/HttpAction.php index 4b6e8e1..1f23141 100644 --- a/src/Actions/HttpAction.php +++ b/src/Actions/HttpAction.php @@ -34,18 +34,56 @@ public function getDescription(): string protected function doExecute(WorkflowContext $context): ActionResult { $url = $this->getConfig('url'); - $method = strtoupper($this->getConfig('method', 'GET')); + $method = $this->getConfig('method', 'GET'); $data = $this->getConfig('data', []); $headers = $this->getConfig('headers', []); - $timeout = (int) $this->getConfig('timeout', 30); - $connectTimeout = (int) $this->getConfig('connect_timeout', min(10, $timeout)); - $verifyTls = (bool) $this->getConfig('verify_tls', true); - $maxRedirects = (int) $this->getConfig('max_redirects', 3); if (! $url) { return ActionResult::failure('URL is required for HTTP action'); } + if (! is_string($url)) { + return ActionResult::failure('HTTP action "url" must be a string'); + } + + if (! is_string($method) || $method === '') { + return ActionResult::failure('HTTP action "method" must be a non-empty string'); + } + + if (! is_array($data)) { + return ActionResult::failure('HTTP action "data" must be an array'); + } + + if (! is_array($headers)) { + return ActionResult::failure('HTTP action "headers" must be an array'); + } + + $headerLines = []; + foreach ($headers as $name => $value) { + if (! is_scalar($value)) { + return ActionResult::failure("HTTP action header \"{$name}\" must be a scalar value"); + } + $headerLines[$name] = $value; + } + + $timeout = $this->intConfig('timeout', 30); + if ($timeout === null) { + return ActionResult::failure('HTTP action "timeout" must be an integer'); + } + + $connectTimeout = $this->intConfig('connect_timeout', min(10, $timeout)); + if ($connectTimeout === null) { + return ActionResult::failure('HTTP action "connect_timeout" must be an integer'); + } + + $maxRedirects = $this->intConfig('max_redirects', 3); + if ($maxRedirects === null) { + return ActionResult::failure('HTTP action "max_redirects" must be an integer'); + } + + $verifyTls = (bool) $this->getConfig('verify_tls', true); + $method = strtoupper($method); + // ext-curl is a suggested, not required, dependency: report its absence // as a normal step failure rather than a fatal "undefined function". if (! function_exists('curl_init')) { @@ -58,6 +96,10 @@ protected function doExecute(WorkflowContext $context): ActionResult $url = $this->processTemplate($url, $context->getData()); $data = $this->processArrayTemplates($data, $context->getData()); + if ($url === '') { + return ActionResult::failure('URL is required for HTTP action'); + } + try { // Initialize cURL $ch = curl_init(); @@ -91,17 +133,17 @@ protected function doExecute(WorkflowContext $context): ActionResult if ($method !== 'GET') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if (! empty($data)) { - $jsonData = json_encode($data); + $jsonData = json_encode($data, JSON_THROW_ON_ERROR); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); - $headers['Content-Type'] = 'application/json'; - $headers['Content-Length'] = strlen($jsonData); + $headerLines['Content-Type'] = 'application/json'; + $headerLines['Content-Length'] = strlen($jsonData); } } // Set headers - if (! empty($headers)) { + if ($headerLines !== []) { $headerArray = []; - foreach ($headers as $key => $value) { + foreach ($headerLines as $key => $value) { $headerArray[] = "{$key}: {$value}"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); @@ -125,7 +167,7 @@ protected function doExecute(WorkflowContext $context): ActionResult $error = curl_error($ch); curl_close($ch); - if ($responseBody === false || $error) { + if (! is_string($responseBody) || $error !== '') { return ActionResult::failure( 'HTTP request failed: '.($error ?: 'unknown cURL error'), [ @@ -180,15 +222,71 @@ protected function doExecute(WorkflowContext $context): ActionResult */ private function processTemplate(string $template, array $data): string { - return preg_replace_callback('/\{\{\s*([^}]+)\s*\}\}/', function ($matches) use ($data) { - return Arr::get($data, trim($matches[1]), $matches[0]); + $processed = preg_replace_callback('/\{\{\s*([^}]+)\s*\}\}/', function (array $matches) use ($data): string { + return $this->stringify(Arr::get($data, trim($matches[1]), $matches[0])); }, $template); + + // preg_replace_callback() only returns null on a PCRE failure (e.g. the + // backtrack limit); leave the template untouched rather than blank it. + return $processed ?? $template; + } + + /** + * Render a resolved template value the way string interpolation would: + * scalars as PHP casts them, null as an empty string, and anything else + * (arrays, objects) as JSON. + */ + private function stringify(mixed $value): string + { + if (is_string($value)) { + return $value; + } + + if (is_scalar($value)) { + return (string) $value; + } + + if ($value === null) { + return ''; + } + + if ($value instanceof \Stringable) { + return (string) $value; + } + + return json_encode($value) ?: ''; + } + + /** + * Read an integer option, accepting integer-like strings and floats. + * + * Returns null when the configured value is not an integer, so the caller + * can fail the step with a clear message instead of silently using 0. + */ + private function intConfig(string $key, int $default): ?int + { + $value = $this->getConfig($key, $default); + + if (is_int($value)) { + return $value; + } + + if (is_string($value) && preg_match('/^-?\d+$/', $value) === 1) { + return (int) $value; + } + + // Fractional seconds were always truncated; keep doing that. + if (is_float($value)) { + return (int) $value; + } + + return null; } /** - * @param array $array + * @param array $array * @param array $data - * @return array + * @return array */ private function processArrayTemplates(array $array, array $data): array { diff --git a/src/Actions/LogAction.php b/src/Actions/LogAction.php index 00c42e5..a4dd87e 100644 --- a/src/Actions/LogAction.php +++ b/src/Actions/LogAction.php @@ -25,6 +25,14 @@ protected function doExecute(WorkflowContext $context): ActionResult $message = $this->getConfig('message', 'Default log message'); $level = $this->getConfig('level', 'info'); + if (! is_string($message)) { + return ActionResult::failure('Log "message" must be a string'); + } + + if (! is_string($level)) { + return ActionResult::failure('Log "level" must be a string'); + } + // Replace placeholders in message with workflow data $processedMessage = $this->processMessage($message, $context->getData()); @@ -49,11 +57,15 @@ protected function doExecute(WorkflowContext $context): ActionResult private function processMessage(string $message, array $data): string { // Simple placeholder replacement: {key.subkey} - return preg_replace_callback('/\{([^}]+)\}/', function ($matches) use ($data) { + $processed = preg_replace_callback('/\{([^}]+)\}/', function (array $matches) use ($data): string { $key = $matches[1]; $value = parent::getNestedValue($data, $key, $matches[0]); // Keep placeholder if key not found - return is_scalar($value) ? (string) $value : json_encode($value); + return is_scalar($value) ? (string) $value : (json_encode($value) ?: ''); }, $message); + + // preg_replace_callback() only returns null on a PCRE failure (e.g. the + // backtrack limit); log the raw message rather than an empty one. + return $processed ?? $message; } } diff --git a/src/Contracts/StorageAdapter.php b/src/Contracts/StorageAdapter.php index 2e086e5..0f17aac 100644 --- a/src/Contracts/StorageAdapter.php +++ b/src/Contracts/StorageAdapter.php @@ -3,11 +3,20 @@ namespace SolutionForest\WorkflowEngine\Contracts; use SolutionForest\WorkflowEngine\Core\WorkflowInstance; +use SolutionForest\WorkflowEngine\Exceptions\ConcurrentModificationException; interface StorageAdapter { /** - * Save a workflow instance + * Save a workflow instance, as one compare-and-swap on its revision. + * + * The stored revision must equal $instance->getRevision() (0 when the instance was + * never saved); otherwise someone saved it since this copy was loaded, and the + * adapter writes nothing and throws ConcurrentModificationException. On success it + * stores the instance, including getWait() and the definition, and calls + * $instance->setRevision($stored + 1). + * + * @throws ConcurrentModificationException */ public function save(WorkflowInstance $instance): void; @@ -19,6 +28,10 @@ public function load(string $id): WorkflowInstance; /** * Find workflow instances by criteria * + * Adapters support at least `state`, `definition_name`, `limit`, `offset` and + * `due_before` (a DateTimeInterface: WAITING instances whose wait has a resume time + * at or before it; WorkflowEngine::resumeDue() uses it). + * * @param array $criteria * @return array */ diff --git a/src/Core/ActionResolver.php b/src/Core/ActionResolver.php index 9d00fc7..d9c557f 100644 --- a/src/Core/ActionResolver.php +++ b/src/Core/ActionResolver.php @@ -327,7 +327,8 @@ class_exists($actionName); private static function normalizeActionName(string $actionName): string { // Convert to snake_case first, then to PascalCase - $snakeCase = strtolower(preg_replace('/[A-Z]/', '_$0', $actionName)); + // preg_replace() only returns null on a PCRE failure; fall back to the raw name. + $snakeCase = strtolower(preg_replace('/[A-Z]/', '_$0', $actionName) ?? $actionName); $snakeCase = str_replace(['-', ' '], '_', $snakeCase); $snakeCase = trim($snakeCase, '_'); diff --git a/src/Core/ActionResult.php b/src/Core/ActionResult.php index 19006df..e7a7f64 100644 --- a/src/Core/ActionResult.php +++ b/src/Core/ActionResult.php @@ -87,8 +87,13 @@ public function __construct( private readonly bool $success, private readonly ?string $errorMessage = null, private readonly array $data = [], - private readonly array $metadata = [] - ) {} + private readonly array $metadata = [], + private readonly ?Suspension $suspension = null, + ) { + if ($suspension !== null && ($success || $errorMessage !== null)) { + throw new \LogicException('A suspended result is neither a success nor a failure.'); + } + } /** * Create a successful action result. @@ -117,7 +122,7 @@ public function __construct( * ); * ``` */ - public static function success(array $data = [], array $metadata = []): static + public static function success(array $data = [], array $metadata = []): self { return new self(true, null, $data, $metadata); } @@ -149,11 +154,42 @@ public static function success(array $data = [], array $metadata = []): static * ); * ``` */ - public static function failure(string $errorMessage, array $metadata = []): static + public static function failure(string $errorMessage, array $metadata = []): self { return new self(false, $errorMessage, [], $metadata); } + /** + * The step is not finished yet: the workflow waits, without holding a process, until + * WorkflowEngine::signal() delivers $for, or until $resumeAt passes, whichever is first. + * Use Wait::TIMER as $for to wait for the time only. $data is merged into the workflow + * data now, as with success(). + * + * Example: an approval step notifies the approvers and returns suspend('approved'). + * + * @param array $data + * @param array $metadata + */ + public static function suspend(string $for, ?\DateTimeInterface $resumeAt = null, array $data = [], array $metadata = []): self + { + return new self(false, null, $data, $metadata, new Suspension( + $for, + $resumeAt === null ? null : \DateTimeImmutable::createFromInterface($resumeAt), + )); + } + + /** Whether the step asked to wait (see suspend()). */ + public function isSuspended(): bool + { + return $this->suspension !== null; + } + + /** What the step waits for, when suspended. */ + public function getSuspension(): ?Suspension + { + return $this->suspension; + } + /** * Check if the action execution was successful. * @@ -188,7 +224,7 @@ public function isSuccess(): bool */ public function isFailure(): bool { - return ! $this->success; + return ! $this->success && $this->suspension === null; } /** @@ -296,7 +332,8 @@ public function withMetadata(array $metadata): static $this->success, $this->errorMessage, $this->data, - array_merge($this->metadata, $metadata) + array_merge($this->metadata, $metadata), + $this->suspension, ); } @@ -349,6 +386,7 @@ public function toArray(): array 'error_message' => $this->errorMessage, 'data' => $this->data, 'metadata' => $this->metadata, + 'suspended' => $this->suspension?->toArray(), ]; } @@ -402,8 +440,8 @@ public function get(string $key, $default = null) */ public function mergeData(array $additionalData): self { - if ($this->isFailure()) { - throw new \LogicException('Cannot merge data on a failed ActionResult'); + if (! $this->success) { + throw new \LogicException('Cannot merge data on a failed or suspended ActionResult'); } return self::success( diff --git a/src/Core/DefinitionParser.php b/src/Core/DefinitionParser.php index e7d1b2c..1187d44 100644 --- a/src/Core/DefinitionParser.php +++ b/src/Core/DefinitionParser.php @@ -3,6 +3,7 @@ namespace SolutionForest\WorkflowEngine\Core; use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowDefinitionException; +use SolutionForest\WorkflowEngine\Support\Arr; /** * Parses and validates workflow definitions from various formats. @@ -127,14 +128,18 @@ public function parse(array|string $definition): WorkflowDefinition ['JSON parsing failed with error code: '.json_last_error()] ); } + if (! is_array($decoded) || ! Arr::isStringKeyed($decoded)) { + throw new InvalidWorkflowDefinitionException( + 'Invalid JSON workflow definition: the document must be a JSON object', + ['raw_definition' => substr($definition, 0, 200)], + ['Expected a JSON object at the top level, got: '.get_debug_type($decoded)] + ); + } $definition = $decoded; } - // Validate the complete definition structure - $this->validateDefinition($definition); - - // Normalize steps before creating WorkflowDefinition - $definition['steps'] = $this->normalizeSteps($definition['steps']); + // Validate the complete definition structure; steps come back normalized + $definition['steps'] = $this->validateDefinition($definition); return WorkflowDefinition::fromArray($definition); } @@ -147,12 +152,13 @@ public function parse(array|string $definition): WorkflowDefinition * Throws detailed exceptions with context for any validation failures. * * @param array $definition The workflow definition to validate + * @return array> The validated steps, normalized and keyed by ID * * @throws InvalidWorkflowDefinitionException If any validation rules fail * * @internal Called during definition parsing */ - private function validateDefinition(array $definition): void + private function validateDefinition(array $definition): array { // Validate required name field if (! isset($definition['name'])) { @@ -160,7 +166,7 @@ private function validateDefinition(array $definition): void } if (! is_string($definition['name']) || empty(trim($definition['name']))) { - throw InvalidWorkflowDefinitionException::invalidName($definition['name']); + throw InvalidWorkflowDefinitionException::invalidName(Arr::describe($definition['name'])); } // Validate required steps field @@ -191,6 +197,14 @@ private function validateDefinition(array $definition): void // Validate transitions if present if (isset($definition['transitions']) && is_array($definition['transitions'])) { foreach ($definition['transitions'] as $transitionIndex => $transition) { + if (! is_array($transition) || ! Arr::isStringKeyed($transition)) { + throw new InvalidWorkflowDefinitionException( + "Transition at index {$transitionIndex} must be an array with 'from' and 'to' fields", + ['transition' => $transition, 'available_steps' => array_keys($steps)], + ['Expected an associative array for transition, got: '.get_debug_type($transition)] + ); + } + $this->validateTransition($transition, $steps, $transitionIndex); } @@ -214,6 +228,8 @@ private function validateDefinition(array $definition): void ['Expected array for metadata field, got: '.gettype($definition['metadata'])] ); } + + return $steps; } /** @@ -225,7 +241,7 @@ private function validateDefinition(array $definition): void * orphaned branch — so an unreachable step is rejected at parse time. * * @param array> $steps Normalized steps keyed by ID - * @param array $transitions Raw transition list + * @param array $transitions Raw transition list * @param array $definition The full definition, for error context * * @throws InvalidWorkflowDefinitionException If any step is unreachable @@ -240,12 +256,16 @@ private function validateReachability(array $steps, array $transitions, array $d $hasIncoming = []; foreach ($transitions as $transition) { - if (! is_array($transition) || ! isset($transition['from'], $transition['to'])) { - continue; // Already reported by validateTransition(). + if (! is_array($transition)) { + continue; // Already reported by validateDefinition(). } - $from = (string) $transition['from']; - $to = (string) $transition['to']; + $from = $transition['from'] ?? null; + $to = $transition['to'] ?? null; + + if (! is_string($from) || ! is_string($to)) { + continue; // Already reported by validateTransition(). + } $outgoing[$from][] = $to; $hasIncoming[$to] = true; @@ -309,7 +329,7 @@ private function validateReachability(array $steps, array $transitions, array $d * where step IDs are keys and step configurations are values. Handles both * sequential arrays with 'id' properties and pre-normalized associative arrays. * - * @param array $steps Raw steps array in various formats + * @param array $steps Raw steps array in various formats * @return array> Normalized steps indexed by ID * * @throws InvalidWorkflowDefinitionException If step structure is invalid @@ -333,14 +353,8 @@ private function validateReachability(array $steps, array $transitions, array $d */ private function normalizeSteps(array $steps): array { - // If steps is already associative, return as-is - if (! array_is_list($steps)) { - // Type hint: already associative array with string keys - /** @var array> $steps */ - return $steps; - } + $isList = array_is_list($steps); - // Convert sequential array with 'id' property to associative $normalizedSteps = []; foreach ($steps as $index => $step) { if (! is_array($step)) { @@ -351,6 +365,26 @@ private function normalizeSteps(array $steps): array ); } + if (! Arr::isStringKeyed($step)) { + throw new InvalidWorkflowDefinitionException( + "Step at index {$index} must be an associative array of step fields", + ['step_data' => $step, 'step_index' => $index], + ["Step {$index} contains non-string keys; expected fields such as 'action' and 'parameters'"] + ); + } + + // Already associative: the key is the step ID + if (! $isList) { + if (! is_string($index)) { + throw InvalidWorkflowDefinitionException::invalidStepId((string) $index); + } + + $normalizedSteps[$index] = $step; + + continue; + } + + // Sequential array: the step ID comes from its 'id' property if (! isset($step['id'])) { throw new InvalidWorkflowDefinitionException( "Step at index {$index} must have an 'id' property when using sequential array format", @@ -361,7 +395,7 @@ private function normalizeSteps(array $steps): array $stepId = $step['id']; if (! is_string($stepId) || empty(trim($stepId))) { - throw InvalidWorkflowDefinitionException::invalidStepId($stepId); + throw InvalidWorkflowDefinitionException::invalidStepId(Arr::describe($stepId)); } // Check for duplicate step IDs @@ -449,7 +483,7 @@ private function validateStep(string $stepId, array $stepData, array $fullDefini "Step '{$stepId}' has invalid timeout format. Expected format: number followed by s/m/h/d (e.g., '30s', '5m')", $fullDefinition, [ - "Invalid timeout: {$stepData['timeout']}", + 'Invalid timeout: '.Arr::describe($stepData['timeout']), 'Valid formats: "30s", "5m", "2h", "1d"', ] ); @@ -458,7 +492,15 @@ private function validateStep(string $stepId, array $stepData, array $fullDefini // Validate retry attempts if (isset($stepData['retry_attempts'])) { - if (! is_int($stepData['retry_attempts']) || $stepData['retry_attempts'] < 0) { + if (! is_int($stepData['retry_attempts'])) { + throw new InvalidWorkflowDefinitionException( + "Step '{$stepId}' retry_attempts must be an integer", + $fullDefinition, + ['Expected integer for retry_attempts in step '.$stepId.', got: '.get_debug_type($stepData['retry_attempts'])] + ); + } + + if ($stepData['retry_attempts'] < 0) { throw InvalidWorkflowDefinitionException::invalidRetryAttempts($stepData['retry_attempts']); } } @@ -484,7 +526,7 @@ private function validateStep(string $stepId, array $stepData, array $fullDefini foreach ($stepData['conditions'] as $conditionIndex => $condition) { if (! is_string($condition) || empty(trim($condition))) { - throw InvalidWorkflowDefinitionException::invalidCondition($condition, 'Condition cannot be empty.'); + throw InvalidWorkflowDefinitionException::invalidCondition(Arr::describe($condition), 'Condition cannot be empty.'); } } } @@ -499,7 +541,7 @@ private function validateStep(string $stepId, array $stepData, array $fullDefini * * @param array $transition The transition definition to validate * @param array> $steps Available workflow steps - * @param int $transitionIndex Index of transition for error context + * @param int|string $transitionIndex Index of transition for error context * * @throws InvalidWorkflowDefinitionException If transition is invalid * @@ -525,7 +567,7 @@ private function validateStep(string $stepId, array $stepData, array $fullDefini * * @internal Called during definition validation */ - private function validateTransition(array $transition, array $steps, int $transitionIndex): void + private function validateTransition(array $transition, array $steps, int|string $transitionIndex): void { // Validate required 'from' field if (! isset($transition['from'])) { @@ -600,7 +642,7 @@ private function validateTransition(array $transition, array $steps, int $transi // Validate optional condition field if (isset($transition['condition'])) { if (! is_string($transition['condition']) || empty(trim($transition['condition']))) { - throw InvalidWorkflowDefinitionException::invalidCondition($transition['condition'], 'Condition cannot be empty.'); + throw InvalidWorkflowDefinitionException::invalidCondition(Arr::describe($transition['condition']), 'Condition cannot be empty.'); } } diff --git a/src/Core/Executor.php b/src/Core/Executor.php index c10d28e..66e4eff 100644 --- a/src/Core/Executor.php +++ b/src/Core/Executor.php @@ -10,7 +10,11 @@ use SolutionForest\WorkflowEngine\Events\StepRetriedEvent; use SolutionForest\WorkflowEngine\Events\WorkflowCompletedEvent; use SolutionForest\WorkflowEngine\Events\WorkflowFailedEvent; +use SolutionForest\WorkflowEngine\Events\WorkflowResumedEvent; +use SolutionForest\WorkflowEngine\Events\WorkflowSuspendedEvent; use SolutionForest\WorkflowEngine\Exceptions\ActionNotFoundException; +use SolutionForest\WorkflowEngine\Exceptions\ConcurrentModificationException; +use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowStateException; use SolutionForest\WorkflowEngine\Exceptions\StepExecutionException; use SolutionForest\WorkflowEngine\Support\NullEventDispatcher; use SolutionForest\WorkflowEngine\Support\NullLogger; @@ -88,7 +92,8 @@ class Executor public function __construct( StateManager $stateManager, ?EventDispatcher $eventDispatcher = null, - ?Logger $logger = null + ?Logger $logger = null, + private readonly bool $signalTimeouts = false, ) { $this->stateManager = $stateManager; $this->eventDispatcher = $eventDispatcher ?? new NullEventDispatcher; @@ -120,6 +125,9 @@ public function execute(WorkflowInstance $instance): void { try { $this->processWorkflow($instance); + } catch (ConcurrentModificationException $e) { + // Someone else advanced the instance; nothing failed. The caller reloads and retries. + throw $e; } catch (\Throwable $e) { $this->logger->error('Workflow execution failed', [ 'workflow_id' => $instance->getId(), @@ -166,8 +174,89 @@ public function execute(WorkflowInstance $instance): void * @throws StepExecutionException If step execution fails * @throws ActionNotFoundException If required action classes are missing */ + /** + * Finish the suspended step of $instance because $signal arrived (or Wait::TIMER, when its + * time passed), then carry on with the next steps. + * + * What resumed it is kept in the workflow data under `steps.`: `resumed_by` + * (the signal name), `payload` and `resumed_at`, so later conditions can branch on it, + * for example `steps.approve.payload.decision === "approved"`. + * + * @param array $payload + * + * @throws InvalidWorkflowStateException If the instance is not waiting for $signal + */ + public function resumeWait(WorkflowInstance $instance, string $signal, array $payload = []): void + { + $wait = $instance->getWait(); + if ($wait === null || $instance->getState() !== WorkflowState::WAITING) { + throw new InvalidWorkflowStateException( + "Workflow '{$instance->getId()}' is not waiting for anything", + $instance->getState(), + WorkflowState::RUNNING, + $instance->getId() + ); + } + if ($signal !== $wait->for && $signal !== Wait::TIMER) { + throw new InvalidWorkflowStateException( + "Workflow '{$instance->getId()}' waits for '{$wait->for}' in step '{$wait->stepId}', not for '{$signal}'", + $instance->getState(), + WorkflowState::RUNNING, + $instance->getId() + ); + } + if ($signal === Wait::TIMER && $wait->resumeAt === null) { + throw new InvalidWorkflowStateException( + "Workflow '{$instance->getId()}' waits for '{$wait->for}' with no time limit", + $instance->getState(), + WorkflowState::RUNNING, + $instance->getId() + ); + } + $step = $instance->getDefinition()->getStep($wait->stepId) + ?? throw new InvalidWorkflowStateException( + "Workflow '{$instance->getId()}' waits in step '{$wait->stepId}', which its definition does not have", + $instance->getState(), + WorkflowState::RUNNING, + $instance->getId() + ); + + $data = $instance->getData(); + $steps = is_array($data['steps'] ?? null) ? $data['steps'] : []; + $steps[$wait->stepId] = [ + 'resumed_by' => $signal, + 'payload' => $payload, + 'resumed_at' => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(\DateTimeInterface::ATOM), + ]; + $data['steps'] = $steps; + $instance->setData($data); + $instance->setWait(null); + $this->stateManager->markStepCompleted($instance, $wait->stepId); + + $this->eventDispatcher->dispatch(new WorkflowResumedEvent($instance, $step, $wait, $signal, $payload)); + $this->eventDispatcher->dispatch(new StepCompletedEvent($instance, $step)); + $this->logger->info('Workflow resumed', [ + 'workflow_id' => $instance->getId(), + 'step_id' => $wait->stepId, + 'signal' => $signal, + ]); + + $this->execute($instance); + } + private function processWorkflow(WorkflowInstance $instance): void { + // A suspended step finishes only through resumeWait(): running the workflow again + // would run that step's action a second time. + if ($instance->isSuspended()) { + throw new InvalidWorkflowStateException( + "Workflow '{$instance->getId()}' waits for '{$instance->getWait()?->for}'; deliver it with WorkflowEngine::signal()", + $instance->getState(), + WorkflowState::RUNNING, + $instance->getId() + ); + } + // If workflow is not running, transition it to running. FAILED is // included so that resuming a failed workflow actually retries it // instead of executing steps while still marked failed (which would @@ -229,7 +318,9 @@ private function processWorkflow(WorkflowInstance $instance): void continue; // Skip steps that can't be executed yet } - $this->executeStep($instance, $step); + if ($this->executeStep($instance, $step)) { + return; // the step suspended the workflow + } $progressed = true; } @@ -268,7 +359,7 @@ private function processWorkflow(WorkflowInstance $instance): void * @throws StepExecutionException If the step fails to execute * @throws ActionNotFoundException If the action class doesn't exist */ - private function executeStep(WorkflowInstance $instance, Step $step): void + private function executeStep(WorkflowInstance $instance, Step $step): bool { // Evaluate step conditions. Steps whose conditions don't match the current // workflow data are skipped (marked completed without running the action) @@ -283,7 +374,7 @@ private function executeStep(WorkflowInstance $instance, Step $step): void $instance->setCurrentStepId($step->getId()); $this->stateManager->markStepCompleted($instance, $step->getId()); - return; + return false; } $this->logger->info('Executing workflow step', [ @@ -298,8 +389,26 @@ private function executeStep(WorkflowInstance $instance, Step $step): void $this->stateManager->save($instance); try { - if ($step->hasAction()) { - $this->executeActionWithRetry($instance, $step); + $suspension = $step->hasAction() ? $this->executeActionWithRetry($instance, $step) : null; + if ($suspension !== null) { + $wait = new Wait( + $step->getId(), + $suspension->for, + $suspension->resumeAt, + new \DateTimeImmutable('now', new \DateTimeZone('UTC')), + ); + $instance->setWait($wait); + $instance->setState(WorkflowState::WAITING); + $this->stateManager->save($instance); + $this->eventDispatcher->dispatch(new WorkflowSuspendedEvent($instance, $step, $wait)); + $this->logger->info('Workflow step suspended', [ + 'workflow_id' => $instance->getId(), + 'step_id' => $step->getId(), + 'waits_for' => $wait->for, + 'resume_at' => $wait->resumeAt?->format(\DateTimeInterface::ATOM), + ]); + + return true; } // Mark step as completed @@ -310,6 +419,8 @@ private function executeStep(WorkflowInstance $instance, Step $step): void 'workflow_id' => $instance->getId(), 'step_id' => $step->getId(), ]); + + return false; } catch (\Throwable $e) { $context = new WorkflowContext( workflowId: $instance->getId(), @@ -359,22 +470,18 @@ private function executeStep(WorkflowInstance $instance, Step $step): void */ private const MAX_BACKOFF_MICROSECONDS = 2_000_000; // 2 seconds - private function executeActionWithRetry(WorkflowInstance $instance, Step $step): void + private function executeActionWithRetry(WorkflowInstance $instance, Step $step): ?Suspension { $maxAttempts = $step->getRetryAttempts() + 1; // +1 for initial attempt if ($maxAttempts <= 1) { // No retries configured, execute directly - $this->executeAction($instance, $step); - - return; + return $this->executeAction($instance, $step); } for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) { try { - $this->executeAction($instance, $step); - - return; // Success — exit retry loop + return $this->executeAction($instance, $step); // Success (or suspended) — exit retry loop } catch (\Throwable $e) { if ($attempt === $maxAttempts) { $this->logger->error('Step failed after all retry attempts', [ @@ -410,6 +517,8 @@ private function executeActionWithRetry(WorkflowInstance $instance, Step $step): usleep($backoffMicroseconds); } } + + return null; } /** @@ -490,10 +599,16 @@ private function executeWithTimeout(callable $callback, int $timeoutSeconds): mi * @throws ActionNotFoundException If the action class doesn't exist or implement the interface * @throws StepExecutionException If action execution fails */ - private function executeAction(WorkflowInstance $instance, Step $step): void + private function executeAction(WorkflowInstance $instance, Step $step): ?Suspension { $actionClass = $step->getActionClass(); + // A step without an action has nothing to execute (callers already + // guard on hasAction(); this keeps the method total). + if ($actionClass === null) { + return null; + } + if (! class_exists($actionClass)) { $context = new WorkflowContext( workflowId: $instance->getId(), @@ -528,7 +643,10 @@ private function executeAction(WorkflowInstance $instance, Step $step): void instance: $instance ); - $timeoutValue = $step->getTimeout(); + // Timeouts by SIGALRM are only safe in a CLI worker that runs one workflow at a time; + // elsewhere (web requests, FrankenPHP / Octane workers) the adapter enforces them, for + // example with the queue job's timeout. + $timeoutValue = $this->signalTimeouts ? $step->getTimeout() : null; if ($timeoutValue !== null) { $timeoutSeconds = Timeout::toSeconds($timeoutValue); $result = $this->executeWithTimeout( @@ -539,18 +657,24 @@ private function executeAction(WorkflowInstance $instance, Step $step): void $result = $action->execute($context); } - if ($result->isSuccess()) { + if (! $result instanceof ActionResult) { + throw StepExecutionException::actionFailed('The action did not return an ActionResult', $step, $context); + } + + if ($result->isSuccess() || $result->isSuspended()) { // Merge any output data from the action if ($result->hasData()) { $instance->mergeData($result->getData()); $this->stateManager->save($instance); } - } else { - throw StepExecutionException::actionFailed( - $result->getErrorMessage() ?? 'Action execution failed without specific error message', - $step, - $context - ); + + return $result->getSuspension(); } + + throw StepExecutionException::actionFailed( + $result->getErrorMessage() ?? 'Action execution failed without specific error message', + $step, + $context + ); } } diff --git a/src/Core/Suspension.php b/src/Core/Suspension.php new file mode 100644 index 0000000..c907c03 --- /dev/null +++ b/src/Core/Suspension.php @@ -0,0 +1,27 @@ + $this->for, 'resume_at' => $this->resumeAt?->format(\DateTimeInterface::ATOM)]; + } +} diff --git a/src/Core/Wait.php b/src/Core/Wait.php new file mode 100644 index 0000000..ed85375 --- /dev/null +++ b/src/Core/Wait.php @@ -0,0 +1,71 @@ +resumeAt !== null && $this->resumeAt <= $now; + } + + /** @return array{step_id: string, for: string, resume_at: string|null, since: string} */ + public function toArray(): array + { + return [ + 'step_id' => $this->stepId, + 'for' => $this->for, + 'resume_at' => $this->resumeAt?->format(\DateTimeInterface::ATOM), + 'since' => $this->since->format(\DateTimeInterface::ATOM), + ]; + } + + /** @param array $data */ + public static function fromArray(array $data): self + { + $stepId = $data['step_id'] ?? null; + $for = $data['for'] ?? null; + $resumeAt = $data['resume_at'] ?? null; + $since = $data['since'] ?? null; + if (! is_string($stepId) || ! is_string($for) || ! is_string($since) || ($resumeAt !== null && ! is_string($resumeAt))) { + throw new InvalidWorkflowStateException( + 'Cannot restore a wait: step_id, for and since must be strings, resume_at a string or null.', + WorkflowState::WAITING, + WorkflowState::WAITING, + '', + ); + } + + return new self($stepId, $for, $resumeAt === null ? null : new \DateTimeImmutable($resumeAt), new \DateTimeImmutable($since)); + } +} diff --git a/src/Core/WorkflowBuilder.php b/src/Core/WorkflowBuilder.php index d7a8229..9350a03 100644 --- a/src/Core/WorkflowBuilder.php +++ b/src/Core/WorkflowBuilder.php @@ -58,10 +58,10 @@ final class WorkflowBuilder /** @var string Human-readable workflow description */ private string $description = ''; - /** @var array> Array of step configurations */ + /** @var list, timeout: string|int|null, retry_attempts: int, conditions?: list}> Array of step configurations */ private array $steps = []; - /** @var array> Array of step transitions */ + /** @var list Array of step transitions */ private array $transitions = []; /** @var array Additional workflow metadata */ @@ -155,7 +155,7 @@ public function version(string $version): self * @param string $id Unique step identifier within the workflow * @param string|WorkflowAction $action Action class name or instance * @param array $config Step-specific configuration parameters - * @param int|null $timeout Maximum execution time in seconds + * @param string|int|null $timeout Maximum execution time (seconds, or a string such as "30s") * @param int $retryAttempts Number of retry attempts on failure (0-10) * @return $this For method chaining * @@ -231,7 +231,7 @@ public function addStep( * * @param string|WorkflowAction $action Action class name or instance * @param array $config Step-specific configuration parameters - * @param int|null $timeout Maximum execution time in seconds + * @param string|int|null $timeout Maximum execution time (seconds, or a string such as "30s") * @param int $retryAttempts Number of retry attempts on failure * @return $this For method chaining * @@ -254,7 +254,7 @@ public function startWith( * * @param string|WorkflowAction $action Action class name or instance * @param array $config Step-specific configuration parameters - * @param int|null $timeout Maximum execution time in seconds + * @param string|int|null $timeout Maximum execution time (seconds, or a string such as "30s") * @param int $retryAttempts Number of retry attempts on failure * @return $this For method chaining * @@ -508,14 +508,7 @@ public function build(): WorkflowDefinition $steps = []; foreach ($this->steps as $stepData) { // Convert timeout to string format for Step object - keep original format if string, convert integer to string - $timeoutString = null; - if ($stepData['timeout'] !== null) { - if (is_string($stepData['timeout'])) { - $timeoutString = $stepData['timeout']; // Keep original string format - } else { - $timeoutString = (string) $stepData['timeout']; // Convert integer to string - } - } + $timeoutString = $stepData['timeout'] === null ? null : (string) $stepData['timeout']; $steps[] = new Step( id: $stepData['id'], diff --git a/src/Core/WorkflowContext.php b/src/Core/WorkflowContext.php index d098038..d84928b 100644 --- a/src/Core/WorkflowContext.php +++ b/src/Core/WorkflowContext.php @@ -96,7 +96,7 @@ public function getStepId(): string * * @param string|null $key Data key (supports dot notation for nested access), or null for all data * @param mixed $default Default value to return if key doesn't exist - * @return mixed Complete data array when key is null, or specific value when key is provided + * @return ($key is null ? array : mixed) Complete data array when key is null, or specific value when key is provided * * @example * ```php diff --git a/src/Core/WorkflowDefinition.php b/src/Core/WorkflowDefinition.php index 5d37f3e..72e1dfb 100644 --- a/src/Core/WorkflowDefinition.php +++ b/src/Core/WorkflowDefinition.php @@ -3,6 +3,7 @@ namespace SolutionForest\WorkflowEngine\Core; use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowDefinitionException; +use SolutionForest\WorkflowEngine\Support\Arr; use SolutionForest\WorkflowEngine\Support\ConditionEvaluator; /** @@ -63,7 +64,9 @@ final class WorkflowDefinition * @param string $name Unique workflow name/identifier * @param string $version Workflow version for change tracking * @param array> $steps Array of Step objects or step configurations - * @param array> $transitions Array of step transitions + * @param array}> $transitions Array of step transitions + * ('condition', when set, is a string; + * extra keys such as 'metadata' are kept) * @param array $metadata Additional workflow metadata * * @throws InvalidWorkflowDefinitionException If the definition is invalid @@ -130,7 +133,7 @@ public function getStep(string $id): ?Step /** * Get all defined step transitions. * - * @return array> Array of transition configurations + * @return array}> Array of transition configurations */ public function getTransitions(): array { @@ -238,7 +241,8 @@ public function getNextSteps(?string $currentStepId, array $data = []): array foreach ($this->transitions as $transition) { if ($transition['from'] === $currentStepId) { // Check condition if present - if (isset($transition['condition']) && ! $this->evaluateCondition($transition['condition'], $data)) { + $condition = $transition['condition'] ?? null; + if (is_string($condition) && ! $this->evaluateCondition($condition, $data)) { continue; } @@ -314,20 +318,59 @@ private function processSteps(array $stepsData): array // Use the 'id' field from step data, or fall back to array index $stepId = $stepData['id'] ?? $index; + if (is_int($stepId)) { + $stepId = (string) $stepId; + } + if (! is_string($stepId)) { + throw InvalidWorkflowDefinitionException::invalidStepId(Arr::describe($stepId)); + } $actionClass = null; if (isset($stepData['action'])) { + if (! is_string($stepData['action'])) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'action must be a string', $stepData); + } $actionClass = ActionResolver::resolve($stepData['action']); } + $config = $stepData['parameters'] ?? $stepData['config'] ?? []; + if (! is_array($config) || ! Arr::isStringKeyed($config)) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'parameters/config must be an associative array', $stepData); + } + + // Timeouts are strings such as '30s'; a bare integer means seconds + // and is kept in its string form, as the constructor always coerced it. + $timeout = $stepData['timeout'] ?? null; + if (is_int($timeout)) { + $timeout = (string) $timeout; + } + if ($timeout !== null && ! is_string($timeout)) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'timeout must be a string such as "30s"', $stepData); + } + + $retryAttempts = $stepData['retry_attempts'] ?? 0; + if (! is_int($retryAttempts)) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'retry_attempts must be an integer', $stepData); + } + + $conditions = $stepData['conditions'] ?? []; + if (! is_array($conditions) || ! Arr::isStringArray($conditions)) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'conditions must be an array of strings', $stepData); + } + + $prerequisites = $stepData['prerequisites'] ?? []; + if (! is_array($prerequisites) || ! Arr::isStringArray($prerequisites)) { + throw InvalidWorkflowDefinitionException::invalidStep($stepId, 'prerequisites must be an array of step IDs', $stepData); + } + $steps[$stepId] = new Step( id: $stepId, actionClass: $actionClass, - config: $stepData['parameters'] ?? $stepData['config'] ?? [], - timeout: $stepData['timeout'] ?? null, - retryAttempts: $stepData['retry_attempts'] ?? 0, - conditions: $stepData['conditions'] ?? [], - prerequisites: $stepData['prerequisites'] ?? [] + config: $config, + timeout: $timeout, + retryAttempts: $retryAttempts, + conditions: $conditions, + prerequisites: $prerequisites ); } @@ -348,10 +391,31 @@ private function evaluateCondition(string $condition, array $data): bool return ConditionEvaluator::evaluate($condition, $data); } + /** + * A SHA-256 of the definition's content. An instance records it, so you can tell which + * version of an edited workflow it runs. Key order does not change it. + */ + public function fingerprint(): string + { + return hash('sha256', (string) json_encode(self::canonical($this->toArray()), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION)); + } + + private static function canonical(mixed $value): mixed + { + if (! is_array($value)) { + return $value; + } + if (! array_is_list($value)) { + ksort($value); + } + + return array_map(self::canonical(...), $value); + } + /** * Convert the workflow definition to an array representation. * - * @return array Array representation suitable for serialization + * @return array{name: string, version: string, steps: array>, transitions: array}>, metadata: array} Array representation suitable for serialization * * @example * ```php @@ -365,7 +429,7 @@ public function toArray(): array return [ 'name' => $this->name, 'version' => $this->version, - 'steps' => array_map(fn ($step) => $step->toArray(), $this->steps), + 'steps' => array_map(fn (Step $step): array => $step->toArray(), $this->steps), 'transitions' => $this->transitions, 'metadata' => $this->metadata, ]; @@ -388,12 +452,115 @@ public function toArray(): array */ public static function fromArray(array $data): static { + $name = $data['name'] ?? null; + if (! is_string($name)) { + throw new InvalidWorkflowDefinitionException( + 'Workflow definition name must be a string', + $data, + ['Expected string for name, got: '.get_debug_type($name)] + ); + } + + $version = $data['version'] ?? '1.0'; + if (! is_string($version)) { + throw new InvalidWorkflowDefinitionException( + 'Workflow version must be a string', + $data, + ['Expected string for version, got: '.get_debug_type($version)] + ); + } + + $metadata = $data['metadata'] ?? []; + if (! is_array($metadata) || ! Arr::isStringKeyed($metadata)) { + throw new InvalidWorkflowDefinitionException( + 'Workflow metadata must be an associative array', + $data, + ['Expected associative array for metadata, got: '.get_debug_type($metadata)] + ); + } + return new self( - name: $data['name'], - version: $data['version'] ?? '1.0', - steps: $data['steps'] ?? [], - transitions: $data['transitions'] ?? [], - metadata: $data['metadata'] ?? [] + name: $name, + version: $version, + steps: self::stepsFromArray($data['steps'] ?? [], $data), + transitions: self::transitionsFromArray($data['transitions'] ?? [], $data), + metadata: $metadata ); } + + /** + * @param array $data Full definition, for error context + * @return array> + * + * @throws InvalidWorkflowDefinitionException If steps is not an array of step configurations + */ + private static function stepsFromArray(mixed $steps, array $data): array + { + if (! is_array($steps)) { + throw new InvalidWorkflowDefinitionException( + 'Workflow definition steps must be an array', + $data, + ['Expected array for steps, got: '.get_debug_type($steps)] + ); + } + + $result = []; + foreach ($steps as $index => $step) { + if (! $step instanceof Step && (! is_array($step) || ! Arr::isStringKeyed($step))) { + throw new InvalidWorkflowDefinitionException( + "Step at index {$index} must be a Step or an associative array", + $data, + ["Expected Step or associative array for step {$index}, got: ".get_debug_type($step)] + ); + } + $result[$index] = $step; + } + + return $result; + } + + /** + * @param array $data Full definition, for error context + * @return array}> + * + * @throws InvalidWorkflowDefinitionException If a transition lacks string 'from'/'to' fields + */ + private static function transitionsFromArray(mixed $transitions, array $data): array + { + if (! is_array($transitions)) { + throw new InvalidWorkflowDefinitionException( + 'Workflow transitions must be an array', + $data, + ['Expected array for transitions, got: '.get_debug_type($transitions)] + ); + } + + $result = []; + foreach ($transitions as $index => $transition) { + $from = is_array($transition) ? ($transition['from'] ?? null) : null; + $to = is_array($transition) ? ($transition['to'] ?? null) : null; + $condition = is_array($transition) ? ($transition['condition'] ?? null) : null; + + if (! is_array($transition) + || ! Arr::isStringKeyed($transition) + || ! is_string($from) + || ! is_string($to) + || ($condition !== null && ! is_string($condition)) + ) { + throw new InvalidWorkflowDefinitionException( + "Transition at index {$index} must have string 'from' and 'to' fields (and an optional string 'condition')", + $data, + ['Invalid transition: '.Arr::describe($transition)] + ); + } + + // Re-assert the validated fields in place so the key order (and any + // extra keys such as 'metadata') is preserved. + $transition['from'] = $from; + $transition['to'] = $to; + $result[$index] = $transition; + } + + return $result; + } } diff --git a/src/Core/WorkflowEngine.php b/src/Core/WorkflowEngine.php index 2362d76..d3713df 100644 --- a/src/Core/WorkflowEngine.php +++ b/src/Core/WorkflowEngine.php @@ -3,9 +3,11 @@ namespace SolutionForest\WorkflowEngine\Core; use SolutionForest\WorkflowEngine\Contracts\EventDispatcher; +use SolutionForest\WorkflowEngine\Contracts\Logger; use SolutionForest\WorkflowEngine\Contracts\StorageAdapter; use SolutionForest\WorkflowEngine\Events\WorkflowCancelledEvent; use SolutionForest\WorkflowEngine\Events\WorkflowStartedEvent; +use SolutionForest\WorkflowEngine\Exceptions\ConcurrentModificationException; use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowDefinitionException; use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowStateException; use SolutionForest\WorkflowEngine\Exceptions\WorkflowInstanceNotFoundException; @@ -70,13 +72,21 @@ class WorkflowEngine * * @throws \InvalidArgumentException If the storage adapter is not properly configured */ + /** + * @param bool $signalTimeouts Enforce step timeouts with SIGALRM (pcntl). Only safe in a CLI + * worker running one workflow at a time; off by default, so + * web requests and long-running workers are never interrupted. + * Adapters normally enforce timeouts with their queue jobs. + */ public function __construct( private readonly StorageAdapter $storage, - private readonly ?EventDispatcher $eventDispatcher = null + private readonly ?EventDispatcher $eventDispatcher = null, + ?Logger $logger = null, + bool $signalTimeouts = false, ) { $this->parser = new DefinitionParser; $this->stateManager = new StateManager($storage); - $this->executor = new Executor($this->stateManager, $eventDispatcher); + $this->executor = new Executor($this->stateManager, $eventDispatcher, $logger, $signalTimeouts); // If no event dispatcher is provided, we'll use a fallback approach if ($this->eventDispatcher === null) { @@ -190,11 +200,76 @@ public function resume(string $instanceId): WorkflowInstance ); } + if ($instance->isSuspended()) { + throw new InvalidWorkflowStateException( + "Cannot resume workflow '{$instanceId}': it waits for '{$instance->getWait()?->for}' in step '{$instance->getWait()?->stepId}'; use signal()", + $instance->getState(), + WorkflowState::RUNNING, + $instanceId + ); + } + $this->executor->execute($instance); return $instance; } + /** + * Deliver a signal to a suspended workflow: the step that waits for $signal is done, and + * the workflow carries on until it completes, fails or suspends again. $payload is kept + * under `steps..payload` in the workflow data, for later conditions. + * + * Storage saves are compare-and-swap: if another process advanced the same instance at the + * same time, this throws ConcurrentModificationException and nothing of this call is + * written; call it again. + * + * @param array $payload + * + * @throws InvalidWorkflowStateException If the workflow is not waiting for $signal + * @throws ConcurrentModificationException + */ + public function signal(string $instanceId, string $signal, array $payload = []): WorkflowInstance + { + if ($signal === Wait::TIMER) { + throw new \InvalidArgumentException('The timer is not a signal anyone can send; resumeDue() ends timed waits.'); + } + + $instance = $this->stateManager->load($instanceId); + $this->executor->resumeWait($instance, $signal, $payload); + + return $instance; + } + + /** + * Resume every suspended workflow whose wait time has passed at $now (default: now). Run it + * from a scheduler, for example every minute. An instance that another process advanced in + * the meantime is skipped; it is no longer due, or the next run picks it up. + * + * @return list IDs of the instances it resumed + */ + public function resumeDue(?\DateTimeInterface $now = null, int $limit = 100): array + { + $now ??= new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + $resumed = []; + foreach ($this->storage->findInstances(['due_before' => $now, 'limit' => $limit]) as $instance) { + if (! $instance->getWait()?->isDue($now)) { + continue; + } + try { + $this->executor->resumeWait($instance, Wait::TIMER); + $resumed[] = $instance->getId(); + } catch (ConcurrentModificationException) { + continue; + } catch (\Throwable) { + // The executor recorded the failure on the instance (FAILED) and fired + // WorkflowFailedEvent; one broken workflow must not stop the others. + $resumed[] = $instance->getId(); + } + } + + return $resumed; + } + /** * Get a workflow instance by its ID. * @@ -292,6 +367,8 @@ public function cancel(string $instanceId, string $reason = ''): WorkflowInstanc /** * Get workflow status + * + * @return array{workflow_id: string, name: string, state: string, current_step: string|null, progress: float, created_at: \DateTime, updated_at: \DateTime} */ public function getStatus(string $workflowId): array { diff --git a/src/Core/WorkflowInstance.php b/src/Core/WorkflowInstance.php index 6ee007d..e304e68 100644 --- a/src/Core/WorkflowInstance.php +++ b/src/Core/WorkflowInstance.php @@ -3,6 +3,7 @@ namespace SolutionForest\WorkflowEngine\Core; use SolutionForest\WorkflowEngine\Exceptions\InvalidWorkflowStateException; +use SolutionForest\WorkflowEngine\Support\Arr; /** * Represents an active instance of a workflow execution. @@ -110,6 +111,16 @@ final class WorkflowInstance /** @var string|null Overall workflow error message if execution failed */ private ?string $errorMessage = null; + /** What the workflow waits for while suspended (WAITING after ActionResult::suspend()). */ + private ?Wait $wait = null; + + /** + * How many times storage has saved this instance. Storage refuses a save whose revision + * is not the stored one (optimistic locking), so two processes advancing the same + * instance cannot overwrite each other. + */ + private int $revision = 0; + /** @var \DateTime When this workflow instance was created */ private readonly \DateTime $createdAt; @@ -313,6 +324,36 @@ public function setErrorMessage(?string $errorMessage): void $this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC')); } + /** What the workflow waits for, while suspended. */ + public function getWait(): ?Wait + { + return $this->wait; + } + + public function setWait(?Wait $wait): void + { + $this->wait = $wait; + $this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC')); + } + + /** Whether a step suspended the workflow and it waits for a signal or a time. */ + public function isSuspended(): bool + { + return $this->wait !== null; + } + + /** The revision storage last saved (0: never saved). */ + public function getRevision(): int + { + return $this->revision; + } + + /** For storage adapters only: record the revision a save wrote. */ + public function setRevision(int $revision): void + { + $this->revision = $revision; + } + /** * Get the workflow instance creation timestamp. * @@ -406,6 +447,9 @@ public function toArray(): array 'completed_steps' => $this->completedSteps, 'failed_steps' => $this->failedSteps, 'error_message' => $this->errorMessage, + 'wait' => $this->wait?->toArray(), + 'revision' => $this->revision, + 'definition_fingerprint' => $this->definition->fingerprint(), 'created_at' => $this->createdAt->format('c'), 'updated_at' => $this->updatedAt->format('c'), ]; @@ -433,7 +477,7 @@ public static function fromArray(array $data, WorkflowDefinition $definition): s 'Cannot restore workflow instance: missing or invalid "id" field.', WorkflowState::PENDING, WorkflowState::PENDING, - (string) ($data['id'] ?? '') + Arr::describe($data['id'] ?? '') ); } @@ -488,6 +532,59 @@ public static function fromArray(array $data, WorkflowDefinition $definition): s ); } + $normalizedFailedSteps = []; + foreach ($failedSteps as $failure) { + $failedStepId = is_array($failure) ? ($failure['step_id'] ?? null) : null; + $failedError = is_array($failure) ? ($failure['error'] ?? null) : null; + $failedAt = is_array($failure) ? ($failure['failed_at'] ?? null) : null; + + if (! is_string($failedStepId) || ! is_string($failedError) || ! is_string($failedAt)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': every \"failed_steps\" entry needs string \"step_id\", \"error\" and \"failed_at\" fields.", + $state, + $state, + $data['id'] + ); + } + + $normalizedFailedSteps[] = ['step_id' => $failedStepId, 'error' => $failedError, 'failed_at' => $failedAt]; + } + + $instanceData = $data['data'] ?? []; + if (! is_array($instanceData) || ! Arr::isStringKeyed($instanceData)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': \"data\" must be an associative array.", + $state, + $state, + $data['id'] + ); + } + + $errorMessage = $data['error_message'] ?? null; + if ($errorMessage !== null && ! is_string($errorMessage)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': \"error_message\" must be a string or null.", + $state, + $state, + $data['id'] + ); + } + + // Timestamps are optional; a payload without them is restored as "now". + $timestamps = []; + foreach (['created_at', 'updated_at'] as $field) { + $value = $data[$field] ?? 'now'; + if (! is_string($value)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': \"{$field}\" must be a date-time string.", + $state, + $state, + $data['id'] + ); + } + $timestamps[$field] = new \DateTime($value); + } + $currentStepId = $data['current_step_id'] ?? null; if ($currentStepId !== null && (! is_string($currentStepId) || ! $definition->hasStep($currentStepId))) { throw new InvalidWorkflowStateException( @@ -502,15 +599,37 @@ public static function fromArray(array $data, WorkflowDefinition $definition): s id: $data['id'], definition: $definition, state: $state, - data: $data['data'] ?? [], - createdAt: new \DateTime($data['created_at']), - updatedAt: new \DateTime($data['updated_at']) + data: $instanceData, + createdAt: $timestamps['created_at'], + updatedAt: $timestamps['updated_at'] ); $instance->currentStepId = $currentStepId; $instance->completedSteps = $completedSteps; - $instance->failedSteps = $failedSteps; - $instance->errorMessage = $data['error_message'] ?? null; + $instance->failedSteps = $normalizedFailedSteps; + $instance->errorMessage = $errorMessage; + $wait = $data['wait'] ?? null; + if ($wait !== null) { + if (! is_array($wait)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': \"wait\" must be an array or null.", + $state, + $state, + $data['id'] + ); + } + $instance->wait = Wait::fromArray($wait); + if (! $definition->hasStep($instance->wait->stepId)) { + throw new InvalidWorkflowStateException( + "Cannot restore workflow instance '{$data['id']}': it waits in step '{$instance->wait->stepId}', which is not defined in the workflow.", + $state, + $state, + $data['id'] + ); + } + } + $revision = $data['revision'] ?? 0; + $instance->revision = is_int($revision) && $revision >= 0 ? $revision : 0; return $instance; } diff --git a/src/Events/StepCompletedEvent.php b/src/Events/StepCompletedEvent.php index 748cc8c..63a242d 100644 --- a/src/Events/StepCompletedEvent.php +++ b/src/Events/StepCompletedEvent.php @@ -31,6 +31,9 @@ public function getStepName(): string return $this->step->getId(); // Use ID as name since Step doesn't have a name property } + /** + * @return array + */ public function getData(): array { return $this->instance->getData(); diff --git a/src/Events/StepFailedEvent.php b/src/Events/StepFailedEvent.php index 446faf6..7ad085d 100644 --- a/src/Events/StepFailedEvent.php +++ b/src/Events/StepFailedEvent.php @@ -37,6 +37,9 @@ public function getErrorMessage(): string return $this->exception->getMessage(); } + /** + * @return array + */ public function getData(): array { return $this->instance->getData(); diff --git a/src/Events/WorkflowResumedEvent.php b/src/Events/WorkflowResumedEvent.php new file mode 100644 index 0000000..108d8de --- /dev/null +++ b/src/Events/WorkflowResumedEvent.php @@ -0,0 +1,27 @@ + + */ +final readonly class WorkflowResumedEvent +{ + /** @param array $payload */ + public function __construct( + public WorkflowInstance $instance, + public Step $step, + public Wait $wait, + public string $signal, + public array $payload = [], + ) {} +} diff --git a/src/Events/WorkflowSuspendedEvent.php b/src/Events/WorkflowSuspendedEvent.php new file mode 100644 index 0000000..4b2f2d4 --- /dev/null +++ b/src/Events/WorkflowSuspendedEvent.php @@ -0,0 +1,19 @@ +for, or until $wait->resumeAt. */ +final readonly class WorkflowSuspendedEvent +{ + public function __construct( + public WorkflowInstance $instance, + public Step $step, + public Wait $wait, + ) {} +} diff --git a/src/Exceptions/ConcurrentModificationException.php b/src/Exceptions/ConcurrentModificationException.php new file mode 100644 index 0000000..ebe7602 --- /dev/null +++ b/src/Exceptions/ConcurrentModificationException.php @@ -0,0 +1,29 @@ + $instanceId, 'expected_revision' => $expectedRevision, 'stored_revision' => $storedRevision], + ); + } + + public function getUserMessage(): string + { + return 'This workflow was changed at the same time by someone else. Try again.'; + } +} diff --git a/src/Exceptions/InvalidWorkflowDefinitionException.php b/src/Exceptions/InvalidWorkflowDefinitionException.php index 111b596..48805f2 100644 --- a/src/Exceptions/InvalidWorkflowDefinitionException.php +++ b/src/Exceptions/InvalidWorkflowDefinitionException.php @@ -2,6 +2,8 @@ namespace SolutionForest\WorkflowEngine\Exceptions; +use SolutionForest\WorkflowEngine\Support\Arr; + /** * Thrown when a workflow definition is invalid or malformed. * @@ -68,6 +70,9 @@ public function getSuggestions(): array } $definition = $this->getContextValue('definition', []); + if (! is_array($definition)) { + $definition = []; + } if (empty($definition['name'])) { $suggestions[] = 'Add a "name" field to identify your workflow'; } @@ -295,19 +300,19 @@ public static function actionNotFound(string $actionName, array $context = []): 'Ensure the action class implements the WorkflowAction interface', ]; - if (isset($context['tried_classes'])) { + if (isset($context['tried_classes']) && is_array($context['tried_classes']) && Arr::isStringArray($context['tried_classes'])) { $suggestions[] = 'Tried resolving to classes: '.implode(', ', $context['tried_classes']); } - if (isset($context['predefined_actions'])) { + if (isset($context['predefined_actions']) && is_array($context['predefined_actions']) && Arr::isStringArray($context['predefined_actions'])) { $suggestions[] = 'Available predefined actions: '.implode(', ', $context['predefined_actions']); } - if (isset($context['custom_actions']) && ! empty($context['custom_actions'])) { + if (isset($context['custom_actions']) && is_array($context['custom_actions']) && Arr::isStringArray($context['custom_actions']) && $context['custom_actions'] !== []) { $suggestions[] = 'Available custom actions: '.implode(', ', $context['custom_actions']); } - if (isset($context['suggestion'])) { + if (isset($context['suggestion']) && is_string($context['suggestion'])) { $suggestions[] = $context['suggestion']; } diff --git a/src/Exceptions/InvalidWorkflowStateException.php b/src/Exceptions/InvalidWorkflowStateException.php index 628d157..51f091b 100644 --- a/src/Exceptions/InvalidWorkflowStateException.php +++ b/src/Exceptions/InvalidWorkflowStateException.php @@ -4,6 +4,7 @@ use SolutionForest\WorkflowEngine\Core\WorkflowInstance; use SolutionForest\WorkflowEngine\Core\WorkflowState; +use SolutionForest\WorkflowEngine\Support\Arr; /** * Thrown when attempting to perform an invalid workflow state transition. @@ -110,7 +111,7 @@ public function getSuggestions(): array $validTransitions = $this->getContextValue('valid_transitions', []); $suggestions = []; - if (! empty($validTransitions)) { + if (is_array($validTransitions) && $validTransitions !== [] && Arr::isStringArray($validTransitions)) { $validStates = implode(', ', $validTransitions); $suggestions[] = "Valid transitions from '{$this->currentState->value}' are: {$validStates}"; } else { diff --git a/src/Exceptions/StepExecutionException.php b/src/Exceptions/StepExecutionException.php index 1ca185d..b7b5524 100644 --- a/src/Exceptions/StepExecutionException.php +++ b/src/Exceptions/StepExecutionException.php @@ -70,10 +70,18 @@ public function getAttemptNumber(): int * @return bool True if the step supports retries and hasn't exceeded the limit */ public function canRetry(): bool + { + return $this->attemptNumber <= $this->maxRetries(); + } + + /** + * The retry budget configured on the step; anything but an integer means none. + */ + private function maxRetries(): int { $maxRetries = $this->step->getConfig()['retry_attempts'] ?? 0; - return $this->attemptNumber <= $maxRetries; + return is_int($maxRetries) ? $maxRetries : 0; } /** @@ -82,7 +90,7 @@ public function canRetry(): bool public function getUserMessage(): string { $stepName = $this->step->getId(); - $actionClass = Arr::classBasename($this->step->getActionClass()); + $actionClass = Arr::classBasename($this->step->getActionClass() ?? ''); return "The workflow step '{$stepName}' (using {$actionClass}) failed to execute. ". 'This may be due to invalid input data, external service issues, or configuration problems.'; @@ -94,7 +102,8 @@ public function getUserMessage(): string public function getSuggestions(): array { $suggestions = []; - $actionClass = $this->step->getActionClass(); + // A step without an action has no class name to match against. + $actionClass = $this->step->getActionClass() ?? ''; // Basic suggestions $suggestions[] = "Verify the action class '{$actionClass}' is properly implemented"; @@ -103,8 +112,7 @@ public function getSuggestions(): array // Retry-specific suggestions if ($this->canRetry()) { - $maxRetries = $this->step->getConfig()['retry_attempts'] ?? 0; - $remaining = $maxRetries - $this->attemptNumber + 1; + $remaining = $this->maxRetries() - $this->attemptNumber + 1; $suggestions[] = "This step will be retried automatically ({$remaining} attempts remaining)"; } elseif (isset($this->step->getConfig()['retry_attempts'])) { $suggestions[] = 'All retry attempts have been exhausted'; diff --git a/src/Storage/InMemoryStorage.php b/src/Storage/InMemoryStorage.php index 5c50508..b7d6ada 100644 --- a/src/Storage/InMemoryStorage.php +++ b/src/Storage/InMemoryStorage.php @@ -1,9 +1,14 @@ Instances keyed by workflow ID */ + /** @var array, definition: WorkflowDefinition}> Snapshots keyed by workflow ID */ private array $instances = []; + /** + * @throws ConcurrentModificationException If the instance was saved since this copy was loaded + */ public function save(WorkflowInstance $instance): void { - $this->instances[$instance->getId()] = $instance; + $id = $instance->getId(); + $stored = isset($this->instances[$id]) ? $this->revisionOf($this->instances[$id]['row']) : 0; + if ($stored !== $instance->getRevision()) { + throw new ConcurrentModificationException($id, $instance->getRevision(), $stored); + } + + $instance->setRevision($stored + 1); + $this->instances[$id] = ['row' => $instance->toArray(), 'definition' => $instance->getDefinition()]; } /** @@ -42,49 +60,45 @@ public function load(string $id): WorkflowInstance throw WorkflowInstanceNotFoundException::notFound($id, self::class); } - return $this->instances[$id]; + return WorkflowInstance::fromArray($this->instances[$id]['row'], $this->instances[$id]['definition']); } /** * Find instances matching simple criteria. * - * Supported keys: `state` (string or WorkflowState value), `definition_name`, - * `limit` and `offset`. Unknown keys are ignored. + * Supported keys: `state` (string or WorkflowState), `definition_name`, `due_before` + * (a DateTimeInterface: suspended instances whose wait time has passed), `limit` and + * `offset`. Unknown keys are ignored. * * @param array $criteria * @return array */ public function findInstances(array $criteria = []): array { - $results = array_values($this->instances); + $results = array_map(fn (string $id): WorkflowInstance => $this->load($id), array_keys($this->instances)); if (isset($criteria['state'])) { $state = $criteria['state']; - $wanted = is_string($state) ? $state : ($state->value ?? null); - - $results = array_values(array_filter( - $results, - static fn (WorkflowInstance $i): bool => $i->getState()->value === $wanted - )); + $wanted = $state instanceof WorkflowState ? $state->value : $state; + $results = array_filter($results, static fn (WorkflowInstance $i): bool => $i->getState()->value === $wanted); } if (isset($criteria['definition_name'])) { $name = $criteria['definition_name']; - - $results = array_values(array_filter( - $results, - static fn (WorkflowInstance $i): bool => $i->getDefinition()->getName() === $name - )); + $results = array_filter($results, static fn (WorkflowInstance $i): bool => $i->getDefinition()->getName() === $name); } - $offset = isset($criteria['offset']) ? max(0, (int) $criteria['offset']) : 0; - $limit = isset($criteria['limit']) ? max(0, (int) $criteria['limit']) : null; - - if ($offset > 0 || $limit !== null) { - $results = array_slice($results, $offset, $limit); + if (($criteria['due_before'] ?? null) instanceof \DateTimeInterface) { + $now = $criteria['due_before']; + $results = array_filter($results, static fn (WorkflowInstance $i): bool => $i->getState() === WorkflowState::WAITING + && ($i->getWait()?->isDue($now) ?? false)); } - return $results; + $results = array_values($results); + $offset = is_int($criteria['offset'] ?? null) ? max(0, $criteria['offset']) : 0; + $limit = is_int($criteria['limit'] ?? null) ? max(0, $criteria['limit']) : null; + + return $offset > 0 || $limit !== null ? array_slice($results, $offset, $limit) : $results; } public function delete(string $id): void @@ -98,22 +112,18 @@ public function exists(string $id): bool } /** - * Apply partial updates to a stored instance. - * - * Instances are mutable objects held by reference, so the engine's own - * writes are already visible here; this method exists to satisfy the - * contract and to support callers that patch state directly. + * Apply a partial update (`data` merged, `error_message`, `current_step_id`) and save. * * @param array $updates - * - * @throws WorkflowInstanceNotFoundException If no instance has that ID */ public function updateState(string $id, array $updates): void { $instance = $this->load($id); if (isset($updates['data']) && is_array($updates['data'])) { - $instance->mergeData($updates['data']); + /** @var array $data */ + $data = $updates['data']; + $instance->mergeData($data); } if (array_key_exists('error_message', $updates)) { @@ -121,26 +131,28 @@ public function updateState(string $id, array $updates): void $instance->setErrorMessage(is_string($errorMessage) ? $errorMessage : null); } - if (isset($updates['current_step_id'])) { - $instance->setCurrentStepId((string) $updates['current_step_id']); + if (is_string($updates['current_step_id'] ?? null)) { + $instance->setCurrentStepId($updates['current_step_id']); } $this->save($instance); } - /** - * Remove every stored instance. - */ + /** Remove every stored instance. */ public function flush(): void { $this->instances = []; } - /** - * Count the stored instances. - */ + /** Number of stored instances. */ public function count(): int { return count($this->instances); } + + /** @param array $row */ + private function revisionOf(array $row): int + { + return is_int($row['revision'] ?? null) ? $row['revision'] : 0; + } } diff --git a/src/Support/Arr.php b/src/Support/Arr.php index ba30368..d272d0a 100644 --- a/src/Support/Arr.php +++ b/src/Support/Arr.php @@ -51,6 +51,59 @@ public static function has(array $array, string $key): bool return true; } + /** + * Whether every key of the array is a string (vacuously true when empty). + * + * @param array $array + * + * @phpstan-assert-if-true array $array + */ + public static function isStringKeyed(array $array): bool + { + foreach (array_keys($array) as $key) { + if (! is_string($key)) { + return false; + } + } + + return true; + } + + /** + * Whether every value of the array is a string (vacuously true when empty). + * + * @param array $array + * + * @phpstan-assert-if-true array $array + */ + public static function isStringArray(array $array): bool + { + foreach ($array as $value) { + if (! is_string($value)) { + return false; + } + } + + return true; + } + + /** + * Describe an arbitrary value for an error message: strings verbatim, + * other scalars as PHP literals, everything else by type name. + */ + public static function describe(mixed $value): string + { + if (is_string($value)) { + return $value; + } + + if (is_scalar($value) || $value === null) { + return var_export($value, true); + } + + return get_debug_type($value); + } + /** * Get the class "basename" of a class string (without namespace). */ diff --git a/src/Support/SimpleWorkflow.php b/src/Support/SimpleWorkflow.php index 4c56303..0550e85 100644 --- a/src/Support/SimpleWorkflow.php +++ b/src/Support/SimpleWorkflow.php @@ -46,7 +46,7 @@ class SimpleWorkflow * Create a new SimpleWorkflow instance. * * @param StorageAdapter $storage Storage adapter for workflow persistence - * @param Dispatcher|null $eventDispatcher Optional event dispatcher for workflow events + * @param EventDispatcher|null $eventDispatcher Optional event dispatcher for workflow events */ public function __construct(StorageAdapter $storage, ?EventDispatcher $eventDispatcher = null) { diff --git a/tests/Unit/ActionTest.php b/tests/Unit/ActionTest.php index 83540af..e75c2a7 100644 --- a/tests/Unit/ActionTest.php +++ b/tests/Unit/ActionTest.php @@ -3,6 +3,7 @@ use SolutionForest\WorkflowEngine\Actions\DelayAction; use SolutionForest\WorkflowEngine\Actions\LogAction; use SolutionForest\WorkflowEngine\Core\ActionResult; +use SolutionForest\WorkflowEngine\Core\Wait; use SolutionForest\WorkflowEngine\Core\WorkflowContext; test('log action can execute', function () { @@ -16,20 +17,20 @@ expect($result->getErrorMessage())->toBeNull(); }); -test('delay action can execute', function () { - $action = new DelayAction(['seconds' => 1]); +test('delay action suspends until its time instead of sleeping', function () { + $action = new DelayAction(['seconds' => 30]); $context = new WorkflowContext('test-workflow', 'test-step'); $start = microtime(true); $result = $action->execute($context); - $end = microtime(true); expect($result)->toBeInstanceOf(ActionResult::class); - expect($result->isSuccess())->toBeTrue(); - expect($result->getErrorMessage())->toBeNull(); - - // Check that at least 1 second passed (with some tolerance) - expect($end - $start)->toBeGreaterThanOrEqual(0.9); + expect($result->isSuspended())->toBeTrue(); + expect($result->isSuccess())->toBeFalse(); + expect($result->isFailure())->toBeFalse(); + expect($result->getSuspension()?->for)->toBe(Wait::TIMER); + expect($result->getSuspension()?->resumeAt?->getTimestamp())->toBeGreaterThanOrEqual(time() + 29); + expect(microtime(true) - $start)->toBeLessThan(0.5); }); test('log action handles invalid template', function () { diff --git a/tests/Unit/BuiltInActionsTest.php b/tests/Unit/BuiltInActionsTest.php index 61fc606..410fcee 100644 --- a/tests/Unit/BuiltInActionsTest.php +++ b/tests/Unit/BuiltInActionsTest.php @@ -71,7 +71,7 @@ function contextWith(array $config, array $data = []): WorkflowContext $result = $action->execute(contextWith(['microseconds' => 1000])); - expect($result->isSuccess())->toBeTrue(); + expect($result->isSuspended())->toBeTrue(); expect($result->getData()['delayed_microseconds'])->toBe(1000); }); diff --git a/tests/Unit/MalformedInputTest.php b/tests/Unit/MalformedInputTest.php new file mode 100644 index 0000000..1c2ffbe --- /dev/null +++ b/tests/Unit/MalformedInputTest.php @@ -0,0 +1,196 @@ + ['name' => 'Ada']]); +} + +describe('built-in actions reject malformed config', function () { + test('ConditionAction fails when the condition is not a string', function () { + $result = (new ConditionAction(['condition' => ['user.name']]))->execute(malformedContext()); + + expect($result->isSuccess())->toBeFalse(); + expect($result->getErrorMessage())->toBe('Condition must be a string expression'); + }); + + test('LogAction fails when message or level is not a string', function () { + $badMessage = (new LogAction(['message' => ['not', 'text']]))->execute(malformedContext()); + $badLevel = (new LogAction(['message' => 'hi', 'level' => 3]))->execute(malformedContext()); + + expect($badMessage->isSuccess())->toBeFalse(); + expect($badMessage->getErrorMessage())->toBe('Log "message" must be a string'); + expect($badLevel->isSuccess())->toBeFalse(); + expect($badLevel->getErrorMessage())->toBe('Log "level" must be a string'); + }); + + test('LogAction still interpolates placeholders for valid input', function () { + $result = (new LogAction(['message' => 'Hello {user.name}']))->execute(malformedContext()); + + expect($result->isSuccess())->toBeTrue(); + expect($result->getData()['logged_message'])->toBe('Hello Ada'); + }); + + test('HttpAction fails on config of the wrong type', function (array $config, string $message) { + $result = (new HttpAction($config))->execute(malformedContext()); + + expect($result->isSuccess())->toBeFalse(); + expect($result->getErrorMessage())->toBe($message); + })->with([ + 'url' => [['url' => ['x']], 'HTTP action "url" must be a string'], + 'method' => [['url' => 'https://example.test', 'method' => 5], 'HTTP action "method" must be a non-empty string'], + 'data' => [['url' => 'https://example.test', 'data' => 'a=b'], 'HTTP action "data" must be an array'], + 'headers' => [['url' => 'https://example.test', 'headers' => 'X-A: b'], 'HTTP action "headers" must be an array'], + 'header value' => [['url' => 'https://example.test', 'headers' => ['X-A' => ['b']]], 'HTTP action header "X-A" must be a scalar value'], + 'timeout' => [['url' => 'https://example.test', 'timeout' => 'soon'], 'HTTP action "timeout" must be an integer'], + 'connect_timeout' => [['url' => 'https://example.test', 'connect_timeout' => []], 'HTTP action "connect_timeout" must be an integer'], + 'max_redirects' => [['url' => 'https://example.test', 'max_redirects' => '3x'], 'HTTP action "max_redirects" must be an integer'], + ]); +}); + +describe('DefinitionParser rejects malformed definitions', function () { + test('JSON that is not an object', function () { + expect(fn () => (new DefinitionParser)->parse('"just a string"')) + ->toThrow(InvalidWorkflowDefinitionException::class, 'the document must be a JSON object'); + }); + + test('a non-string name', function () { + expect(fn () => (new DefinitionParser)->parse(['name' => ['x'], 'steps' => [['id' => 'a']]])) + ->toThrow(InvalidWorkflowDefinitionException::class, "Invalid workflow name: 'array'"); + }); + + test('a transition that is not an array', function () { + expect(fn () => (new DefinitionParser)->parse([ + 'name' => 'wf', + 'steps' => [['id' => 'a']], + 'transitions' => ['a->b'], + ]))->toThrow(InvalidWorkflowDefinitionException::class, 'Transition at index 0 must be an array'); + }); + + test('a step with non-string keys', function () { + expect(fn () => (new DefinitionParser)->parse([ + 'name' => 'wf', + 'steps' => [['id' => 'a', 0 => 'log']], + ]))->toThrow(InvalidWorkflowDefinitionException::class, 'must be an associative array of step fields'); + }); + + test('a non-string step id', function () { + expect(fn () => (new DefinitionParser)->parse([ + 'name' => 'wf', + 'steps' => [['id' => ['a']]], + ]))->toThrow(InvalidWorkflowDefinitionException::class, "Invalid step ID: 'array'"); + }); + + test('a non-integer retry_attempts', function () { + expect(fn () => (new DefinitionParser)->parse([ + 'name' => 'wf', + 'steps' => [['id' => 'a', 'retry_attempts' => '3']], + ]))->toThrow(InvalidWorkflowDefinitionException::class, "Step 'a' retry_attempts must be an integer"); + }); + + test('a non-string step condition', function () { + expect(fn () => (new DefinitionParser)->parse([ + 'name' => 'wf', + 'steps' => [['id' => 'a', 'conditions' => [42]]], + ]))->toThrow(InvalidWorkflowDefinitionException::class, "Invalid condition expression: '42'"); + }); +}); + +describe('WorkflowDefinition::fromArray rejects malformed data', function () { + test('throws a clear exception for each malformed field', function (array $data, string $message) { + expect(fn () => WorkflowDefinition::fromArray($data)) + ->toThrow(InvalidWorkflowDefinitionException::class, $message); + })->with([ + 'missing name' => [['steps' => []], 'Workflow definition name must be a string'], + 'version' => [['name' => 'wf', 'version' => 2], 'Workflow version must be a string'], + 'metadata' => [['name' => 'wf', 'metadata' => 'x'], 'Workflow metadata must be an associative array'], + 'steps' => [['name' => 'wf', 'steps' => 'a'], 'Workflow definition steps must be an array'], + 'step entry' => [['name' => 'wf', 'steps' => ['a']], 'Step at index 0 must be a Step or an associative array'], + 'step id' => [['name' => 'wf', 'steps' => [['id' => 1.5]]], "Invalid step ID: '1.5'"], + 'action' => [['name' => 'wf', 'steps' => ['a' => ['action' => 5]]], 'action must be a string'], + 'config' => [['name' => 'wf', 'steps' => ['a' => ['config' => 'x']]], 'parameters/config must be an associative array'], + 'timeout' => [['name' => 'wf', 'steps' => ['a' => ['timeout' => 1.5]]], 'timeout must be a string'], + 'retry_attempts' => [['name' => 'wf', 'steps' => ['a' => ['retry_attempts' => '2']]], 'retry_attempts must be an integer'], + 'conditions' => [['name' => 'wf', 'steps' => ['a' => ['conditions' => [1]]]], 'conditions must be an array of strings'], + 'prerequisites' => [['name' => 'wf', 'steps' => ['a' => ['prerequisites' => 'b']]], 'prerequisites must be an array of step IDs'], + 'transitions' => [['name' => 'wf', 'transitions' => 'a->b'], 'Workflow transitions must be an array'], + 'transition fields' => [['name' => 'wf', 'transitions' => [['from' => 'a']]], "Transition at index 0 must have string 'from' and 'to' fields"], + 'transition condition' => [['name' => 'wf', 'transitions' => [['from' => 'a', 'to' => 'b', 'condition' => true]]], "Transition at index 0 must have string 'from' and 'to' fields"], + ]); + + test('keeps integer timeouts and positional ids as strings, as before', function () { + $definition = WorkflowDefinition::fromArray([ + 'name' => 'wf', + 'steps' => [['timeout' => 30]], + ]); + + expect($definition->getStep('0')?->getTimeout())->toBe('30'); + }); + + test('preserves extra transition keys such as metadata', function () { + $definition = WorkflowDefinition::fromArray([ + 'name' => 'wf', + 'steps' => ['a' => [], 'b' => []], + 'transitions' => [['from' => 'a', 'to' => 'b', 'metadata' => ['x' => 1]]], + ]); + + expect($definition->getTransitions())->toBe([['from' => 'a', 'to' => 'b', 'metadata' => ['x' => 1]]]); + }); +}); + +describe('WorkflowInstance::fromArray rejects malformed fields', function () { + beforeEach(function () { + $this->definition = (new DefinitionParser)->parse([ + 'name' => 'restore-malformed', + 'steps' => [['id' => 'a', 'action' => 'log']], + ]); + $this->payload = [ + 'id' => 'inst-1', + 'state' => 'running', + 'completed_steps' => [], + 'failed_steps' => [], + 'created_at' => '2026-01-01T00:00:00+00:00', + 'updated_at' => '2026-01-01T00:00:00+00:00', + ]; + }); + + test('throws a clear exception for each malformed field', function (array $override, string $message) { + expect(fn () => WorkflowInstance::fromArray(array_merge($this->payload, $override), $this->definition)) + ->toThrow(InvalidWorkflowStateException::class, $message); + })->with([ + 'failed step entry' => [['failed_steps' => [['step_id' => 'a']]], 'every "failed_steps" entry needs string'], + 'data' => [['data' => 'x'], '"data" must be an associative array'], + 'error_message' => [['error_message' => ['boom']], '"error_message" must be a string or null'], + 'created_at' => [['created_at' => 1700000000], '"created_at" must be a date-time string'], + ]); + + test('restores well-formed failed steps', function () { + $failure = ['step_id' => 'a', 'error' => 'boom', 'failed_at' => '2026-01-01T00:00:00+00:00']; + + $instance = WorkflowInstance::fromArray(array_merge($this->payload, ['failed_steps' => [$failure]]), $this->definition); + + expect($instance->getFailedSteps())->toBe([$failure]); + }); + + test('defaults missing timestamps to now', function () { + $payload = $this->payload; + unset($payload['created_at'], $payload['updated_at']); + + $instance = WorkflowInstance::fromArray($payload, $this->definition); + + expect(abs($instance->getCreatedAt()->getTimestamp() - time()))->toBeLessThan(5); + }); +}); diff --git a/tests/Unit/Support/ArrTest.php b/tests/Unit/Support/ArrTest.php index d35e397..19bcd99 100644 --- a/tests/Unit/Support/ArrTest.php +++ b/tests/Unit/Support/ArrTest.php @@ -63,4 +63,27 @@ expect($data['name'])->toBe('Jane'); }); }); + + describe('type guards', function () { + test('isStringKeyed accepts maps and the empty array', function () { + expect(Arr::isStringKeyed(['a' => 1, 'b' => 2]))->toBeTrue(); + expect(Arr::isStringKeyed([]))->toBeTrue(); + expect(Arr::isStringKeyed(['a' => 1, 0 => 2]))->toBeFalse(); + expect(Arr::isStringKeyed([1, 2]))->toBeFalse(); + }); + + test('isStringArray requires every value to be a string', function () { + expect(Arr::isStringArray(['a', 'b']))->toBeTrue(); + expect(Arr::isStringArray([]))->toBeTrue(); + expect(Arr::isStringArray(['a', 1]))->toBeFalse(); + }); + + test('describe renders values for error messages', function () { + expect(Arr::describe('abc'))->toBe('abc'); + expect(Arr::describe(5))->toBe('5'); + expect(Arr::describe(null))->toBe('NULL'); + expect(Arr::describe(['x']))->toBe('array'); + expect(Arr::describe(new stdClass))->toBe('stdClass'); + }); + }); }); diff --git a/tests/Unit/SuspendResumeTest.php b/tests/Unit/SuspendResumeTest.php new file mode 100644 index 0000000..77672b8 --- /dev/null +++ b/tests/Unit/SuspendResumeTest.php @@ -0,0 +1,301 @@ + $config */ + public function __construct(public array $config = [], public mixed $logger = null) {} + + public function execute(WorkflowContext $context): ActionResult + { + self::$runs++; + $deadline = $this->config['deadline'] ?? null; + + return ActionResult::suspend( + 'decided', + is_string($deadline) ? new DateTimeImmutable($deadline) : null, + ['asked' => true], + ); + } + + public function canExecute(WorkflowContext $context): bool + { + return true; + } + + public function getName(): string + { + return 'Await approval'; + } + + public function getDescription(): string + { + return 'Waits for a decision'; + } +} + +/** @return array */ +function approvalFlow(?string $deadline = null): array +{ + return [ + 'name' => 'purchase-approval', + 'version' => '1.0', + 'steps' => [ + ['id' => 'approve', 'action' => AwaitApprovalAction::class, 'config' => $deadline === null ? [] : ['deadline' => $deadline]], + ['id' => 'order', 'action' => LogAction::class, 'config' => ['message' => 'ordering']], + ['id' => 'reject', 'action' => LogAction::class, 'config' => ['message' => 'rejected']], + ], + 'transitions' => [ + ['from' => 'approve', 'to' => 'order', 'condition' => 'steps.approve.payload.decision === "approved"'], + ['from' => 'approve', 'to' => 'reject', 'condition' => 'steps.approve.payload.decision !== "approved"'], + ], + ]; +} + +beforeEach(function () { + AwaitApprovalAction::$runs = 0; + $this->events = new SpyEventDispatcher; + $this->engine = new WorkflowEngine($this->storage, $this->events); +}); + +describe('suspend and signal', function () { + test('a suspended step waits without finishing, and the next steps do not run', function () { + $this->engine->start('po-1', approvalFlow(), ['amount' => 25_000]); + $instance = $this->engine->getInstance('po-1'); + + expect($instance->getState())->toBe(WorkflowState::WAITING) + ->and($instance->getWait()?->stepId)->toBe('approve') + ->and($instance->getWait()?->for)->toBe('decided') + ->and($instance->getCompletedSteps())->toBe([]) + ->and($instance->getData()['asked'])->toBeTrue() + ->and($this->events->countDispatched(WorkflowSuspendedEvent::class))->toBe(1) + ->and($this->events->hasDispatched(WorkflowCompletedEvent::class))->toBeFalse(); + }); + + test('the signal finishes the step, keeps its payload and takes the matching branch', function () { + $this->engine->start('po-1', approvalFlow()); + + $instance = $this->engine->signal('po-1', 'decided', ['decision' => 'approved', 'by' => 'ada']); + + expect($instance->getState())->toBe(WorkflowState::COMPLETED) + ->and($instance->getCompletedSteps())->toBe(['approve', 'order']) + ->and($instance->getData()['steps']['approve']['resumed_by'])->toBe('decided') + ->and($instance->getData()['steps']['approve']['payload'])->toBe(['decision' => 'approved', 'by' => 'ada']) + ->and($instance->getWait())->toBeNull() + ->and(AwaitApprovalAction::$runs)->toBe(1) + ->and($this->events->countDispatched(WorkflowResumedEvent::class))->toBe(1); + + $resumed = $this->events->getDispatched(WorkflowResumedEvent::class)[0]; + expect($resumed->signal)->toBe('decided')->and($resumed->step->getId())->toBe('approve'); + expect(array_map(fn (StepCompletedEvent $e) => $e->step->getId(), $this->events->getDispatched(StepCompletedEvent::class))) + ->toBe(['approve', 'order']); + }); + + test('another payload takes the other branch', function () { + $this->engine->start('po-1', approvalFlow()); + + expect($this->engine->signal('po-1', 'decided', ['decision' => 'rejected'])->getCompletedSteps())->toBe(['approve', 'reject']); + }); + + test('refuses a signal the workflow does not wait for, and anything once it is done', function () { + $this->engine->start('po-1', approvalFlow()); + + expect(fn () => $this->engine->signal('po-1', 'paid'))->toThrow(InvalidWorkflowStateException::class, "waits for 'decided'"); + expect($this->engine->getInstance('po-1')->getState())->toBe(WorkflowState::WAITING); + + $this->engine->signal('po-1', 'decided', ['decision' => 'approved']); + expect(fn () => $this->engine->signal('po-1', 'decided'))->toThrow(InvalidWorkflowStateException::class, 'not waiting'); + }); + + test('nobody can send the timer signal', function () { + $this->engine->start('po-1', approvalFlow()); + + expect(fn () => $this->engine->signal('po-1', Wait::TIMER))->toThrow(InvalidArgumentException::class); + }); + + test('resume() does not run a suspended step a second time', function () { + $this->engine->start('po-1', approvalFlow()); + + expect(fn () => $this->engine->resume('po-1'))->toThrow(InvalidWorkflowStateException::class, 'use signal()'); + expect(AwaitApprovalAction::$runs)->toBe(1); + }); + + test('the wait survives storage: a fresh copy still knows what it waits for', function () { + $this->engine->start('po-1', approvalFlow('2030-01-01T00:00:00+00:00')); + + $copy = $this->storage->load('po-1'); + $row = $copy->toArray(); + + expect($copy)->not->toBe($this->storage->load('po-1')) + ->and($copy->getWait()?->resumeAt?->format('Y-m-d'))->toBe('2030-01-01') + ->and($row['wait']['for'])->toBe('decided') + ->and($row['definition_fingerprint'])->toHaveLength(64); + }); +}); + +describe('timed waits', function () { + test('resumeDue() leaves waits that are not due, and ends those that are', function () { + $this->engine->start('po-1', approvalFlow('2030-01-01T00:00:00+00:00')); + $this->engine->start('po-2', approvalFlow()); + + expect($this->engine->resumeDue(new DateTimeImmutable('2029-12-31T23:59:00+00:00')))->toBe([]); + + expect($this->engine->resumeDue(new DateTimeImmutable('2030-01-01T00:00:01+00:00')))->toBe(['po-1']); + $instance = $this->engine->getInstance('po-1'); + expect($instance->getState())->toBe(WorkflowState::COMPLETED) + ->and($instance->getData()['steps']['approve']['resumed_by'])->toBe(Wait::TIMER) + ->and($instance->getCompletedSteps())->toBe(['approve', 'reject']); + + // Without a deadline only the signal ends the wait. + expect($this->engine->getInstance('po-2')->getState())->toBe(WorkflowState::WAITING); + }); + + test('a signal before the deadline wins, and the timer no longer applies', function () { + $this->engine->start('po-1', approvalFlow('2030-01-01T00:00:00+00:00')); + $this->engine->signal('po-1', 'decided', ['decision' => 'approved']); + + expect($this->engine->resumeDue(new DateTimeImmutable('2031-01-01')))->toBe([]); + expect($this->engine->getInstance('po-1')->getCompletedSteps())->toBe(['approve', 'order']); + }); + + test('a delay step suspends instead of sleeping, and continues once due', function () { + $start = microtime(true); + $this->engine->start('d-1', [ + 'name' => 'reminder', + 'steps' => [ + ['id' => 'wait', 'action' => DelayAction::class, 'config' => ['hours' => 2]], + ['id' => 'remind', 'action' => LogAction::class, 'config' => ['message' => 'reminder']], + ], + 'transitions' => [['from' => 'wait', 'to' => 'remind']], + ]); + + expect(microtime(true) - $start)->toBeLessThan(0.5); + expect($this->engine->getInstance('d-1')->getState())->toBe(WorkflowState::WAITING); + expect($this->engine->resumeDue(new DateTimeImmutable('+1 hour')))->toBe([]); + expect($this->engine->resumeDue(new DateTimeImmutable('+3 hours')))->toBe(['d-1']); + expect($this->engine->getInstance('d-1')->getCompletedSteps())->toBe(['wait', 'remind']); + }); +}); + +describe('optimistic locking', function () { + test('a save from a stale copy is refused and writes nothing', function () { + $this->engine->start('po-1', approvalFlow()); + $stale = $this->storage->load('po-1'); + + $this->engine->signal('po-1', 'decided', ['decision' => 'approved']); + + $stale->setErrorMessage('overwritten'); + expect(fn () => $this->storage->save($stale))->toThrow(ConcurrentModificationException::class); + expect($this->engine->getInstance('po-1')->getState())->toBe(WorkflowState::COMPLETED) + ->and($this->engine->getInstance('po-1')->getErrorMessage())->toBeNull(); + }); + + test('two approvers at once: the second signal finds nothing to wait for', function () { + $this->engine->start('po-1', approvalFlow()); + $first = $this->storage->load('po-1'); + $second = $this->storage->load('po-1'); + $executor = (fn () => $this->executor)->call($this->engine); + + $executor->resumeWait($first, 'decided', ['decision' => 'approved']); + + expect(fn () => $executor->resumeWait($second, 'decided', ['decision' => 'rejected'])) + ->toThrow(ConcurrentModificationException::class); + expect($this->engine->getInstance('po-1')->getCompletedSteps())->toBe(['approve', 'order']); + }); + + test('revisions count saves, starting from one', function () { + $storage = new InMemoryStorage; + (new WorkflowEngine($storage))->start('po-1', approvalFlow()); + + expect($storage->load('po-1')->getRevision())->toBeGreaterThan(1); + }); +}); + +describe('definition fingerprint', function () { + test('is the same for the same content in any key order, and changes with the content', function () { + $a = WorkflowDefinition::fromArray(approvalFlow()); + $reordered = approvalFlow(); + $reordered = array_reverse($reordered, true); + $b = WorkflowDefinition::fromArray($reordered); + $changed = approvalFlow(); + $changed['steps'][1]['config']['message'] = 'ordering now'; + + expect($a->fingerprint())->toBe($b->fingerprint()) + ->and($a->fingerprint())->not->toBe(WorkflowDefinition::fromArray($changed)->fingerprint()); + }); +}); + +class SlowAction implements WorkflowAction +{ + /** @param array $config */ + public function __construct(public array $config = [], public mixed $logger = null) {} + + public function execute(WorkflowContext $context): ActionResult + { + usleep(1_200_000); + + return ActionResult::success(['slow' => true]); + } + + public function canExecute(WorkflowContext $context): bool + { + return true; + } + + public function getName(): string + { + return 'Slow'; + } + + public function getDescription(): string + { + return 'Takes 1.2 s'; + } +} + +describe('step timeouts', function () { + test('are not enforced with signals unless asked for', function () { + $this->engine->start('t-1', ['name' => 'slow', 'steps' => [['id' => 'slow', 'action' => SlowAction::class, 'timeout' => '1s']]]); + + expect($this->engine->getInstance('t-1')->getState())->toBe(WorkflowState::COMPLETED); + }); + + test('are enforced with signalTimeouts in a CLI worker', function () { + $engine = new WorkflowEngine(new InMemoryStorage, signalTimeouts: true); + + expect(fn () => $engine->start('t-1', ['name' => 'slow', 'steps' => [['id' => 'slow', 'action' => SlowAction::class, 'timeout' => '1s']]])) + ->toThrow(StepExecutionException::class, "Step 'slow' failed: Step execution timed out after 1 seconds"); + })->skip(! function_exists('pcntl_alarm'), 'needs pcntl'); + + test('a conflict while running is not recorded as a failure', function () { + $this->engine->start('po-1', approvalFlow()); + $stale = $this->storage->load('po-1'); + $this->engine->signal('po-1', 'decided', ['decision' => 'approved']); + $executor = (fn () => $this->executor)->call($this->engine); + + expect(fn () => $executor->resumeWait($stale, 'decided', ['decision' => 'rejected']))->toThrow(ConcurrentModificationException::class); + expect($this->events->hasDispatched(WorkflowFailedEvent::class))->toBeFalse(); + }); +});