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
161 changes: 161 additions & 0 deletions docs/configuration/publishing-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,164 @@ Then register it in `config/workflows.php`:
The redactor receives the current value plus context such as `path`, `category`, `workflow_instance_id`, `workflow_run_id`, and `workflow_type`. The export calls it for workflow argument/output payloads, history-event payloads, command payload/context, update payloads, task payloads, activity payloads, and failure message/file/trace diagnostics. The resulting bundle includes `redaction.applied`, `redaction.policy`, and `redaction.paths` so downstream tooling can tell which policy shaped the artifact.

Every export also includes an `integrity` block computed after redaction. The checksum uses `canonicalization = json-recursive-ksort-v1` and `checksum_algorithm = sha256`; when `signing_key` is configured, the same canonical payload is signed with `signature_algorithm = hmac-sha256` and the optional `signing_key_id` is reported as `key_id`. Keep the signing key outside the exported artifact and rotate the key id when downstream verifiers need to distinguish keys.

## Worker interceptors {#worker-interceptors}

Worker interceptors are available in Workflow 2.42.0 and later.
Embedded Durable Workflow runs ordered worker interceptors around the workflow
tasks, activities, queries and update validations it executes in your
application's processes. Use them for audit logging, metric tags, tenant context or tracing that you want to
write once instead of in every workflow and activity. The hook shape matches the
[Python](../polyglot/python.md#worker-interceptors),
[PHP](../polyglot/php.md#worker-interceptors) and
[Rust](../polyglot/rust.md#worker-interceptors) SDK interceptors.

List interceptor classes under `workflows.v2.interceptors` in
`config/workflows.php`. They are resolved from the Laravel container, so
constructor injection works, and they run in the listed order; the first is the
outermost wrapper.

```php
'v2' => [
// ...
'interceptors' => [
App\Workflows\AuditInterceptor::class,
],
],
```

Each interceptor implements `Workflow\V2\Interceptors\WorkerInterceptor`.
Extend `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` to implement only
the hooks you need, and call `$next($context)` to continue the chain. This audit
interceptor logs each committed workflow task and every activity attempt:

```php
namespace App\Workflows;

use Illuminate\Support\Facades\DB;
use Psr\Log\LoggerInterface;
use Workflow\V2\Interceptors\ActivityInterceptorContext;
use Workflow\V2\Interceptors\PassthroughWorkerInterceptor;
use Workflow\V2\Interceptors\WorkflowTaskInterceptorContext;
use Workflow\V2\Interceptors\WorkflowTaskOutcome;

final class AuditInterceptor extends PassthroughWorkerInterceptor
{
public function __construct(private readonly LoggerInterface $audit)
{
}

public function executeWorkflowTask(WorkflowTaskInterceptorContext $context, callable $next): WorkflowTaskOutcome
{
$outcome = $next($context);
// The task commits after the chain returns; log only once it has.
DB::afterCommit(fn () => $this->audit->info('workflow task', [
'workflow_id' => $context->workflowId,
'run_id' => $context->runId,
'attempt' => $context->workflowTaskAttempt,
'recorded' => $outcome->historyEventTypes,
]));

return $outcome;
}

public function executeActivity(ActivityInterceptorContext $context, callable $next): mixed
{
$this->audit->info('activity started', [
'activity_type' => $context->activityType,
'attempt' => $context->attemptNumber,
'workflow_id' => $context->workflowId,
]);
try {
return $next($context);
} finally {
$this->audit->info('activity finished', ['activity_type' => $context->activityType]);
}
}
}
```

The container builds the configured interceptors for each task. Bind one as a
singleton when it must keep state between tasks.

| Hook | Context | `$next` returns |
| --- | --- | --- |
| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (also `replayState()`) | `WorkflowTaskOutcome` with `historyEventTypes`, `runStatus`, `nextTaskId` |
| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | the activity result |
| `executeQueryTask($context, $next)` | `workerId` (always null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (always `Replaying`) | the query result |
| `executeUpdateValidation($context, $next)` | `workerId` (always null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (always `Replaying`) | `UpdateValidationOutcome` with `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` |

`task` is an array snapshot of the claimed task row, never the model itself.
`workerId` identifies the queue worker process by host and process ID. Queries
and update validations run in the calling process, so their `workerId` is null.

Workflow-task interceptors cannot change what a workflow records:

- `executeWorkflowTask` wraps the workflow task inside its database
transaction, once per task attempt. `replaying` is `true` when earlier
workflow tasks already recorded commands for the run. It is not a
deduplication key: `historyEventTypes` lists only the events this task
appended.
- `replayState()` gives the same answer as a
`Workflow\V2\Enums\WorkflowReplayState`, the enum `Workflow::replayState()`
uses; the interceptor's value is fixed for the task.
- Hook side effects run before the task commits and can repeat when an attempt
is retried, so defer them with `DB::afterCommit()` or key them on `taskId` and
`workflowTaskAttempt`.
- The engine commits the history the workflow code produced. The outcome is a
read-only view; returning a different outcome, or passing a different context
to `$next`, changes nothing.
- A failure from the workflow code reaches the engine unchanged, even if an
interceptor catches it and returns normally.
- If an interceptor throws out of the chain, skips `$next` or calls it more than
once, the task's transaction rolls back, so nothing is recorded. The task is
released with `WorkflowTaskInterceptorFailed` as its last error and retried
after the usual repair backoff. An outer interceptor may still catch an
exception an inner interceptor threw after `$next` and let the task commit; a
skipped or repeated `$next` always fails the task.
- Hooks run while the run and task rows are locked, so keep them short. They
must not commit or roll back the surrounding transaction, and must not send
commands such as signals to the run they are wrapping; a change to the run's
recorded state fails the task on every attempt.
- Local activities run inside the workflow task, so a hook that keeps failing
after `$next` makes each retry run those local activities again.

Update-validation interceptors wrap the replay and the validator call that run
before an update with an `#[UpdateValidator]` is accepted. Updates without a
validator don't run the hook. The hooks observe the decision; they cannot
change it:

- The engine acts on the validator's own outcome. Returning a different
`UpdateValidationOutcome`, or passing different arguments to `$next`, changes
nothing; the validator always receives the update's arguments.
- If a hook throws, skips `$next` or calls it more than once, the update is
refused with `UpdateValidationFailedException` and nothing is recorded, so a
hook can never let an update through unvalidated.
- The hook runs inside the update's admission transaction, while the run's rows
are locked, so keep it short. Defer side effects with `DB::afterCommit()`;
writes a hook makes commit or roll back with the admission. Hook code runs
outside the workflow fiber, so it cannot schedule durable work for the run.

Activity and query interceptors may change arguments with
`$context->withArguments(...)` and may change the returned value, because an
activity result is recorded once and a query records nothing. Rewritten query
arguments are validated against the query contract again. Activity exceptions
pass through every interceptor unless one handles them, and then go through the
activity's normal retry policy. Activity interceptors wrap queued and local
activities; `local` tells them apart. Mocked activities in
`WorkflowStub::fake()` do not run interceptors.

When [embedded tracing](../monitoring.md#embedded-tracing) is enabled, the
built-in workflow and activity spans stay outermost, so interceptors run inside
the active span and can add attributes or child spans.

Interceptors wrap the queue jobs, local activities and queries this package
runs. Tasks handed to external SDK workers through the worker task bridges run
under that SDK's own interceptors. The worker bridge's `execute` route, which
runs a claimed workflow task in-process for a bridge caller, does not run
workflow-task interceptors. An entry in `workflows.v2.interceptors` that
cannot be resolved fails each path its own way: a queued workflow task is
released and retried, an activity attempt fails under its retry policy, and a
query throws to its caller. Check the list when you deploy. The
[embedded interceptor guide](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md)
has the full contract.
147 changes: 147 additions & 0 deletions docs/polyglot/php.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,153 @@ service-mode bridge, including drain and rollback. Use
[Deployment Modes](/docs/polyglot/deployment-modes/) for the wider runtime
boundary comparison.

## Worker interceptors {#worker-interceptors}

Worker interceptors are available in PHP SDK 3.32.0 and later. Pass ordered
`interceptors` to `Worker::create()` (or the `Worker` constructor) to add audit
logging, metric tags, tenant context or tracing around every task once,
instead of in each handler. Each interceptor implements
`DurableWorkflow\Worker\Interceptor\WorkerInterceptor`; extend
`PassthroughWorkerInterceptor` to implement only the hooks you need. The hook
shape matches the [Python](./python.md#worker-interceptors) and
[Rust](./rust.md#worker-interceptors) SDK interceptors.

This audit interceptor logs every workflow task outcome and activity attempt:

```php
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\Interceptor\ActivityInterceptorContext;
use DurableWorkflow\Worker\Interceptor\PassthroughWorkerInterceptor;
use DurableWorkflow\Worker\Interceptor\WorkflowTaskInterceptorContext;
use DurableWorkflow\Worker\Interceptor\WorkflowTaskOutcome;
use Psr\Log\LoggerInterface;

final class AuditInterceptor extends PassthroughWorkerInterceptor
{
public function __construct(private readonly LoggerInterface $audit)
{
}

public function executeWorkflowTask(WorkflowTaskInterceptorContext $context, callable $next): WorkflowTaskOutcome
{
$outcome = $next($context);
$this->audit->info('workflow task', [
'workflow_id' => $context->workflowId,
'workflow_type' => $context->workflowType,
'attempt' => $context->workflowTaskAttempt,
'replayed_history' => $context->replaying,
'commands' => $outcome->commandTypes(),
]);

return $outcome;
}

public function executeActivity(ActivityInterceptorContext $context, callable $next): mixed
{
$this->audit->info('activity started', [
'activity_type' => $context->activityType,
'attempt' => $context->attemptNumber,
'workflow_id' => $context->workflowId,
]);
try {
return $next($context);
} finally {
$this->audit->info('activity finished', ['activity_type' => $context->activityType]);
}
}
}

$worker = Worker::create($client, 'orders', container: $container,
interceptors: [AuditInterceptor::class]);
```

| Hook | Context | `$next` returns |
| --- | --- | --- |
| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (also `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` with a copy of the commands |
| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | the activity result |
| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | the query result |
| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` with `approved`, `reason`, `message`, `failureType`, `validationErrors` |

Interceptors run in the order you list them. The first interceptor is the
outermost wrapper: it runs first before the task and last after it. Each hook
calls `$next($context)` to continue the chain. When tracing is configured, the
built-in worker spans stay outermost, so interceptors run inside the active
task span.

Workflow-task interceptors cannot break determinism:

- `executeWorkflowTask` wraps the workflow code that produces one workflow
task's commands, once per task attempt. `replaying` is `true` when earlier
workflow tasks already recorded commands, so the workflow code re-ran that
committed prefix first. The outcome holds only the commands this task adds;
replayed commands are never resubmitted.
- `replayState()` reports the same thing as the `WorkflowReplayState` that
`WorkflowContext::replayState()` uses: `Replaying` or `Executing`.
- A retried attempt (`workflowTaskAttempt > 1`) can repeat an outcome whose task
failed, so make external audit writes idempotent.
- Update tasks (`updateId` set) run the update handler against committed state
without re-running the workflow body; for them `replaying` only reports that
earlier commands exist.
- The worker submits exactly the commands the workflow code produced. The
outcome is a copy; returning a different outcome, or passing a different
context to `$next`, changes nothing.
- A failure from the workflow code reaches the worker unchanged, even if an
interceptor catches it and returns normally.
- An exception thrown by an interceptor fails the workflow task. Nothing is
recorded and the Server retries the task. Skipping `$next`, or calling it more
than once, fails the task with `WorkflowTaskInterceptorViolation`.

Update-validation interceptors (`executeUpdateValidation()`) wrap the run of an
update's validator before the Server accepts the update. They see the decision
as a read-only `UpdateValidationOutcome` and cannot change the decision, the
update's arguments or the history the validator reads: the validator always
runs read-only in its own Fiber with the worker's copy of the task, and the
worker answers with the validator's own decision. An exception from the
interceptor, or skipping `$next` or calling it more than once
(`UpdateValidationInterceptorViolation`), answers the task with
`update_validation_worker_failed`, so the update is not accepted and the caller
can retry.

Activity and query interceptors may change arguments with
`$context->withArguments(...)` and may change the returned value, because
activity results are recorded once and queries record nothing. Activity
exceptions pass through every interceptor unless one handles them. Activity
interceptors wrap remote and local activities; `local` tells them apart. With
cooperative cancellation, remote, cooperative local and prepared local activity
callbacks and their interceptors run in the activity's child process, so memory
changes there do not reach the worker process.

### Container and framework configuration {#worker-interceptor-configuration}

Pass interceptor instances or class names. Class names are resolved from the
PSR-11 container passed to the worker, the same way attributed handlers are.
Without a container, a class name must have no required constructor arguments.

In Laravel and Symfony service mode, list interceptor classes under
`worker.interceptors`. They are resolved from the framework container in that
order:

```php
// config/durable-workflow.php
'worker' => [
'interceptors' => [App\Durable\AuditInterceptor::class],
],
```

```yaml
# config/packages/durable_workflow.yaml
durable_workflow:
worker:
interceptors:
- App\Durable\AuditInterceptor
```

Embedded Laravel workflows configure their own interceptors under
`workflows.v2.interceptors`; see
[embedded worker interceptors](../configuration/publishing-config.md#worker-interceptors).
The [PHP SDK reference](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors)
has the full interceptor contract.

## Query results with binary values {#query-binary-results}

PHP SDK 3.18.2 fixes query completion for valid Avro results containing nested
Expand Down
Loading