Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<step id>` (`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
Expand Down
34 changes: 24 additions & 10 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand All @@ -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)
Expand Down Expand Up @@ -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) |

Expand All @@ -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.<step id>` 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
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
48 changes: 40 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.<step id>` (`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
Expand Down Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 1 addition & 5 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -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#'
9 changes: 4 additions & 5 deletions src/Actions/ConditionAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand All @@ -67,11 +71,6 @@ protected function doExecute(WorkflowContext $context): ActionResult
}
}

/**
* Enhanced condition evaluation with PHP 8.3+ match expressions
*
* @param array<string, mixed> $data
*/
/**
* Evaluate a condition expression against workflow data.
*
Expand Down
28 changes: 19 additions & 9 deletions src/Actions/DelayAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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
Expand Down Expand Up @@ -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')]);
}
}
Loading
Loading