diff --git a/docs/configuration/publishing-config.md b/docs/configuration/publishing-config.md index 364cc50fca0..80f524a5eaf 100644 --- a/docs/configuration/publishing-config.md +++ b/docs/configuration/publishing-config.md @@ -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. diff --git a/docs/polyglot/php.md b/docs/polyglot/php.md index a1940c649a0..d607359d11b 100644 --- a/docs/polyglot/php.md +++ b/docs/polyglot/php.md @@ -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 diff --git a/docs/polyglot/rust.md b/docs/polyglot/rust.md index ece6090dd6e..cf6fcb19cbd 100644 --- a/docs/polyglot/rust.md +++ b/docs/polyglot/rust.md @@ -295,6 +295,136 @@ cargo run --features metrics-prometheus --example metrics_prometheus For OpenTelemetry metrics, implement the recorder using your existing meter: count-unit (`1`) counters and second-unit (`s`) histograms with the exact names/tags above. Provider, aggregation, resource labels and exporter lifecycle remain application-owned. This is separate from execution tracing. See the [recorder API](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), [Prometheus adapter API](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) and [released metrics contract](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Worker interceptors {#worker-interceptors} + +Worker interceptors are available in Rust SDK 4.25.0 and later. They add +cross-cutting behaviour, such as audit logging, metric tags or tenant context, +once for every task a worker runs. Implement `WorkerInterceptor` and register it +with `Worker::interceptor`, or several with `Worker::interceptors`. Every hook +defaults to passing the call on, so implement only the hooks you need; +`PassthroughWorkerInterceptor` is a no-op interceptor. The hook shape matches +the [Python](./python.md#worker-interceptors) and +[PHP](./php.md#worker-interceptors) SDK interceptors. + +This audit interceptor logs every workflow task outcome and activity attempt: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +The repository's +[`audit_interceptor` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +runs the same interceptor against a self-hosted Server. + +| Hook | Runs around | Context | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | one workflow task, including replay | `WorkflowTaskInterceptorContext` | `next.run()` returns a read-only `WorkflowTaskOutcome` | +| `execute_activity` | one activity or local activity attempt | `ActivityInterceptorContext` | `next.run(context)` returns the activity result | +| `execute_query_task` | one query task | `QueryTaskInterceptorContext` | `next.run()` returns the query result or `QueryTaskFailure` | +| `execute_update_validation_task` | one update-validation task | `UpdateValidationInterceptorContext` | `next.run()` returns a read-only `UpdateValidationOutcome` | + +Contexts are read-only. They carry the worker id, task queue, namespace and the +task's identity: task id, workflow id, run id, workflow or activity type, +attempt and, for workflow tasks, history length, the task's trace carrier and +replay state. An activity context also exposes the decoded arguments, whether +the attempt is a local activity, and the `ActivityContext` the handler receives. +An update-validation context carries the validation task id and attempt, the +workflow id, run id and type, the update name and the trace carrier. + +Interceptors run in registration order. The first one registered is the +outermost: it runs first before the task and last after it. Each hook must call +`next` to continue the chain; the innermost `next` runs the SDK's own handling. +Errors from the task pass back out through every interceptor unchanged unless +an activity or query interceptor deliberately handles them. Activity +interceptors can change arguments with `context.with_args(..)` and transform +results, and activity and query interceptors may answer without calling `next`. +Built-in `ExecutionTelemetry` spans stay outermost around the whole chain. + +Workflow-task interceptors cannot change what a workflow records: + +- `next.run()` takes no input, so the task always runs as received. +- The worker submits exactly the commands the workflow produced. The outcome is + a read-only view of them. +- If the task fails, the worker reports that failure even when an interceptor + returns `Ok`. Interceptors see it as `Error::WorkflowTaskFailed`, a read-only + description with `.kind()`, `.message()` and `.debug()`; the worker keeps the + original error. +- An interceptor error after the task succeeded, or returning without running + `next`, fails the workflow task with `Error::WorkflowTaskInterceptor`. Nothing + is recorded and the Server retries the task. The workflow does not fail. +- Interceptors run on every workflow task. `context.replay_state()` is + `Replaying` when the task re-ran commands committed by earlier tasks before + new execution, and `Executing` for a task with no committed history. The + worker never resubmits replayed commands, so an outcome's commands are always + new for that task: audit every successful outcome, whatever the replay state. +- If a task fails after an interceptor observed it, its retry can repeat the + same outcome; `context.attempt()` above 1 identifies a retry, so make external + audit writes idempotent. + +Update-validation interceptors cannot change whether an update is accepted: + +- `next.run()` takes no input, so the validator always runs on the task as + received, and the worker sends the validator's own approval or rejection. + The outcome is a read-only view: `is_approved()`, `is_rejected()`, + `is_worker_failure()`, `reason()` and `rejection()`. +- An interceptor error, returning or failing without running `next`, or + dropping the validation partway makes the worker report + `update_validation_worker_failed` instead. The update is not accepted, and + the caller's retry with the same request id asks the validator again. + +The offline `WorkflowEnvironment` runs activity interceptors registered on the +worker it wraps. It has no workflow or query tasks, so those hooks do not run +there. See the +[Rust SDK README](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors) +for the full interceptor contract. + ## Worker task concurrency {#worker-task-concurrency} The bounded worker lanes below require Rust SDK **4.3.1 or newer**. Check the crate in `Cargo.lock` before using them: the installation pin above belongs to a separate qualified artifact tuple and may select an older SDK. The [published-package acceptance](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) verifies three configured slots, a fourth callback admitted after a slot is released, and seven completed workflows including a handled activity failure. This guide does not change the Server protocol requirements above. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/de/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index ce2a2d1e563..f962dabfe85 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -348,3 +348,179 @@ Wenn `signing_key` konfiguriert ist, wird derselbe kanonische Payload mit als `key_id` ausgegeben. Halten Sie den Signaturschlüssel außerhalb des exportierten Artefakts und wechseln Sie die Schlüssel-ID, wenn nachgelagerte Prüfer Schlüssel unterscheiden müssen. + +## Worker-Interceptors {#worker-interceptors} + +Worker-Interceptors sind ab Workflow 2.42.0 verfügbar. +Das eingebettete Durable Workflow führt geordnete Worker-Interceptors um die +Workflow-Tasks, Aktivitäten, Abfragen und Update-Validierungen aus, die es in +den Prozessen Ihrer Anwendung ausführt. Verwenden Sie sie für Audit-Logging, +Metrik-Tags, Mandantenkontext oder Tracing, das Sie einmal schreiben möchten +statt in jedem Workflow und jeder Aktivität. Die Form der Hooks entspricht den +Interceptors des [Python](../polyglot/python.md#worker-interceptors)-, +[PHP](../polyglot/php.md#worker-interceptors)- und +[Rust](../polyglot/rust.md#worker-interceptors)-SDK. + +Listen Sie Interceptor-Klassen unter `workflows.v2.interceptors` in +`config/workflows.php` auf. Sie werden aus dem Laravel-Container aufgelöst, daher +funktioniert Konstruktorinjektion, und sie laufen in der aufgeführten +Reihenfolge; der erste ist der äußerste Wrapper. + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +Jeder Interceptor implementiert `Workflow\V2\Interceptors\WorkerInterceptor`. +Erweitern Sie `Workflow\V2\Interceptors\PassthroughWorkerInterceptor`, um nur die +benötigten Hooks zu implementieren, und rufen Sie `$next($context)` auf, um die +Kette fortzusetzen. Dieser Audit-Interceptor protokolliert jeden +festgeschriebenen Workflow-Task und jeden Aktivitätsversuch: + +```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]); + } + } +} +``` + +Der Container erstellt die konfigurierten Interceptors für jeden Task. Binden Sie +einen als Singleton, wenn er zwischen Tasks Zustand behalten muss. + +| Hook | Kontext | Rückgabe von `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (auch `replayState()`) | `WorkflowTaskOutcome` mit `historyEventTypes`, `runStatus`, `nextTaskId` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | das Aktivitätsergebnis | +| `executeQueryTask($context, $next)` | `workerId` (immer null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (immer `Replaying`) | das Abfrageergebnis | +| `executeUpdateValidation($context, $next)` | `workerId` (immer null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (immer `Replaying`) | `UpdateValidationOutcome` mit `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` | + +`task` ist ein Array-Snapshot der beanspruchten Task-Zeile, niemals das Modell +selbst. `workerId` identifiziert den Queue-Worker-Prozess anhand von Host und +Prozess-ID. Abfragen und Update-Validierungen laufen im aufrufenden Prozess, +daher ist ihre `workerId` null. + +Interceptors für Workflow-Tasks können nicht ändern, was ein Workflow aufzeichnet: + +- `executeWorkflowTask` umschließt den Workflow-Task innerhalb seiner + Datenbanktransaktion, einmal pro Task-Versuch. `replaying` ist `true`, wenn + frühere Workflow-Tasks bereits Befehle für den Lauf aufgezeichnet haben. Es ist + kein Deduplizierungsschlüssel: `historyEventTypes` listet nur die Ereignisse + auf, die dieser Task angehängt hat. +- `replayState()` liefert dieselbe Antwort als + `Workflow\V2\Enums\WorkflowReplayState`, die Enum, die auch + `Workflow::replayState()` verwendet; der Wert des Interceptors steht für den + Task fest. +- Seiteneffekte von Hooks laufen, bevor der Task festgeschrieben wird, und können + sich wiederholen, wenn ein Versuch wiederholt wird; verschieben Sie sie daher + mit `DB::afterCommit()` oder verknüpfen Sie sie mit `taskId` und + `workflowTaskAttempt` als Schlüssel. +- Die Engine schreibt die Historie fest, die der Workflow-Code erzeugt hat. Das + Ergebnis ist eine schreibgeschützte Sicht; die Rückgabe eines anderen + Ergebnisses oder die Übergabe eines anderen Kontexts an `$next` ändert nichts. +- Ein Fehler aus dem Workflow-Code erreicht die Engine unverändert, selbst wenn + ein Interceptor ihn abfängt und normal zurückkehrt. +- Wenn ein Interceptor eine Ausnahme aus der Kette heraus auslöst, `$next` + überspringt oder mehr als einmal aufruft, wird die Transaktion des Tasks + zurückgerollt, sodass nichts aufgezeichnet wird. Der Task wird mit + `WorkflowTaskInterceptorFailed` als letztem Fehler freigegeben und nach dem + üblichen Reparatur-Backoff wiederholt. Ein äußerer Interceptor kann eine + Ausnahme, die ein innerer Interceptor nach `$next` ausgelöst hat, dennoch + abfangen und den Task festschreiben lassen; ein übersprungenes oder + wiederholtes `$next` lässt den Task immer fehlschlagen. +- Hooks laufen, während die Lauf- und Task-Zeilen gesperrt sind, halten Sie sie + daher kurz. Sie dürfen die umgebende Transaktion weder festschreiben noch + zurückrollen und keine Befehle wie Signale an den Lauf senden, den sie + umschließen; eine Änderung am aufgezeichneten Zustand des Laufs lässt den Task + bei jedem Versuch fehlschlagen. +- Lokale Aktivitäten laufen innerhalb des Workflow-Tasks, daher führt ein Hook, + der nach `$next` wiederholt fehlschlägt, diese lokalen Aktivitäten bei jeder + Wiederholung erneut aus. + +Update-Validierungs-Interceptors umschließen das Replay und den Aufruf des +Validators, die laufen, bevor ein Update mit einem `#[UpdateValidator]` +angenommen wird. Updates ohne Validator führen den Hook nicht aus. Die Hooks +beobachten die Entscheidung; ändern können sie sie nicht: + +- Die Engine handelt nach dem eigenen Ergebnis des Validators. Die Rückgabe + eines anderen `UpdateValidationOutcome` oder die Übergabe anderer Argumente an + `$next` ändert nichts; der Validator erhält immer die Argumente des Updates. +- Wirft ein Hook, überspringt er `$next` oder ruft er es mehr als einmal auf, + wird das Update mit `UpdateValidationFailedException` abgelehnt und nichts + aufgezeichnet; ein Hook kann ein Update also nie unvalidiert durchlassen. +- Der Hook läuft innerhalb der Annahmetransaktion des Updates, während die + Zeilen des Laufs gesperrt sind, halten Sie ihn daher kurz. Verschieben Sie + Seiteneffekte mit `DB::afterCommit()`; Schreibvorgänge eines Hooks werden + zusammen mit der Annahme festgeschrieben oder zurückgerollt. Hook-Code läuft + außerhalb der Workflow-Fiber und kann daher keine dauerhafte Arbeit für den + Lauf einplanen. + +Aktivitäts- und Abfrage-Interceptors dürfen Argumente mit +`$context->withArguments(...)` ändern und den Rückgabewert verändern, weil ein +Aktivitätsergebnis einmal aufgezeichnet wird und eine Abfrage nichts aufzeichnet. +Umgeschriebene Abfrageargumente werden erneut gegen den Abfragevertrag validiert. +Aktivitätsausnahmen durchlaufen jeden Interceptor, sofern keiner sie behandelt, +und unterliegen dann der normalen Wiederholungsrichtlinie der Aktivität. +Aktivitäts-Interceptors umschließen Aktivitäten aus der Queue und lokale +Aktivitäten; `local` unterscheidet sie. Gemockte Aktivitäten in +`WorkflowStub::fake()` führen keine Interceptors aus. + +Wenn [eingebettetes Tracing](../monitoring.md#embedded-tracing) aktiviert ist, +bleiben die eingebauten Workflow- und Aktivitäts-Spans am weitesten außen, sodass +Interceptors innerhalb des aktiven Spans laufen und Attribute oder Kind-Spans +hinzufügen können. + +Interceptors umschließen die Queue-Jobs, lokalen Aktivitäten und Abfragen, die +dieses Paket ausführt. Tasks, die über die Worker-Task-Bridges an externe +SDK-Worker übergeben werden, laufen unter den eigenen Interceptors dieses SDK. Die +`execute`-Route der Worker-Bridge, die einen beanspruchten Workflow-Task für einen +Bridge-Aufrufer im Prozess ausführt, führt keine Workflow-Task-Interceptors aus. +Ein Eintrag in `workflows.v2.interceptors`, der nicht aufgelöst werden kann, lässt +jeden Pfad auf eigene Weise fehlschlagen: Ein Workflow-Task aus der Queue wird +freigegeben und wiederholt, ein Aktivitätsversuch schlägt gemäß seiner +Wiederholungsrichtlinie fehl, und eine Abfrage löst eine Ausnahme bei ihrem +Aufrufer aus. Prüfen Sie die Liste beim Deployment. Der +[Leitfaden zu eingebetteten Interceptors](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md) +enthält den vollständigen Vertrag. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md index 2c7859032e6..a8de63d3eea 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -360,6 +360,160 @@ ausgelieferten Service-Modus-Brücke, einschließlich Auslaufen und Rollback. [Bereitstellungsmodi](/docs/polyglot/deployment-modes/) vergleicht die Laufzeitgrenzen umfassender. +## Worker-Interceptors {#worker-interceptors} + +Worker-Interceptors sind ab PHP SDK 3.32.0 verfügbar. Übergeben +Sie geordnete `interceptors` an `Worker::create()` (oder den `Worker`-Konstruktor), +um Audit-Logging, Metrik-Tags, Mandantenkontext oder Tracing einmal um jeden Task +herum hinzuzufügen, statt in jedem Handler. Jeder Interceptor implementiert +`DurableWorkflow\Worker\Interceptor\WorkerInterceptor`; erweitern Sie +`PassthroughWorkerInterceptor`, um nur die benötigten Hooks zu implementieren. Die +Form der Hooks entspricht den Interceptors des [Python](./python.md#worker-interceptors)- +und des [Rust](./rust.md#worker-interceptors)-SDK. + +Dieser Audit-Interceptor protokolliert jedes Ergebnis eines Workflow-Tasks und +jeden Aktivitätsversuch: + +```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 | Kontext | Rückgabe von `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (auch `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` mit einer Kopie der Befehle | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | das Aktivitätsergebnis | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | das Abfrageergebnis | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` mit `approved`, `reason`, `message`, `failureType`, `validationErrors` | + +Interceptors laufen in der angegebenen Reihenfolge. Der erste Interceptor ist der +äußerste Wrapper: Er läuft vor dem Task als erster und nach ihm als letzter. Jeder +Hook ruft `$next($context)` auf, um die Kette fortzusetzen. Ist Tracing +konfiguriert, bleiben die eingebauten Worker-Spans am weitesten außen, sodass +Interceptors innerhalb des aktiven Task-Spans laufen. + +Interceptors für Workflow-Tasks können den Determinismus nicht verletzen: + +- `executeWorkflowTask` umschließt den Workflow-Code, der die Befehle eines + Workflow-Tasks erzeugt, einmal pro Task-Versuch. `replaying` ist `true`, wenn + frühere Workflow-Tasks bereits Befehle aufgezeichnet haben, sodass der + Workflow-Code zuerst dieses festgeschriebene Präfix erneut ausgeführt hat. Das + Ergebnis enthält nur die Befehle, die dieser Task hinzufügt; wiedergegebene + Befehle werden nie erneut übermittelt. +- `replayState()` meldet dasselbe als `WorkflowReplayState`, den auch + `WorkflowContext::replayState()` verwendet: `Replaying` oder `Executing`. +- Ein wiederholter Versuch (`workflowTaskAttempt > 1`) kann ein Ergebnis + wiederholen, dessen Task fehlgeschlagen ist; gestalten Sie externe + Audit-Schreibvorgänge daher idempotent. +- Update-Tasks (`updateId` gesetzt) führen den Update-Handler gegen den + festgeschriebenen Zustand aus, ohne den Workflow-Rumpf erneut auszuführen; bei + ihnen meldet `replaying` nur, dass frühere Befehle existieren. +- Der Worker übermittelt genau die Befehle, die der Workflow-Code erzeugt hat. Das + Ergebnis ist eine Kopie; die Rückgabe eines anderen Ergebnisses oder die + Übergabe eines anderen Kontexts an `$next` ändert nichts. +- Ein Fehler aus dem Workflow-Code erreicht den Worker unverändert, selbst wenn + ein Interceptor ihn abfängt und normal zurückkehrt. +- Eine von einem Interceptor ausgelöste Ausnahme lässt den Workflow-Task + fehlschlagen. Es wird nichts aufgezeichnet, und der Server wiederholt den Task. + Wird `$next` übersprungen oder mehr als einmal aufgerufen, schlägt der Task mit + `WorkflowTaskInterceptorViolation` fehl. + +Update-Validierungs-Interceptors (`executeUpdateValidation()`) umschließen die +Ausführung des Validators eines Updates, bevor der Server das Update annimmt. +Sie sehen die Entscheidung als schreibgeschütztes `UpdateValidationOutcome` und +können weder die Entscheidung noch die Argumente des Updates oder die Historie +ändern, die der Validator liest: Der Validator läuft immer schreibgeschützt in +seiner eigenen Fiber mit der Kopie des Tasks, die der Worker hält, und der +Worker antwortet mit der eigenen Entscheidung des Validators. Eine Ausnahme aus +dem Interceptor oder ein übersprungener oder mehrfacher Aufruf von `$next` +(`UpdateValidationInterceptorViolation`) beantwortet den Task mit +`update_validation_worker_failed`; das Update wird also nicht angenommen, und +der Aufrufer kann es erneut versuchen. + +Aktivitäts- und Abfrage-Interceptors dürfen Argumente mit +`$context->withArguments(...)` ändern und den Rückgabewert verändern, weil +Aktivitätsergebnisse einmal aufgezeichnet werden und Abfragen nichts aufzeichnen. +Aktivitätsausnahmen durchlaufen jeden Interceptor, sofern keiner sie behandelt. +Aktivitäts-Interceptors umschließen entfernte und lokale Aktivitäten; `local` +unterscheidet sie. Bei kooperativem Abbruch laufen die Callbacks entfernter, +kooperativer lokaler und vorbereiteter lokaler Aktivitäten samt ihren +Interceptors im Kindprozess der Aktivität, sodass Speicheränderungen dort den +Worker-Prozess nicht erreichen. + +### Container- und Framework-Konfiguration {#worker-interceptor-configuration} + +Übergeben Sie Interceptor-Instanzen oder Klassennamen. Klassennamen werden aus +dem an den Worker übergebenen PSR-11-Container aufgelöst, genauso wie Handler mit +Attributen. Ohne Container darf ein Klassenname keine erforderlichen +Konstruktorargumente haben. + +Im Service-Modus von Laravel und Symfony listen Sie Interceptor-Klassen unter +`worker.interceptors` auf. Sie werden in dieser Reihenfolge aus dem +Framework-Container aufgelöst: + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +Eingebettete Laravel-Workflows konfigurieren ihre eigenen Interceptors unter +`workflows.v2.interceptors`; siehe +[Interceptors für eingebettete Worker](../configuration/publishing-config.md#worker-interceptors). +Die [PHP-SDK-Referenz](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors) +enthält den vollständigen Interceptor-Vertrag. + ## Query-Ergebnisse mit Binärwerten {#query-binary-results} PHP SDK 3.18.2 korrigiert Query-Completions für gültige Avro-Ergebnisse mit verschachtelten `AvroBinaryValue`-Bytes. `result_envelope` bleibt maßgeblich. Das SDK lässt nur die optionale einfache `result`-Projektion weg, wenn sie nicht JSON-kodiert werden kann; gewöhnliche JSON-kompatible Ergebnisse behalten diese Projektion. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md index b69acc1bbff..337d5814eae 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -281,6 +281,149 @@ cargo run --features metrics-prometheus --example metrics_prometheus Für OpenTelemetry-Metriken implementieren Sie den Recorder mit Ihrem vorhandenen Meter: Zähler mit Einheit `1`, Histogramme mit Sekunden `s`, genau den Namen/Tags oben. Provider, Aggregation, Ressourcenlabels und Exporter-Lebenszyklus bleiben bei der Anwendung. Dies ist von Ausführungstracing getrennt. Siehe [Recorder-API](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), [Prometheus-API](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) und [veröffentlichten Vertrag](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Worker-Interceptors {#worker-interceptors} + +Worker-Interceptors sind ab Rust SDK 4.25.0 verfügbar. Sie fügen +querschnittliches Verhalten wie Audit-Logging, Metrik-Tags oder Mandantenkontext +einmal für jeden Task hinzu, den ein Worker ausführt. Implementieren Sie +`WorkerInterceptor` und registrieren Sie ihn mit `Worker::interceptor`, oder +mehrere mit `Worker::interceptors`. Jeder Hook reicht den Aufruf standardmäßig +weiter, implementieren Sie also nur die benötigten Hooks; +`PassthroughWorkerInterceptor` ist ein Interceptor ohne eigene Wirkung. Die Form +der Hooks entspricht den Interceptors des [Python](./python.md#worker-interceptors)- +und des [PHP](./php.md#worker-interceptors)-SDK. + +Dieser Audit-Interceptor protokolliert jedes Ergebnis eines Workflow-Tasks und +jeden Aktivitätsversuch: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +Das +[`audit_interceptor`-Beispiel](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +des Repositorys führt denselben Interceptor gegen einen selbst gehosteten Server aus. + +| Hook | Umschließt | Kontext | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | einen Workflow-Task, einschließlich Replay | `WorkflowTaskInterceptorContext` | `next.run()` gibt ein schreibgeschütztes `WorkflowTaskOutcome` zurück | +| `execute_activity` | einen Versuch einer Aktivität oder lokalen Aktivität | `ActivityInterceptorContext` | `next.run(context)` gibt das Aktivitätsergebnis zurück | +| `execute_query_task` | einen Abfrage-Task | `QueryTaskInterceptorContext` | `next.run()` gibt das Abfrageergebnis oder `QueryTaskFailure` zurück | +| `execute_update_validation_task` | einen Update-Validierungs-Task | `UpdateValidationInterceptorContext` | `next.run()` gibt ein schreibgeschütztes `UpdateValidationOutcome` zurück | + +Kontexte sind schreibgeschützt. Sie enthalten Worker-ID, Task-Queue, Namespace und +die Identität des Tasks: Task-ID, Workflow-ID, Lauf-ID, Workflow- oder +Aktivitätstyp, Versuch sowie bei Workflow-Tasks die Historienlänge, den +Trace-Carrier des Tasks und den Replay-Zustand. Ein Aktivitätskontext stellt +außerdem die decodierten Argumente bereit, ob der Versuch eine lokale Aktivität +ist, und den `ActivityContext`, den der Handler erhält. +Ein Update-Validierungs-Kontext enthält die ID und den Versuch des +Validierungs-Tasks, Workflow-ID, Lauf-ID und Workflow-Typ, den Update-Namen und +den Trace-Carrier. + +Interceptors laufen in der Reihenfolge ihrer Registrierung. Der zuerst +registrierte ist der äußerste: Er läuft vor dem Task als erster und nach ihm als +letzter. Jeder Hook muss `next` aufrufen, um die Kette fortzusetzen; das innerste +`next` führt die eigene Verarbeitung des SDK aus. Fehler aus dem Task laufen +unverändert durch jeden Interceptor zurück nach außen, sofern ein Aktivitäts- oder +Abfrage-Interceptor sie nicht bewusst behandelt. Aktivitäts-Interceptors können +Argumente mit `context.with_args(..)` ändern und Ergebnisse umwandeln, und +Aktivitäts- und Abfrage-Interceptors dürfen antworten, ohne `next` aufzurufen. +Eingebaute `ExecutionTelemetry`-Spans bleiben am weitesten außen um die gesamte +Kette. + +Interceptors für Workflow-Tasks können nicht ändern, was ein Workflow aufzeichnet: + +- `next.run()` nimmt keine Eingabe entgegen, daher läuft der Task immer so, wie er + empfangen wurde. +- Der Worker übermittelt genau die Befehle, die der Workflow erzeugt hat. Das + Ergebnis ist eine schreibgeschützte Sicht darauf. +- Schlägt der Task fehl, meldet der Worker diesen Fehler auch dann, wenn ein + Interceptor `Ok` zurückgibt. Interceptors sehen ihn als + `Error::WorkflowTaskFailed`, eine schreibgeschützte Beschreibung mit `.kind()`, + `.message()` und `.debug()`; der Worker behält den ursprünglichen Fehler. +- Ein Interceptor-Fehler nach erfolgreichem Task oder eine Rückkehr, ohne `next` + auszuführen, lässt den Workflow-Task mit `Error::WorkflowTaskInterceptor` + fehlschlagen. Es wird nichts aufgezeichnet, und der Server wiederholt den Task. + Der Workflow schlägt nicht fehl. +- Interceptors laufen bei jedem Workflow-Task. `context.replay_state()` ist + `Replaying`, wenn der Task vor neuer Ausführung von früheren Tasks + festgeschriebene Befehle erneut ausgeführt hat, und `Executing` bei einem Task + ohne festgeschriebene Historie. Der Worker übermittelt wiedergegebene Befehle + nie erneut, daher sind die Befehle eines Ergebnisses für diesen Task immer neu: + Protokollieren Sie jedes erfolgreiche Ergebnis im Audit, unabhängig vom Replay-Zustand. +- Schlägt ein Task fehl, nachdem ein Interceptor ihn beobachtet hat, kann seine + Wiederholung dasselbe Ergebnis wiederholen; `context.attempt()` über 1 + kennzeichnet eine Wiederholung, gestalten Sie externe Audit-Schreibvorgänge + daher idempotent. + +Update-Validierungs-Interceptors können nicht ändern, ob ein Update angenommen +wird: + +- `next.run()` nimmt keine Eingabe entgegen, daher läuft der Validator immer auf + dem Task, wie er empfangen wurde, und der Worker sendet die eigene Zustimmung + oder Ablehnung des Validators. Das Ergebnis ist eine schreibgeschützte Sicht: + `is_approved()`, `is_rejected()`, `is_worker_failure()`, `reason()` und + `rejection()`. +- Ein Interceptor-Fehler, ein Zurückkehren oder Scheitern, ohne `next` + auszuführen, oder ein Abbruch der Validierung mittendrin lässt den Worker + stattdessen `update_validation_worker_failed` melden. Das Update wird nicht + angenommen, und ein erneuter Versuch des Aufrufers mit derselben Request-ID + fragt den Validator erneut. + +Die Offline-`WorkflowEnvironment` führt Aktivitäts-Interceptors aus, die auf dem +von ihr umschlossenen Worker registriert sind. Sie hat keine Workflow- oder +Abfrage-Tasks, daher laufen diese Hooks dort nicht. Den vollständigen +Interceptor-Vertrag finden Sie in der +[README des Rust SDK](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors). + ## Parallelität der Worker-Tasks {#worker-task-concurrency} Die folgenden begrenzten Ausführungsspuren benötigen Rust SDK **4.3.1 oder neuer**. Prüfen Sie die Version in `Cargo.lock`: Die oben fixierte Installation gehört zu einem anderen qualifizierten Artefaktsatz und kann ein älteres SDK auswählen. Die [Akzeptanz des veröffentlichten Pakets](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) prüft drei konfigurierte Slots, einen vierten Callback erst nach Slot-Freigabe und sieben abgeschlossene Workflows einschließlich eines behandelten Aktivitätsfehlers. Die oben beschriebenen Server-Protokollanforderungen gelten weiterhin. diff --git a/i18n/de/source-hashes.json b/i18n/de/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/de/source-hashes.json +++ b/i18n/de/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/es/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/es/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index 4c0260eaa6b..6ace586ce2c 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -240,3 +240,178 @@ Después regístralo en `config/workflows.php`: El ocultador recibe el valor actual y contexto como `path`, `category`, `workflow_instance_id`, `workflow_run_id` y `workflow_type`. La exportación lo invoca para las cargas de argumentos/resultados del workflow, eventos de historial, carga/contexto de comandos, actualizaciones, tareas, actividades y diagnósticos de mensaje/archivo/traza de fallos. El paquete resultante incluye `redaction.applied`, `redaction.policy` y `redaction.paths` para que las herramientas posteriores identifiquen la política aplicada. Cada exportación incluye también un bloque `integrity` calculado después de la ocultación. La suma de comprobación usa `canonicalization = json-recursive-ksort-v1` y `checksum_algorithm = sha256`. Si se configura `signing_key`, la misma carga canónica se firma con `signature_algorithm = hmac-sha256` y el `signing_key_id` opcional se informa como `key_id`. Mantén la clave de firma fuera del artefacto y rota su identificador cuando los verificadores posteriores necesiten distinguir claves. + +## Interceptores de worker {#worker-interceptors} + +Los interceptores de worker están disponibles a partir de Workflow 2.42.0. Durable Workflow integrado ejecuta interceptores de worker +ordenados alrededor de las tareas de workflow, actividades, consultas y +validaciones de actualizaciones que ejecuta en los procesos de tu aplicación. +Úsalos para registros de auditoría, etiquetas de métricas, contexto de tenant o +trazas que quieras escribir una sola vez en lugar de en cada workflow y +actividad. La forma de los hooks coincide con la de los interceptores de los SDK +de [Python](../polyglot/python.md#worker-interceptors), +[PHP](../polyglot/php.md#worker-interceptors) y +[Rust](../polyglot/rust.md#worker-interceptors). + +Enumera las clases de interceptores en `workflows.v2.interceptors` dentro de +`config/workflows.php`. Se resuelven desde el contenedor de Laravel, de modo que +la inyección por constructor funciona, y se ejecutan en el orden indicado; el +primero es el envoltorio más externo. + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +Cada interceptor implementa `Workflow\V2\Interceptors\WorkerInterceptor`. +Extiende `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` para +implementar solo los hooks que necesites, y llama a `$next($context)` para +continuar la cadena. Este interceptor de auditoría registra cada tarea de +workflow confirmada y cada intento de actividad: + +```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]); + } + } +} +``` + +El contenedor construye los interceptores configurados para cada tarea. Registra +uno como singleton cuando deba conservar estado entre tareas. + +| Hook | Contexto | Devuelve `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (también `replayState()`) | `WorkflowTaskOutcome` con `historyEventTypes`, `runStatus`, `nextTaskId` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | el resultado de la actividad | +| `executeQueryTask($context, $next)` | `workerId` (siempre null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (siempre `Replaying`) | el resultado de la consulta | +| `executeUpdateValidation($context, $next)` | `workerId` (siempre null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (siempre `Replaying`) | `UpdateValidationOutcome` con `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` | + +`task` es una instantánea en forma de array de la fila de la tarea reclamada, +nunca el propio modelo. `workerId` identifica el proceso del worker de colas por +host e ID de proceso. Las consultas y las validaciones de actualizaciones se +ejecutan en el proceso que las invoca, por lo que su `workerId` es null. + +Los interceptores de tareas de workflow no pueden cambiar lo que registra un +workflow: + +- `executeWorkflowTask` envuelve la tarea de workflow dentro de su transacción + de base de datos, una vez por intento de tarea. `replaying` es `true` cuando + tareas de workflow anteriores ya registraron comandos para la ejecución. No es + una clave de deduplicación: `historyEventTypes` enumera solo los eventos que + añadió esta tarea. +- `replayState()` da la misma respuesta como un + `Workflow\V2\Enums\WorkflowReplayState`, el enum que usa + `Workflow::replayState()`; el valor del interceptor queda fijo para la tarea. +- Los efectos secundarios de los hooks se ejecutan antes de que la tarea se + confirme y pueden repetirse cuando se reintenta un intento, así que difiérelos + con `DB::afterCommit()` o identifícalos con `taskId` y `workflowTaskAttempt`. +- El motor confirma el historial que produjo el código del workflow. El + resultado es una vista de solo lectura; devolver un resultado distinto, o + pasar un contexto distinto a `$next`, no cambia nada. +- Un fallo del código del workflow llega al motor sin cambios, aunque un + interceptor lo capture y devuelva normalmente. +- Si un interceptor lanza una excepción fuera de la cadena, omite `$next` o lo + llama más de una vez, la transacción de la tarea se revierte, por lo que no se + registra nada. La tarea se libera con `WorkflowTaskInterceptorFailed` como + último error y se reintenta tras el backoff de reparación habitual. Un + interceptor externo aún puede capturar una excepción que un interceptor + interno lanzó después de `$next` y dejar que la tarea se confirme; un `$next` + omitido o repetido siempre hace fallar la tarea. +- Los hooks se ejecutan mientras las filas de la ejecución y de la tarea están + bloqueadas, así que mantenlos breves. No deben confirmar ni revertir la + transacción que los rodea, ni enviar comandos, como señales, a la ejecución + que envuelven; un cambio en el estado registrado de la ejecución hace fallar + la tarea en cada intento. +- Las actividades locales se ejecutan dentro de la tarea de workflow, por lo que + un hook que sigue fallando después de `$next` hace que cada reintento vuelva a + ejecutar esas actividades locales. + +Los interceptores de validación de actualizaciones envuelven la reproducción y +la llamada al validador que se ejecutan antes de aceptar una actualización con +un `#[UpdateValidator]`. Las actualizaciones sin validador no ejecutan el hook. +Los hooks observan la decisión; no pueden cambiarla: + +- El motor actúa según el resultado del propio validador. Devolver otro + `UpdateValidationOutcome`, o pasar otros argumentos a `$next`, no cambia nada; + el validador siempre recibe los argumentos de la actualización. +- Si un hook lanza una excepción, omite `$next` o lo llama más de una vez, la + actualización se rechaza con `UpdateValidationFailedException` y no se + registra nada, así que un hook nunca puede dejar pasar una actualización sin + validar. +- El hook se ejecuta dentro de la transacción de admisión de la actualización, + mientras las filas de la ejecución están bloqueadas, así que mantenlo breve. + Aplaza los efectos secundarios con `DB::afterCommit()`; las escrituras que + haga un hook se confirman o se revierten junto con la admisión. El código del + hook se ejecuta fuera de la fiber del workflow, así que no puede programar + trabajo duradero para la ejecución. + +Los interceptores de actividades y consultas pueden cambiar los argumentos con +`$context->withArguments(...)` y pueden cambiar el valor devuelto, porque el +resultado de una actividad se registra una sola vez y una consulta no registra +nada. Los argumentos de consulta reescritos se vuelven a validar contra el +contrato de la consulta. Las excepciones de actividad atraviesan todos los +interceptores salvo que alguno las maneje, y después pasan por la política de +reintentos normal de la actividad. Los interceptores de actividades envuelven +actividades encoladas y locales; `local` permite distinguirlas. Las actividades +simuladas en `WorkflowStub::fake()` no ejecutan interceptores. + +Cuando las [trazas integradas](../monitoring.md#embedded-tracing) están +habilitadas, los spans integrados de workflow y de actividad siguen siendo los +más externos, de modo que los interceptores se ejecutan dentro del span activo y +pueden añadir atributos o spans hijos. + +Los interceptores envuelven los jobs de cola, las actividades locales y las +consultas que ejecuta este paquete. Las tareas entregadas a workers de SDK +externos mediante los puentes de tareas de worker se ejecutan con los +interceptores propios de ese SDK. La ruta `execute` del puente de workers, que +ejecuta en el mismo proceso una tarea de workflow reclamada para quien llama al +puente, no ejecuta interceptores de tareas de workflow. Una entrada de +`workflows.v2.interceptors` que no se puede resolver hace fallar cada ruta a su +manera: una tarea de workflow encolada se libera y se reintenta, un intento de +actividad falla según su política de reintentos y una consulta lanza una +excepción a quien la invoca. Revisa la lista al desplegar. La +[guía de interceptores integrados](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md) +contiene el contrato completo. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md index d42eacfd353..68104c5908d 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -358,6 +358,162 @@ mismo caso representativo en v1, v2 integrado y este puente de modo servicio, incluidos drenaje y reversión. Utiliza [Modos de despliegue](/docs/polyglot/deployment-modes/) para una comparación más amplia de límites del runtime. +## Interceptores de worker {#worker-interceptors} + +Los interceptores de worker están disponibles a partir del SDK de PHP 3.32.0. Pasa `interceptors` ordenados a `Worker::create()` (o al constructor +de `Worker`) para añadir una sola vez registros de auditoría, etiquetas de +métricas, contexto de tenant o trazas alrededor de cada tarea, en lugar de +hacerlo en cada manejador. Cada interceptor implementa +`DurableWorkflow\Worker\Interceptor\WorkerInterceptor`; extiende +`PassthroughWorkerInterceptor` para implementar solo los hooks que necesites. La +forma de los hooks coincide con la de los interceptores de los SDK de +[Python](./python.md#worker-interceptors) y +[Rust](./rust.md#worker-interceptors). + +Este interceptor de auditoría registra el resultado de cada tarea de workflow y +cada intento de actividad: + +```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 | Contexto | Devuelve `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (también `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` con una copia de los comandos | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | el resultado de la actividad | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | el resultado de la consulta | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` con `approved`, `reason`, `message`, `failureType`, `validationErrors` | + +Los interceptores se ejecutan en el orden en que los enumeras. El primer +interceptor es el envoltorio más externo: se ejecuta el primero antes de la +tarea y el último después de ella. Cada hook llama a `$next($context)` para +continuar la cadena. Cuando las trazas están configuradas, los spans integrados +del worker siguen siendo los más externos, de modo que los interceptores se +ejecutan dentro del span activo de la tarea. + +Los interceptores de tareas de workflow no pueden romper el determinismo: + +- `executeWorkflowTask` envuelve el código del workflow que produce los comandos + de una tarea de workflow, una vez por intento de tarea. `replaying` es `true` + cuando tareas de workflow anteriores ya registraron comandos, por lo que el + código del workflow volvió a ejecutar primero ese prefijo confirmado. El + resultado contiene solo los comandos que añade esta tarea; los comandos + reproducidos nunca se vuelven a enviar. +- `replayState()` informa lo mismo como el `WorkflowReplayState` que usa + `WorkflowContext::replayState()`: `Replaying` o `Executing`. +- Un intento reintentado (`workflowTaskAttempt > 1`) puede repetir un resultado + cuya tarea falló, así que haz que las escrituras de auditoría externas sean + idempotentes. +- Las tareas de actualización (con `updateId` definido) ejecutan el manejador de + la actualización sobre el estado confirmado sin volver a ejecutar el cuerpo del + workflow; en ellas, `replaying` solo indica que existen comandos anteriores. +- El worker envía exactamente los comandos que produjo el código del workflow. El + resultado es una copia; devolver un resultado distinto, o pasar un contexto + distinto a `$next`, no cambia nada. +- Un fallo del código del workflow llega al worker sin cambios, aunque un + interceptor lo capture y devuelva normalmente. +- Una excepción lanzada por un interceptor hace fallar la tarea de workflow. No + se registra nada y el Server reintenta la tarea. Omitir `$next`, o llamarlo más + de una vez, hace fallar la tarea con `WorkflowTaskInterceptorViolation`. + +Los interceptores de validación de actualizaciones (`executeUpdateValidation()`) +envuelven la ejecución del validador de una actualización antes de que el Server +la acepte. Ven la decisión como un `UpdateValidationOutcome` de solo lectura y +no pueden cambiar la decisión, los argumentos de la actualización ni el +historial que lee el validador: el validador siempre se ejecuta en modo de solo +lectura en su propia Fiber con la copia de la tarea que tiene el worker, y el +worker responde con la decisión del propio validador. Una excepción del +interceptor, u omitir `$next` o llamarlo más de una vez +(`UpdateValidationInterceptorViolation`), responde a la tarea con +`update_validation_worker_failed`, de modo que la actualización no se acepta y +quien llama puede reintentarla. + +Los interceptores de actividades y consultas pueden cambiar los argumentos con +`$context->withArguments(...)` y pueden cambiar el valor devuelto, porque los +resultados de actividad se registran una sola vez y las consultas no registran +nada. Las excepciones de actividad atraviesan todos los interceptores salvo que +alguno las maneje. Los interceptores de actividades envuelven actividades +remotas y locales; `local` permite distinguirlas. Con la cancelación +cooperativa, los callbacks de actividades remotas, locales cooperativas y +locales preparadas, junto con sus interceptores, se ejecutan en el proceso hijo +de la actividad, por lo que los cambios en memoria realizados allí no llegan al +proceso del worker. + +### Configuración del contenedor y del framework {#worker-interceptor-configuration} + +Pasa instancias o nombres de clase de interceptores. Los nombres de clase se +resuelven desde el contenedor PSR-11 pasado al worker, del mismo modo que los +manejadores con atributos. Sin contenedor, un nombre de clase no debe tener +argumentos de constructor obligatorios. + +En el modo servicio de Laravel y Symfony, enumera las clases de interceptores en +`worker.interceptors`. Se resuelven desde el contenedor del framework en ese +orden: + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +Los workflows integrados de Laravel configuran sus propios interceptores en +`workflows.v2.interceptors`; consulta +[interceptores de worker integrados](../configuration/publishing-config.md#worker-interceptors). +La [referencia del SDK de PHP](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors) +contiene el contrato completo de los interceptores. + ## Resultados de consulta con valores binarios {#query-binary-results} PHP SDK 3.18.2 corrige la finalización de consultas para resultados Avro válidos con bytes `AvroBinaryValue` anidados. `result_envelope` sigue siendo la representación autoritativa. El SDK omite únicamente la proyección simple opcional `result` cuando no se puede codificar en JSON; los resultados habituales compatibles con JSON conservan esa proyección. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md index 57413a420f6..7591522824d 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -229,6 +229,153 @@ cargo run --features metrics-prometheus --example metrics_prometheus Para métricas OpenTelemetry, implemente el recorder con su meter existente: contadores de unidad `1` e histogramas de segundos `s`, con nombres/tags exactos. Provider, agregación, etiquetas de recursos y ciclo del exporter pertenecen a la aplicación. Es independiente del tracing de ejecución. Véanse la [API recorder](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), [API Prometheus](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) y [contrato publicado](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Interceptores de worker {#worker-interceptors} + +Los interceptores de worker están disponibles a partir del SDK de Rust 4.25.0. Añaden comportamiento transversal, como registros de auditoría, +etiquetas de métricas o contexto de tenant, una sola vez para cada tarea que +ejecuta un worker. Implementa `WorkerInterceptor` y regístralo con +`Worker::interceptor`, o varios con `Worker::interceptors`. Por defecto, cada +hook pasa la llamada al siguiente, así que implementa solo los hooks que +necesites; `PassthroughWorkerInterceptor` es un interceptor que no hace nada. La +forma de los hooks coincide con la de los interceptores de los SDK de +[Python](./python.md#worker-interceptors) y +[PHP](./php.md#worker-interceptors). + +Este interceptor de auditoría registra el resultado de cada tarea de workflow y +cada intento de actividad: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +El +[ejemplo `audit_interceptor`](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +del repositorio ejecuta el mismo interceptor contra un Server autohospedado. + +| Hook | Se ejecuta alrededor de | Contexto | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | una tarea de workflow, incluida la reproducción | `WorkflowTaskInterceptorContext` | `next.run()` devuelve un `WorkflowTaskOutcome` de solo lectura | +| `execute_activity` | un intento de actividad o de actividad local | `ActivityInterceptorContext` | `next.run(context)` devuelve el resultado de la actividad | +| `execute_query_task` | una tarea de consulta | `QueryTaskInterceptorContext` | `next.run()` devuelve el resultado de la consulta o `QueryTaskFailure` | +| `execute_update_validation_task` | una tarea de validación de actualización | `UpdateValidationInterceptorContext` | `next.run()` devuelve un `UpdateValidationOutcome` de solo lectura | + +Los contextos son de solo lectura. Contienen el id del worker, la cola de +tareas, el espacio de nombres y la identidad de la tarea: id de tarea, id de +workflow, id de ejecución, tipo de workflow o de actividad, intento y, para las +tareas de workflow, la longitud del historial, el portador de trazas de la tarea +y el estado de reproducción. Un contexto de actividad también expone los +argumentos decodificados, si el intento es una actividad local y el +`ActivityContext` que recibe el manejador. +Un contexto de validación de actualización contiene el id y el intento de la +tarea de validación, el id, el id de ejecución y el tipo del workflow, el nombre +de la actualización y el portador de trazas. + +Los interceptores se ejecutan en orden de registro. El primero registrado es el +más externo: se ejecuta el primero antes de la tarea y el último después de +ella. Cada hook debe llamar a `next` para continuar la cadena; el `next` más +interno ejecuta el procesamiento propio del SDK. Los errores de la tarea +vuelven a salir a través de todos los interceptores sin cambios, salvo que un +interceptor de actividad o de consulta los maneje deliberadamente. Los +interceptores de actividades pueden cambiar los argumentos con +`context.with_args(..)` y transformar los resultados, y los interceptores de +actividades y consultas pueden responder sin llamar a `next`. Los spans +integrados de `ExecutionTelemetry` siguen siendo los más externos alrededor de +toda la cadena. + +Los interceptores de tareas de workflow no pueden cambiar lo que registra un +workflow: + +- `next.run()` no recibe ninguna entrada, por lo que la tarea siempre se ejecuta + tal como se recibió. +- El worker envía exactamente los comandos que produjo el workflow. El resultado + es una vista de solo lectura de ellos. +- Si la tarea falla, el worker informa de ese fallo aunque un interceptor + devuelva `Ok`. Los interceptores lo ven como `Error::WorkflowTaskFailed`, una + descripción de solo lectura con `.kind()`, `.message()` y `.debug()`; el + worker conserva el error original. +- Un error de un interceptor después de que la tarea haya tenido éxito, o + devolver sin ejecutar `next`, hace fallar la tarea de workflow con + `Error::WorkflowTaskInterceptor`. No se registra nada y el Server reintenta la + tarea. El workflow no falla. +- Los interceptores se ejecutan en cada tarea de workflow. + `context.replay_state()` es `Replaying` cuando la tarea volvió a ejecutar + comandos confirmados por tareas anteriores antes de la nueva ejecución, y + `Executing` para una tarea sin historial confirmado. El worker nunca vuelve a + enviar comandos reproducidos, por lo que los comandos de un resultado siempre + son nuevos para esa tarea: audita cada resultado satisfactorio, sea cual sea + el estado de reproducción. +- Si una tarea falla después de que un interceptor la haya observado, su + reintento puede repetir el mismo resultado; un `context.attempt()` mayor que 1 + identifica un reintento, así que haz que las escrituras de auditoría externas + sean idempotentes. + +Los interceptores de validación de actualizaciones no pueden cambiar si se +acepta una actualización: + +- `next.run()` no recibe ninguna entrada, así que el validador siempre se + ejecuta sobre la tarea tal como se recibió, y el worker envía la aprobación o + el rechazo del propio validador. El resultado es una vista de solo lectura: + `is_approved()`, `is_rejected()`, `is_worker_failure()`, `reason()` y + `rejection()`. +- Un error del interceptor, volver o fallar sin ejecutar `next`, o abandonar la + validación a medias hace que el worker informe + `update_validation_worker_failed` en su lugar. La actualización no se acepta, + y el reintento de quien llama con el mismo id de solicitud vuelve a consultar + al validador. + +El `WorkflowEnvironment` sin conexión ejecuta los interceptores de actividades +registrados en el worker que envuelve. No tiene tareas de workflow ni de +consulta, por lo que esos hooks no se ejecutan allí. Consulta el +[README del SDK de Rust](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors) +para ver el contrato completo de los interceptores. + ## Concurrencia de tareas del worker {#worker-task-concurrency} Los carriles acotados descritos aquí requieren Rust SDK **4.3.1 o posterior**. Compruebe la versión de `Cargo.lock`: la instalación fijada arriba pertenece a otra tupla cualificada y puede seleccionar un SDK anterior. La [verificación del paquete publicado](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) confirma tres slots configurados, una cuarta llamada admitida al liberarse uno, y siete workflows completados, incluido un fallo de actividad manejado. Siguen vigentes los requisitos de protocolo del Server descritos arriba. diff --git a/i18n/es/source-hashes.json b/i18n/es/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/es/source-hashes.json +++ b/i18n/es/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/fr/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index c2888593393..98f4e843051 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -240,3 +240,168 @@ Puis enregistrez-le dans `config/workflows.php` : L’outil reçoit la valeur courante et un contexte tel que `path`, `category`, `workflow_instance_id`, `workflow_run_id` et `workflow_type`. L’export l’appelle pour les arguments et résultats du workflow, les données d’événements d’historique, les données et contextes de commandes, les données de mises à jour, de tâches et d’activités, ainsi que les diagnostics de message, fichier et trace des échecs. Le paquet obtenu inclut `redaction.applied`, `redaction.policy` et `redaction.paths` pour que les outils en aval identifient la politique appliquée. Chaque export inclut aussi un bloc `integrity` calculé après masquage. La somme de contrôle utilise `canonicalization = json-recursive-ksort-v1` et `checksum_algorithm = sha256`. Si `signing_key` est configuré, les mêmes données canoniques sont signées avec `signature_algorithm = hmac-sha256` et le `signing_key_id` facultatif est indiqué comme `key_id`. Conservez la clé de signature hors de l’artefact exporté et renouvelez son identifiant lorsque les vérificateurs en aval doivent distinguer les clés. + +## Intercepteurs worker {#worker-interceptors} + +Les intercepteurs worker sont disponibles à partir de Workflow 2.42.0. +Durable Workflow embarqué exécute des intercepteurs worker ordonnés autour des tâches de workflow, +des activités, des requêtes et des validations de mises à jour qu'il exécute dans les processus de votre application. Utilisez-les +pour la journalisation d'audit, les tags de métriques, le contexte de tenant ou le traçage que vous voulez +écrire une seule fois plutôt que dans chaque workflow et chaque activité. La forme des hooks correspond à celle +des intercepteurs des SDK +[Python](../polyglot/python.md#worker-interceptors), +[PHP](../polyglot/php.md#worker-interceptors) et +[Rust](../polyglot/rust.md#worker-interceptors). + +Listez les classes d'intercepteurs sous `workflows.v2.interceptors` dans +`config/workflows.php`. Elles sont résolues à partir du conteneur Laravel, de sorte que +l'injection par constructeur fonctionne, et elles s'exécutent dans l'ordre de la liste ; la première est +l'enveloppe la plus extérieure. + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +Chaque intercepteur implémente `Workflow\V2\Interceptors\WorkerInterceptor`. +Étendez `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` pour n'implémenter que +les hooks dont vous avez besoin, et appelez `$next($context)` pour poursuivre la chaîne. Cet intercepteur +d'audit journalise chaque tâche de workflow validée et chaque tentative d'activité : + +```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]); + } + } +} +``` + +Le conteneur construit les intercepteurs configurés pour chaque tâche. Liez-en un en tant que +singleton lorsqu'il doit conserver un état entre les tâches. + +| Hook | Contexte | Retour de `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (aussi `replayState()`) | `WorkflowTaskOutcome` avec `historyEventTypes`, `runStatus`, `nextTaskId` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | le résultat de l'activité | +| `executeQueryTask($context, $next)` | `workerId` (toujours null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (toujours `Replaying`) | le résultat de la requête | +| `executeUpdateValidation($context, $next)` | `workerId` (toujours null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (toujours `Replaying`) | `UpdateValidationOutcome` avec `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` | + +`task` est un instantané sous forme de tableau de la ligne de tâche réclamée, jamais le modèle lui-même. +`workerId` identifie le processus worker de file par hôte et identifiant de processus. Les requêtes +et les validations de mises à jour s'exécutent dans le processus appelant ; leur `workerId` est donc null. + +Les intercepteurs de tâche de workflow ne peuvent pas modifier ce qu'un workflow enregistre : + +- `executeWorkflowTask` enveloppe la tâche de workflow à l'intérieur de sa transaction de base de + données, une fois par tentative de tâche. `replaying` vaut `true` lorsque des tâches de workflow + antérieures ont déjà enregistré des commandes pour l'exécution. Ce n'est pas une clé de + déduplication : `historyEventTypes` ne liste que les événements ajoutés par cette tâche. +- `replayState()` donne la même réponse sous la forme d'un + `Workflow\V2\Enums\WorkflowReplayState`, l'enum qu'utilise + `Workflow::replayState()` ; la valeur vue par l'intercepteur est fixe pour la + tâche. +- Les effets de bord des hooks s'exécutent avant la validation de la tâche et peuvent se répéter lorsqu'une tentative + est relancée ; différez-les donc avec `DB::afterCommit()` ou indexez-les sur `taskId` et + `workflowTaskAttempt`. +- Le moteur valide l'historique produit par le code de workflow. Le résultat est une + vue en lecture seule ; renvoyer un résultat différent, ou passer un contexte différent + à `$next`, ne change rien. +- Un échec du code de workflow parvient au moteur inchangé, même si un + intercepteur l'intercepte et retourne normalement. +- Si un intercepteur lève une exception hors de la chaîne, omet `$next` ou l'appelle plus + d'une fois, la transaction de la tâche est annulée et rien n'est donc enregistré. La tâche est + libérée avec `WorkflowTaskInterceptorFailed` comme dernière erreur et relancée + après le délai de réparation habituel. Un intercepteur extérieur peut encore intercepter une + exception levée par un intercepteur intérieur après `$next` et laisser la tâche être validée ; un + `$next` omis ou répété fait toujours échouer la tâche. +- Les hooks s'exécutent pendant que les lignes de l'exécution et de la tâche sont verrouillées ; gardez-les donc courts. Ils + ne doivent ni valider ni annuler la transaction englobante, et ne doivent pas envoyer de + commandes, comme des signaux, à l'exécution qu'ils enveloppent ; une modification de l'état + enregistré de l'exécution fait échouer la tâche à chaque tentative. +- Les activités locales s'exécutent à l'intérieur de la tâche de workflow ; un hook qui continue d'échouer + après `$next` fait donc réexécuter ces activités locales à chaque nouvelle tentative. + +Les intercepteurs de validation de mise à jour enveloppent la relecture et +l'appel du validateur qui s'exécutent avant l'acceptation d'une mise à jour +dotée d'un `#[UpdateValidator]`. Les mises à jour sans validateur n'exécutent +pas le hook. Les hooks observent la décision ; ils ne peuvent pas la modifier : + +- Le moteur agit selon le résultat propre du validateur. Renvoyer un autre + `UpdateValidationOutcome`, ou passer d'autres arguments à `$next`, ne change + rien ; le validateur reçoit toujours les arguments de la mise à jour. +- Si un hook lève une exception, omet `$next` ou l'appelle plus d'une fois, la + mise à jour est refusée avec `UpdateValidationFailedException` et rien n'est + enregistré : un hook ne peut donc jamais laisser passer une mise à jour non + validée. +- Le hook s'exécute dans la transaction d'admission de la mise à jour, pendant + que les lignes de l'exécution sont verrouillées ; gardez-le donc court. + Différez les effets de bord avec `DB::afterCommit()` ; les écritures d'un hook + sont validées ou annulées avec l'admission. Le code du hook s'exécute hors de + la fiber du workflow et ne peut donc pas planifier de travail durable pour + l'exécution. + +Les intercepteurs d'activité et de requête peuvent modifier les arguments avec +`$context->withArguments(...)` et modifier la valeur renvoyée, car un +résultat d'activité est enregistré une seule fois et une requête n'enregistre rien. Les arguments de requête +réécrits sont à nouveau validés par rapport au contrat de la requête. Les exceptions d'activité +traversent tous les intercepteurs, sauf si l'un d'eux les gère, puis passent par la +politique de nouvelle tentative normale de l'activité. Les intercepteurs d'activité enveloppent les activités en file +et locales ; `local` permet de les distinguer. Les activités simulées dans +`WorkflowStub::fake()` n'exécutent pas les intercepteurs. + +Lorsque le [traçage embarqué](../monitoring.md#embedded-tracing) est activé, les +spans intégrés de workflow et d'activité restent les plus extérieurs ; les intercepteurs s'exécutent donc à l'intérieur +du span actif et peuvent ajouter des attributs ou des spans enfants. + +Les intercepteurs enveloppent les jobs de file, les activités locales et les requêtes que ce paquet +exécute. Les tâches confiées à des workers de SDK externes via les ponts de tâches worker s'exécutent +sous les propres intercepteurs de ce SDK. La route `execute` du pont worker, qui +exécute dans le processus une tâche de workflow réclamée pour un appelant du pont, n'exécute pas +les intercepteurs de tâche de workflow. Une entrée de `workflows.v2.interceptors` qui +ne peut pas être résolue fait échouer chaque chemin à sa manière : une tâche de workflow en file est +libérée et relancée, une tentative d'activité échoue selon sa politique de nouvelle tentative, et une +requête lève une exception vers son appelant. Vérifiez la liste lors du déploiement. Le +[guide des intercepteurs embarqués](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md) +contient le contrat complet. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md index 1fc6d526352..677e7910fad 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -363,6 +363,155 @@ mode service livré, y compris le drainage et le retour arrière. Les [modes de déploiement](/docs/polyglot/deployment-modes/) comparent plus largement les frontières du runtime. +## Intercepteurs worker {#worker-interceptors} + +Les intercepteurs worker sont disponibles à partir du SDK PHP 3.32.0. Passez des +`interceptors` ordonnés à `Worker::create()` (ou au constructeur `Worker`) pour ajouter une journalisation +d'audit, des tags de métriques, un contexte de tenant ou du traçage autour de chaque tâche, une seule fois, +plutôt que dans chaque handler. Chaque intercepteur implémente +`DurableWorkflow\Worker\Interceptor\WorkerInterceptor` ; étendez +`PassthroughWorkerInterceptor` pour n'implémenter que les hooks dont vous avez besoin. La forme des hooks +correspond à celle des intercepteurs des SDK [Python](./python.md#worker-interceptors) et +[Rust](./rust.md#worker-interceptors). + +Cet intercepteur d'audit journalise chaque résultat de tâche de workflow et chaque tentative d'activité : + +```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 | Contexte | Retour de `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (aussi `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` avec une copie des commandes | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | le résultat de l'activité | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | le résultat de la requête | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` avec `approved`, `reason`, `message`, `failureType`, `validationErrors` | + +Les intercepteurs s'exécutent dans l'ordre où vous les listez. Le premier intercepteur est +l'enveloppe la plus extérieure : il s'exécute en premier avant la tâche et en dernier après elle. Chaque hook +appelle `$next($context)` pour poursuivre la chaîne. Lorsque le traçage est configuré, les +spans worker intégrés restent les plus extérieurs, de sorte que les intercepteurs s'exécutent à l'intérieur du span +de tâche actif. + +Les intercepteurs de tâche de workflow ne peuvent pas rompre le déterminisme : + +- `executeWorkflowTask` enveloppe le code de workflow qui produit les commandes d'une tâche + de workflow, une fois par tentative de tâche. `replaying` vaut `true` lorsque des tâches de workflow + antérieures ont déjà enregistré des commandes ; le code de workflow a alors d'abord rejoué ce + préfixe validé. Le résultat ne contient que les commandes ajoutées par cette tâche ; + les commandes rejouées ne sont jamais soumises à nouveau. +- `replayState()` indique la même chose sous la forme du `WorkflowReplayState` + qu'utilise `WorkflowContext::replayState()` : `Replaying` ou `Executing`. +- Une tentative relancée (`workflowTaskAttempt > 1`) peut répéter un résultat dont la tâche + a échoué ; rendez donc idempotentes les écritures d'audit externes. +- Les tâches de mise à jour (`updateId` défini) exécutent le handler de mise à jour sur l'état validé + sans réexécuter le corps du workflow ; pour elles, `replaying` indique seulement que + des commandes antérieures existent. +- Le worker soumet exactement les commandes produites par le code de workflow. Le + résultat est une copie ; renvoyer un résultat différent, ou passer un contexte différent + à `$next`, ne change rien. +- Un échec du code de workflow parvient au worker inchangé, même si un + intercepteur l'intercepte et retourne normalement. +- Une exception levée par un intercepteur fait échouer la tâche de workflow. Rien n'est + enregistré et le Server relance la tâche. Omettre `$next`, ou l'appeler plus + d'une fois, fait échouer la tâche avec `WorkflowTaskInterceptorViolation`. + +Les intercepteurs de validation de mise à jour (`executeUpdateValidation()`) +enveloppent l'exécution du validateur d'une mise à jour avant que le Server +n'accepte la mise à jour. Ils voient la décision sous la forme d'un +`UpdateValidationOutcome` en lecture seule et ne peuvent modifier ni la +décision, ni les arguments de la mise à jour, ni l'historique que lit le +validateur : le validateur s'exécute toujours en lecture seule dans sa propre +Fiber avec la copie de la tâche détenue par le worker, et le worker répond avec +la décision propre du validateur. Une exception levée par l'intercepteur, ou le +fait d'omettre `$next` ou de l'appeler plus d'une fois +(`UpdateValidationInterceptorViolation`), répond à la tâche avec +`update_validation_worker_failed` : la mise à jour n'est donc pas acceptée et +l'appelant peut réessayer. + +Les intercepteurs d'activité et de requête peuvent modifier les arguments avec +`$context->withArguments(...)` et modifier la valeur renvoyée, car +les résultats d'activité sont enregistrés une seule fois et les requêtes n'enregistrent rien. Les +exceptions d'activité traversent tous les intercepteurs, sauf si l'un d'eux les gère. Les intercepteurs +d'activité enveloppent les activités distantes et locales ; `local` permet de les distinguer. Avec +l'annulation coopérative, les callbacks des activités distantes, locales coopératives et locales préparées, +ainsi que leurs intercepteurs, s'exécutent dans le processus enfant de l'activité ; les modifications +de mémoire qui y sont faites n'atteignent donc pas le processus worker. + +### Configuration du conteneur et du framework {#worker-interceptor-configuration} + +Passez des instances d'intercepteurs ou des noms de classes. Les noms de classes sont résolus à partir du +conteneur PSR-11 passé au worker, de la même manière que les handlers déclarés par attributs. +Sans conteneur, une classe ne doit avoir aucun argument de constructeur obligatoire. + +En mode service Laravel et Symfony, listez les classes d'intercepteurs sous +`worker.interceptors`. Elles sont résolues à partir du conteneur du framework dans cet +ordre : + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +Les workflows Laravel embarqués configurent leurs propres intercepteurs sous +`workflows.v2.interceptors` ; consultez +[intercepteurs worker embarqués](../configuration/publishing-config.md#worker-interceptors). +La [référence du SDK PHP](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors) +contient le contrat complet des intercepteurs. + ## Résultats de requête avec des valeurs binaires {#query-binary-results} Le PHP SDK 3.18.2 corrige la finalisation des requêtes pour des résultats Avro valides contenant des octets `AvroBinaryValue` imbriqués. `result_envelope` reste la représentation de référence. Le SDK omet uniquement la projection simple facultative `result` lorsqu’elle ne peut pas être encodée en JSON ; les résultats ordinaires compatibles JSON conservent cette projection. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md index 261932acf89..9d6dbaa2e35 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -287,6 +287,139 @@ cargo run --features metrics-prometheus --example metrics_prometheus Pour les métriques OpenTelemetry, implémentez le recorder avec votre meter existant : compteurs d’unité `1`, histogrammes en secondes `s`, noms/tags exacts ci-dessus. Provider, agrégation, labels de ressources et cycle de l’exporter restent applicatifs. Cela est distinct du tracing d’exécution. Voir l’[API recorder](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), l’[API Prometheus](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) et le [contrat publié](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Intercepteurs worker {#worker-interceptors} + +Les intercepteurs worker sont disponibles à partir du SDK Rust 4.25.0. Ils ajoutent +un comportement transversal, comme la journalisation d'audit, des tags de métriques ou un contexte de tenant, +une seule fois pour chaque tâche exécutée par un worker. Implémentez `WorkerInterceptor` et enregistrez-le +avec `Worker::interceptor`, ou plusieurs avec `Worker::interceptors`. Chaque hook +transmet l'appel par défaut ; n'implémentez donc que les hooks dont vous avez besoin. +`PassthroughWorkerInterceptor` est un intercepteur sans effet. La forme des hooks correspond à celle +des intercepteurs des SDK [Python](./python.md#worker-interceptors) et +[PHP](./php.md#worker-interceptors). + +Cet intercepteur d'audit journalise chaque résultat de tâche de workflow et chaque tentative d'activité : + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +L'[exemple `audit_interceptor`](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +du dépôt exécute le même intercepteur contre un Server auto-hébergé. + +| Hook | S'exécute autour de | Contexte | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | une tâche de workflow, relecture comprise | `WorkflowTaskInterceptorContext` | `next.run()` renvoie un `WorkflowTaskOutcome` en lecture seule | +| `execute_activity` | une tentative d'activité ou d'activité locale | `ActivityInterceptorContext` | `next.run(context)` renvoie le résultat de l'activité | +| `execute_query_task` | une tâche de requête | `QueryTaskInterceptorContext` | `next.run()` renvoie le résultat de la requête ou `QueryTaskFailure` | +| `execute_update_validation_task` | une tâche de validation de mise à jour | `UpdateValidationInterceptorContext` | `next.run()` renvoie un `UpdateValidationOutcome` en lecture seule | + +Les contextes sont en lecture seule. Ils portent l'identifiant du worker, la file de tâches, le namespace et +l'identité de la tâche : identifiant de tâche, identifiant de workflow, identifiant d'exécution, type de workflow ou d'activité, +tentative et, pour les tâches de workflow, la longueur de l'historique, le porteur de trace de la tâche et +l'état de relecture. Un contexte d'activité expose aussi les arguments décodés, indique si +la tentative est une activité locale, et fournit l'`ActivityContext` que reçoit le handler. +Un contexte de validation de mise à jour porte l'identifiant et la tentative de +la tâche de validation, l'identifiant, l'identifiant d'exécution et le type du +workflow, le nom de la mise à jour et le porteur de trace. + +Les intercepteurs s'exécutent dans l'ordre d'enregistrement. Le premier enregistré est le plus +extérieur : il s'exécute en premier avant la tâche et en dernier après elle. Chaque hook doit appeler +`next` pour poursuivre la chaîne ; le `next` le plus intérieur exécute le traitement propre du SDK. +Les erreurs de la tâche remontent inchangées à travers chaque intercepteur, sauf si +un intercepteur d'activité ou de requête les gère délibérément. Les intercepteurs +d'activité peuvent modifier les arguments avec `context.with_args(..)` et transformer les +résultats, et les intercepteurs d'activité et de requête peuvent répondre sans appeler `next`. +Les spans intégrés `ExecutionTelemetry` restent les plus extérieurs autour de toute la chaîne. + +Les intercepteurs de tâche de workflow ne peuvent pas modifier ce qu'un workflow enregistre : + +- `next.run()` ne prend aucune entrée ; la tâche s'exécute donc toujours telle qu'elle a été reçue. +- Le worker soumet exactement les commandes produites par le workflow. Le résultat en est + une vue en lecture seule. +- Si la tâche échoue, le worker signale cet échec même lorsqu'un intercepteur + renvoie `Ok`. Les intercepteurs le voient sous la forme `Error::WorkflowTaskFailed`, une + description en lecture seule avec `.kind()`, `.message()` et `.debug()` ; le worker conserve + l'erreur d'origine. +- Une erreur d'intercepteur après la réussite de la tâche, ou un retour sans exécuter + `next`, fait échouer la tâche de workflow avec `Error::WorkflowTaskInterceptor`. Rien + n'est enregistré et le Server relance la tâche. Le workflow n'échoue pas. +- Les intercepteurs s'exécutent sur chaque tâche de workflow. `context.replay_state()` vaut + `Replaying` lorsque la tâche a rejoué des commandes validées par des tâches antérieures avant + toute nouvelle exécution, et `Executing` pour une tâche sans historique validé. Le + worker ne soumet jamais à nouveau les commandes rejouées ; les commandes d'un résultat sont donc toujours + nouvelles pour cette tâche : auditez chaque résultat réussi, quel que soit l'état de relecture. +- Si une tâche échoue après qu'un intercepteur l'a observée, sa relance peut répéter le + même résultat ; une valeur de `context.attempt()` supérieure à 1 identifie une relance, donc rendez + idempotentes les écritures d'audit externes. + +Les intercepteurs de validation de mise à jour ne peuvent pas modifier +l'acceptation d'une mise à jour : + +- `next.run()` ne prend aucune entrée : le validateur s'exécute donc toujours + sur la tâche telle qu'elle a été reçue, et le worker envoie l'approbation ou + le rejet propre au validateur. Le résultat est une vue en lecture seule : + `is_approved()`, `is_rejected()`, `is_worker_failure()`, `reason()` et + `rejection()`. +- Une erreur d'intercepteur, un retour ou un échec sans exécuter `next`, ou + l'abandon de la validation en cours de route amène le worker à signaler + `update_validation_worker_failed` à la place. La mise à jour n'est pas + acceptée, et une nouvelle tentative de l'appelant avec le même identifiant de + requête interroge de nouveau le validateur. + +Le `WorkflowEnvironment` hors ligne exécute les intercepteurs d'activité enregistrés sur le +worker qu'il enveloppe. Il n'a ni tâches de workflow ni tâches de requête ; ces hooks ne s'y exécutent donc +pas. Consultez le +[README du SDK Rust](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors) +pour le contrat complet des intercepteurs. + ## Concurrence des tâches du worker {#worker-task-concurrency} Les voies bornées ci-dessous nécessitent Rust SDK **4.3.1 ou ultérieur**. Vérifiez la version dans `Cargo.lock` : l’installation fixée plus haut appartient à une autre combinaison qualifiée et peut sélectionner un ancien SDK. La [vérification du paquet publié](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) confirme trois emplacements configurés, un quatrième callback admis après libération d’un emplacement et sept workflows terminés, dont un échec d’activité traité. Les exigences de protocole Server précédentes restent applicables. diff --git a/i18n/fr/source-hashes.json b/i18n/fr/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/fr/source-hashes.json +++ b/i18n/fr/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/ja/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index 3a63838424d..4b0f508cd58 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -237,3 +237,100 @@ final class WorkflowHistoryExportRedactor implements HistoryExportRedactor 秘匿化処理は現在の値と、`path`、`category`、`workflow_instance_id`、`workflow_run_id`、`workflow_type` などのコンテキストを受け取ります。ワークフローの引数・出力、履歴イベント、コマンドのペイロード・コンテキスト、更新、タスク、アクティビティ、失敗のメッセージ・ファイル・トレース診断に対して呼ばれます。結果のバンドルは `redaction.applied`、`redaction.policy`、`redaction.paths` を含み、後続ツールは適用したポリシーを識別できます。 各エクスポートは秘匿化後に計算した `integrity` も含みます。チェックサムは `canonicalization = json-recursive-ksort-v1` と `checksum_algorithm = sha256` を使います。`signing_key` が設定されていれば、同じ正規化ペイロードに `signature_algorithm = hmac-sha256` で署名し、任意の `signing_key_id` を `key_id` として報告します。署名キーはエクスポート成果物の外に保管し、後続の検証器がキーを区別する必要がある場合はキー ID を更新してください。 + +## Worker インターセプター {#worker-interceptors} + +Worker インターセプターは Workflow 2.42.0 以降で利用できます。組み込み Durable Workflow は、アプリケーションのプロセス内で実行するワークフロータスク、アクティビティ、クエリ、更新の検証の前後で、順序付きの Worker インターセプターを実行します。監査ログ、メトリクスタグ、テナントコンテキスト、トレースなど、各ワークフローやアクティビティではなく一度だけ書きたい処理に使用します。フックの形は [Python](../polyglot/python.md#worker-interceptors)、[PHP](../polyglot/php.md#worker-interceptors)、[Rust](../polyglot/rust.md#worker-interceptors) の SDK インターセプターと同じです。 + +インターセプタークラスを `config/workflows.php` の `workflows.v2.interceptors` に列挙します。これらは Laravel コンテナから解決されるためコンストラクターインジェクションが使え、列挙した順に実行されます。最初のものが最も外側のラッパーです。 + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +各インターセプターは `Workflow\V2\Interceptors\WorkerInterceptor` を実装します。必要なフックだけを実装するには `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` を継承し、チェーンを続けるために `$next($context)` を呼び出します。次の監査インターセプターは、コミットされた各ワークフロータスクとすべてのアクティビティ試行をログに記録します。 + +```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]); + } + } +} +``` + +コンテナは、設定されたインターセプターをタスクごとに構築します。タスク間で状態を保持する必要がある場合は、シングルトンとしてバインドしてください。 + +| フック | コンテキスト | `$next` の戻り値 | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying`(`replayState()` も) | `historyEventTypes`、`runStatus`、`nextTaskId` を持つ `WorkflowTaskOutcome` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | アクティビティの結果 | +| `executeQueryTask($context, $next)` | `workerId`(常に null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()`(常に `Replaying`) | クエリの結果 | +| `executeUpdateValidation($context, $next)` | `workerId`(常に null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()`(常に `Replaying`) | `approved`、`rejectionMessage`、`exceptionType`、`validationErrors` を持つ `UpdateValidationOutcome` | + +`task` は取得したタスク行の配列スナップショットであり、モデルそのものではありません。`workerId` はホストとプロセス ID でキュー Worker プロセスを識別します。クエリと更新の検証は呼び出し元のプロセスで実行されるため、その `workerId` は null です。 + +ワークフロータスクのインターセプターは、ワークフローが記録する内容を変更できません。 + +- `executeWorkflowTask` は、ワークフロータスクをそのデータベーストランザクションの内側で、タスク試行ごとに一度ラップします。それ以前のワークフロータスクがその実行に対してすでにコマンドを記録している場合、`replaying` は `true` になります。これは重複排除のキーではありません。`historyEventTypes` には、このタスクが追加したイベントだけが列挙されます。 +- `replayState()` は同じ答えを、`Workflow::replayState()` が使う列挙型 `Workflow\V2\Enums\WorkflowReplayState` として返します。インターセプターが見る値はそのタスクの間は固定です。 +- フックの副作用はタスクのコミット前に実行され、試行が再試行されると繰り返される可能性があります。そのため、`DB::afterCommit()` で遅延させるか、`taskId` と `workflowTaskAttempt` をキーにしてください。 +- エンジンは、ワークフローコードが生成した履歴をコミットします。結果は読み取り専用のビューです。別の結果を返したり、別のコンテキストを `$next` に渡したりしても、何も変わりません。 +- ワークフローコードからの失敗は、インターセプターがそれを捕捉して正常に戻った場合でも、そのままエンジンに届きます。 +- インターセプターがチェーンの外に例外をスローした場合、`$next` を呼ばなかった場合、または複数回呼び出した場合、タスクのトランザクションはロールバックされるため、何も記録されません。タスクは `WorkflowTaskInterceptorFailed` を最後のエラーとして解放され、通常の修復バックオフの後に再試行されます。内側のインターセプターが `$next` の後にスローした例外を外側のインターセプターが捕捉し、タスクをコミットさせることはできます。ただし、`$next` を呼ばなかった場合や繰り返し呼び出した場合は、常にタスクが失敗します。 +- フックは実行行とタスク行がロックされている間に実行されるため、短く保ってください。フックは周囲のトランザクションをコミットまたはロールバックしてはならず、ラップしている実行に対してシグナルなどのコマンドを送信してはなりません。実行の記録済み状態を変更すると、すべての試行でタスクが失敗します。 +- ローカルアクティビティはワークフロータスクの内側で実行されるため、`$next` の後に失敗し続けるフックがあると、再試行のたびにそれらのローカルアクティビティが再度実行されます。 + +更新検証のインターセプターは、`#[UpdateValidator]` を持つ更新が受理される前に実行されるリプレイとバリデーター呼び出しをラップします。バリデーターのない更新ではこのフックは実行されません。フックは判定を観察するだけで、変更はできません。 + +- エンジンはバリデーター自身の結果に従って動作します。別の `UpdateValidationOutcome` を返したり、別の引数を `$next` に渡したりしても、何も変わりません。バリデーターは常に更新の引数を受け取ります。 +- フックが例外をスローした場合、`$next` を呼ばなかった場合、または複数回呼び出した場合、更新は `UpdateValidationFailedException` で拒否され、何も記録されません。そのため、フックが検証されていない更新を通すことはありません。 +- フックは更新の受理トランザクションの内側で、実行の行がロックされている間に実行されるため、短く保ってください。副作用は `DB::afterCommit()` で遅延させてください。フックによる書き込みは、受理とともにコミットまたはロールバックされます。フックのコードはワークフローの Fiber の外側で実行されるため、その実行に対して永続的な処理をスケジュールすることはできません。 + +アクティビティとクエリのインターセプターは、`$context->withArguments(...)` で引数を変更でき、戻り値も変更できます。アクティビティの結果は一度だけ記録され、クエリは何も記録しないためです。書き換えられたクエリの引数は、クエリの契約に対して再度検証されます。アクティビティの例外は、いずれかのインターセプターが処理しない限り、すべてのインターセプターを通過し、その後アクティビティの通常のリトライポリシーに従います。アクティビティのインターセプターはキューに入れられたアクティビティとローカルアクティビティの両方をラップし、`local` で両者を区別できます。`WorkflowStub::fake()` でモックしたアクティビティでは、インターセプターは実行されません。 + +[組み込みトレース](../monitoring.md#embedded-tracing)が有効な場合、組み込みのワークフローとアクティビティのスパンが最も外側に留まるため、インターセプターはアクティブなスパンの内側で実行され、属性や子スパンを追加できます。 + +インターセプターは、このパッケージが実行するキュージョブ、ローカルアクティビティ、クエリをラップします。Worker タスクブリッジを通じて外部 SDK の Worker に渡されたタスクは、その SDK 自身のインターセプターの下で実行されます。ブリッジの呼び出し元のために取得済みのワークフロータスクをプロセス内で実行する Worker ブリッジの `execute` ルートでは、ワークフロータスクのインターセプターは実行されません。`workflows.v2.interceptors` 内のエントリーを解決できない場合、経路ごとに異なる形で失敗します。キューに入れられたワークフロータスクは解放されて再試行され、アクティビティ試行はそのリトライポリシーの下で失敗し、クエリは呼び出し元に例外をスローします。デプロイ時にリストを確認してください。完全な契約は[組み込みインターセプターガイド](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md)にあります。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md index 6f7a428a1a1..481bea4c4d2 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -255,6 +255,105 @@ Worker は `workflow_entry_arguments_validation` を自動的に通知します これらのブリッジは、`durable-workflow/workflow` によって Laravel アプリケーション自体が永続状態を所有し Laravel キューで実行する[組み込み Laravel ワークフロー](/docs/installation/)とは別です。ドレインとロールバックを含め、v1、v2 組み込み、同梱サービスモードブリッジで同じ代表的な Laravel ユースケースを比較するには、[Laravel の採用とランタイム移行](/docs/laravel-adoption/)を参照してください。より広いランタイム境界の比較には[デプロイモード](/docs/polyglot/deployment-modes/)を使います。 +## Worker インターセプター {#worker-interceptors} + +Worker インターセプターは PHP SDK 3.32.0 以降で利用できます。順序付きの `interceptors` を `Worker::create()`(または `Worker` コンストラクター)に渡すと、監査ログ、メトリクスタグ、テナントコンテキスト、トレースを各ハンドラーではなく、すべてのタスクの前後に一度だけ追加できます。各インターセプターは `DurableWorkflow\Worker\Interceptor\WorkerInterceptor` を実装します。必要なフックだけを実装するには `PassthroughWorkerInterceptor` を継承します。フックの形は [Python](./python.md#worker-interceptors) と [Rust](./rust.md#worker-interceptors) の SDK インターセプターと同じです。 + +次の監査インターセプターは、すべてのワークフロータスクの結果とアクティビティ試行をログに記録します。 + +```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]); +``` + +| フック | コンテキスト | `$next` の戻り値 | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying`(`replayState()` も), `updateId`, `observabilitySupported` | コマンドのコピーを持つ `WorkflowTaskOutcome` | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | アクティビティの結果 | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | クエリの結果 | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `approved`、`reason`、`message`、`failureType`、`validationErrors` を持つ `UpdateValidationOutcome` | + +インターセプターは列挙した順に実行されます。最初のインターセプターが最も外側のラッパーで、タスクの前では最初に、タスクの後では最後に実行されます。各フックはチェーンを続けるために `$next($context)` を呼び出します。トレースが設定されている場合、組み込みの Worker スパンが最も外側に留まるため、インターセプターはアクティブなタスクスパンの内側で実行されます。 + +ワークフロータスクのインターセプターは決定性を壊せません。 + +- `executeWorkflowTask` は、1つのワークフロータスクのコマンドを生成するワークフローコードを、タスク試行ごとに一度ラップします。それ以前のワークフロータスクがすでにコマンドを記録している場合、`replaying` は `true` になり、ワークフローコードはまずそのコミット済みの部分を再実行しています。結果には、このタスクが追加するコマンドだけが含まれます。リプレイされたコマンドが再送信されることはありません。 +- `replayState()` は同じ情報を、`WorkflowContext::replayState()` が使う `WorkflowReplayState`(`Replaying` または `Executing`)として返します。 +- 再試行された試行(`workflowTaskAttempt > 1`)では、タスクが失敗した結果が繰り返される可能性があるため、外部への監査書き込みは冪等にしてください。 +- Update タスク(`updateId` が設定されたもの)は、ワークフロー本体を再実行せずに、コミット済みの状態に対して Update ハンドラーを実行します。このタスクでは、`replaying` はそれ以前のコマンドが存在することを示すだけです。 +- Worker は、ワークフローコードが生成したコマンドをそのまま送信します。結果はコピーです。別の結果を返したり、別のコンテキストを `$next` に渡したりしても、何も変わりません。 +- ワークフローコードからの失敗は、インターセプターがそれを捕捉して正常に戻った場合でも、そのまま Worker に届きます。 +- インターセプターが例外をスローすると、ワークフロータスクは失敗します。何も記録されず、Server がタスクを再試行します。`$next` を呼ばなかったり、複数回呼び出したりすると、タスクは `WorkflowTaskInterceptorViolation` で失敗します。 + +Update 検証インターセプター(`executeUpdateValidation()`)は、Server が Update を受理する前に行われる、Update のバリデーターの実行をラップします。インターセプターは判定を読み取り専用の `UpdateValidationOutcome` として参照できますが、判定、Update の引数、バリデーターが読む履歴は変更できません。バリデーターは常に Worker が持つタスクのコピーを使って独自の Fiber 内で読み取り専用で実行され、Worker はバリデーター自身の判定で応答します。インターセプターが例外をスローした場合、または `$next` を呼ばなかったり複数回呼び出したりした場合(`UpdateValidationInterceptorViolation`)、タスクには `update_validation_worker_failed` で応答します。そのため Update は受理されず、呼び出し元は再試行できます。 + +アクティビティとクエリのインターセプターは、`$context->withArguments(...)` で引数を変更でき、戻り値も変更できます。アクティビティの結果は一度だけ記録され、クエリは何も記録しないためです。アクティビティの例外は、いずれかのインターセプターが処理しない限り、すべてのインターセプターを通過します。アクティビティのインターセプターはリモートアクティビティとローカルアクティビティの両方をラップし、`local` で両者を区別できます。協調的キャンセルを使う場合、リモート、協調的ローカル、準備済みローカルの各アクティビティのコールバックとそのインターセプターはアクティビティの子プロセスで実行されるため、そこでのメモリの変更は Worker プロセスに反映されません。 + +### コンテナとフレームワークの設定 {#worker-interceptor-configuration} + +インターセプターのインスタンスまたはクラス名を渡します。クラス名は、属性付きハンドラーと同じ方法で、Worker に渡された PSR-11 コンテナから解決されます。コンテナがない場合、クラス名のコンストラクターには必須の引数があってはなりません。 + +Laravel と Symfony のサービスモードでは、インターセプタークラスを `worker.interceptors` に列挙します。これらはその順序でフレームワークのコンテナから解決されます。 + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +組み込み Laravel ワークフローは、独自のインターセプターを `workflows.v2.interceptors` に設定します。[組み込み Worker インターセプター](../configuration/publishing-config.md#worker-interceptors)を参照してください。インターセプターの完全な契約は [PHP SDK リファレンス](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors)にあります。 + ## バイナリ値を含む Query 結果 {#query-binary-results} PHP SDK 3.18.2 は、入れ子の `AvroBinaryValue` バイトを含む正当な Avro 結果の Query 完了を修正します。`result_envelope` が引き続き正規の結果です。SDK は JSON にエンコードできない場合だけ任意のプレーン `result` 表現を省略し、通常の JSON 互換の結果ではその表現を保持します。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md index e80f1290b89..50a15cf9ab7 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -219,6 +219,92 @@ cargo run --features metrics-prometheus --example metrics_prometheus OpenTelemetry のメトリクスには既存 meter で recorder を実装し、単位 `1` のカウンターと秒 `s` のヒストグラムを上の名前/タグで作ります。provider、集約、resource label、exporter のライフサイクルはアプリが管理し、実行 tracing とは別です。[recorder API](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html)、[Prometheus API](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html)、[公開契約](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics)を参照してください。 +## Worker インターセプター {#worker-interceptors} + +Worker インターセプターは Rust SDK 4.25.0 以降で利用できます。監査ログ、メトリクスタグ、テナントコンテキストなどの横断的な処理を、Worker が実行するすべてのタスクに対して一度だけ追加できます。`WorkerInterceptor` を実装して `Worker::interceptor` で登録するか、複数を `Worker::interceptors` で登録します。すべてのフックはデフォルトで呼び出しをそのまま次に渡すため、必要なフックだけを実装します。`PassthroughWorkerInterceptor` は何もしないインターセプターです。フックの形は [Python](./python.md#worker-interceptors) と [PHP](./php.md#worker-interceptors) の SDK インターセプターと同じです。 + +次の監査インターセプターは、すべてのワークフロータスクの結果とアクティビティ試行をログに記録します。 + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +リポジトリの [`audit_interceptor` サンプル](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs)は、同じインターセプターをセルフホストの Server に対して実行します。 + +| フック | ラップする範囲 | コンテキスト | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | リプレイを含む1つのワークフロータスク | `WorkflowTaskInterceptorContext` | `next.run()` は読み取り専用の `WorkflowTaskOutcome` を返す | +| `execute_activity` | 1回のアクティビティまたはローカルアクティビティの試行 | `ActivityInterceptorContext` | `next.run(context)` はアクティビティの結果を返す | +| `execute_query_task` | 1つのクエリタスク | `QueryTaskInterceptorContext` | `next.run()` はクエリの結果または `QueryTaskFailure` を返す | +| `execute_update_validation_task` | 1つの更新検証タスク | `UpdateValidationInterceptorContext` | `next.run()` は読み取り専用の `UpdateValidationOutcome` を返す | + +コンテキストは読み取り専用です。Worker ID、タスクキュー、名前空間と、タスクの識別情報(タスク ID、ワークフロー ID、実行 ID、ワークフローまたはアクティビティの型、試行回数、およびワークフロータスクの場合は履歴の長さ、タスクのトレースキャリア、リプレイ状態)を保持します。アクティビティのコンテキストは、デコード済みの引数、その試行がローカルアクティビティかどうか、ハンドラーが受け取る `ActivityContext` も公開します。更新検証のコンテキストは、検証タスクの ID と試行回数、ワークフロー ID、実行 ID、ワークフローの型、更新名、トレースキャリアを保持します。 + +インターセプターは登録順に実行されます。最初に登録したものが最も外側になり、タスクの前では最初に、タスクの後では最後に実行されます。各フックはチェーンを続けるために `next` を呼び出す必要があります。最も内側の `next` が SDK 自身の処理を実行します。タスクからのエラーは、アクティビティまたはクエリのインターセプターが意図的に処理しない限り、すべてのインターセプターをそのまま通って外側に戻ります。アクティビティのインターセプターは `context.with_args(..)` で引数を変更し、結果を変換できます。また、アクティビティとクエリのインターセプターは `next` を呼ばずに応答できます。組み込みの `ExecutionTelemetry` スパンは、チェーン全体を囲む最も外側に留まります。 + +ワークフロータスクのインターセプターは、ワークフローが記録する内容を変更できません。 + +- `next.run()` は入力を受け取らないため、タスクは常に受信したとおりに実行されます。 +- Worker は、ワークフローが生成したコマンドをそのまま送信します。結果はそれらの読み取り専用のビューです。 +- タスクが失敗した場合、インターセプターが `Ok` を返しても、Worker はその失敗を報告します。インターセプターからは `Error::WorkflowTaskFailed` として見えます。これは `.kind()`、`.message()`、`.debug()` を持つ読み取り専用の説明で、Worker は元のエラーを保持します。 +- タスクが成功した後のインターセプターのエラー、または `next` を実行せずに戻ることは、ワークフロータスクを `Error::WorkflowTaskInterceptor` で失敗させます。何も記録されず、Server がタスクを再試行します。ワークフローは失敗しません。 +- インターセプターはすべてのワークフロータスクで実行されます。`context.replay_state()` は、タスクが新しい実行の前に以前のタスクでコミットされたコマンドを再実行した場合は `Replaying`、コミット済みの履歴がないタスクでは `Executing` になります。Worker はリプレイされたコマンドを再送信しないため、結果のコマンドは常にそのタスクにとって新しいものです。リプレイ状態にかかわらず、成功したすべての結果を監査してください。 +- インターセプターが観察した後にタスクが失敗した場合、その再試行で同じ結果が繰り返される可能性があります。`context.attempt()` が 1 より大きければ再試行であることを示すため、外部への監査書き込みは冪等にしてください。 + +更新検証のインターセプターは、更新が受理されるかどうかを変更できません。 + +- `next.run()` は入力を受け取らないため、バリデーターは常に受信したとおりのタスクで実行され、Worker はバリデーター自身の承認または拒否を送信します。結果は読み取り専用のビューで、`is_approved()`、`is_rejected()`、`is_worker_failure()`、`reason()`、`rejection()` を提供します。 +- インターセプターがエラーを返した場合、`next` を実行せずに戻ったり失敗したりした場合、または検証を途中で破棄した場合、Worker は代わりに `update_validation_worker_failed` を報告します。更新は受理されず、呼び出し元が同じリクエスト ID で再試行すると、バリデーターにもう一度問い合わせます。 + +オフラインの `WorkflowEnvironment` は、ラップする Worker に登録されたアクティビティのインターセプターを実行します。ワークフロータスクやクエリタスクはないため、それらのフックはそこでは実行されません。インターセプターの完全な契約については、[Rust SDK README](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors) を参照してください。 + ## Worker タスクの並行実行 {#worker-task-concurrency} 以下の有界実行レーンには Rust SDK **4.3.1 以降**が必要です。`Cargo.lock` のバージョンを確認してください。上の固定インストールは別の検証済み構成に属し、古い SDK を選ぶ場合があります。[公開パッケージの受け入れ検証](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863)では、設定した三つのスロット、解放後に初めて入る四つ目のコールバック、処理済みのアクティビティ失敗を含む七つのワークフロー完了を確認しています。前述の Server プロトコル要件は引き続き適用されます。 diff --git a/i18n/ja/source-hashes.json b/i18n/ja/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/ja/source-hashes.json +++ b/i18n/ja/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index 7dd6711ebdb..61e771efd81 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -241,3 +241,170 @@ Em seguida, registre-o em `config/workflows.php`: O componente recebe o valor atual e informações de contexto como `path`, `category`, `workflow_instance_id`, `workflow_run_id` e `workflow_type`. A exportação o chama para payloads de argumentos/saída do workflow, payloads de eventos do histórico, payload/contexto de comandos, payloads de atualizações, tarefas e atividades, e diagnósticos de mensagem/arquivo/rastreamento de falha. O pacote resultante inclui `redaction.applied`, `redaction.policy` e `redaction.paths` para que ferramentas posteriores identifiquem qual política moldou o artefato. Cada exportação também inclui um bloco `integrity` calculado após a ocultação de dados. A soma de verificação usa `canonicalization = json-recursive-ksort-v1` e `checksum_algorithm = sha256`. Quando `signing_key` está configurado, o mesmo payload canônico é assinado com `signature_algorithm = hmac-sha256` e o `signing_key_id` opcional é informado como `key_id`. Mantenha a chave de assinatura fora do artefato exportado e altere o identificador da chave quando os verificadores posteriores precisarem distinguir chaves. + +## Interceptadores de worker {#worker-interceptors} + +Os interceptadores de worker estão disponíveis a partir do Workflow 2.42.0. O Durable Workflow embarcado executa interceptadores de worker +ordenados em torno das tarefas de workflow, atividades, consultas e validações +de atualizações que executa nos processos da sua aplicação. Use-os para logs de +auditoria, tags de métricas, contexto de tenant ou tracing que você queira +escrever uma única vez, em vez de em cada workflow e atividade. O formato dos +hooks corresponde aos interceptadores dos SDKs +[Python](../polyglot/python.md#worker-interceptors), +[PHP](../polyglot/php.md#worker-interceptors) e +[Rust](../polyglot/rust.md#worker-interceptors). + +Liste as classes de interceptadores em `workflows.v2.interceptors` no +`config/workflows.php`. Elas são resolvidas a partir do contêiner do Laravel, então a +injeção pelo construtor funciona, e executam na ordem listada; o primeiro é o +wrapper mais externo. + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +Cada interceptador implementa `Workflow\V2\Interceptors\WorkerInterceptor`. +Estenda `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` para implementar apenas +os hooks de que precisar e chame `$next($context)` para continuar a cadeia. Este interceptador +de auditoria registra em log cada tarefa de workflow confirmada e cada tentativa de atividade: + +```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]); + } + } +} +``` + +O contêiner cria os interceptadores configurados para cada tarefa. Registre um como +singleton quando ele precisar manter estado entre tarefas. + +| Hook | Contexto | Retorno de `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (também `replayState()`) | `WorkflowTaskOutcome` com `historyEventTypes`, `runStatus`, `nextTaskId` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | o resultado da atividade | +| `executeQueryTask($context, $next)` | `workerId` (sempre null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (sempre `Replaying`) | o resultado da consulta | +| `executeUpdateValidation($context, $next)` | `workerId` (sempre null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (sempre `Replaying`) | `UpdateValidationOutcome` com `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` | + +`task` é um snapshot em array da linha da tarefa adquirida, nunca o próprio +model. `workerId` identifica o processo do worker de fila pelo host e pelo ID do +processo. Consultas e validações de atualizações executam no processo chamador, +então o `workerId` delas é null. + +Interceptadores de tarefa de workflow não conseguem alterar o que um workflow registra: + +- `executeWorkflowTask` envolve a tarefa de workflow dentro da sua transação de + banco de dados, uma vez por tentativa da tarefa. `replaying` é `true` quando tarefas de + workflow anteriores já registraram comandos para a execução. Ele não é uma + chave de deduplicação: `historyEventTypes` lista apenas os eventos que esta tarefa + acrescentou. +- `replayState()` dá a mesma resposta como um + `Workflow\V2\Enums\WorkflowReplayState`, o enum que `Workflow::replayState()` + usa; o valor do interceptador é fixo para a tarefa. +- Os efeitos colaterais dos hooks executam antes de a tarefa ser confirmada e podem se repetir quando uma tentativa + é executada novamente, então adie-os com `DB::afterCommit()` ou use `taskId` e + `workflowTaskAttempt` como chave. +- O engine confirma o histórico que o código do workflow produziu. O resultado é uma + visão somente leitura; retornar um resultado diferente, ou passar um contexto diferente + para `$next`, não altera nada. +- Uma falha do código do workflow chega ao engine inalterada, mesmo que um + interceptador a capture e retorne normalmente. +- Se um interceptador lançar uma exceção para fora da cadeia, pular `$next` ou chamá-lo mais de + uma vez, a transação da tarefa é revertida, então nada é registrado. A tarefa é + liberada com `WorkflowTaskInterceptorFailed` como seu último erro e executada novamente + após o backoff de reparo habitual. Um interceptador externo ainda pode capturar uma + exceção que um interceptador interno lançou depois de `$next` e deixar a tarefa ser confirmada; um + `$next` pulado ou repetido sempre faz a tarefa falhar. +- Os hooks executam enquanto as linhas da execução e da tarefa estão bloqueadas, então mantenha-os curtos. Eles + não podem confirmar nem reverter a transação em volta, e não podem enviar + comandos, como sinais, para a execução que estão envolvendo; uma alteração no estado + registrado da execução faz a tarefa falhar em todas as tentativas. +- Atividades locais executam dentro da tarefa de workflow, então um hook que continua falhando + depois de `$next` faz cada nova tentativa executar essas atividades locais novamente. + +Interceptadores de validação de atualização envolvem o replay e a chamada ao +validador que executam antes que uma atualização com um `#[UpdateValidator]` +seja aceita. Atualizações sem validador não executam o hook. Os hooks observam a +decisão; não conseguem alterá-la: + +- O engine age conforme o resultado do próprio validador. Retornar um + `UpdateValidationOutcome` diferente, ou passar argumentos diferentes para + `$next`, não muda nada; o validador sempre recebe os argumentos da + atualização. +- Se um hook lançar uma exceção, pular `$next` ou chamá-lo mais de uma vez, a + atualização é recusada com `UpdateValidationFailedException` e nada é + registrado, então um hook nunca consegue deixar uma atualização passar sem + validação. +- O hook executa dentro da transação de admissão da atualização, enquanto as + linhas da execução estão bloqueadas, então mantenha-o curto. Adie efeitos + colaterais com `DB::afterCommit()`; as gravações feitas por um hook são + confirmadas ou revertidas junto com a admissão. O código do hook executa fora + da fiber do workflow, então não consegue agendar trabalho durável para a + execução. + +Interceptadores de atividade e de consulta podem alterar argumentos com +`$context->withArguments(...)` e podem alterar o valor retornado, porque um +resultado de atividade é registrado uma única vez e uma consulta não registra nada. Argumentos +de consulta reescritos são validados novamente contra o contrato da consulta. Exceções de atividade +passam por todos os interceptadores, a menos que um deles as trate, e então seguem a +política normal de novas tentativas da atividade. Interceptadores de atividade envolvem atividades enfileiradas e locais; +`local` as diferencia. Atividades simuladas em +`WorkflowStub::fake()` não executam interceptadores. + +Quando o [tracing embarcado](../monitoring.md#embedded-tracing) está habilitado, os +spans internos de workflow e de atividade permanecem como os mais externos, de modo que os interceptadores executam dentro +do span ativo e podem adicionar atributos ou spans filhos. + +Os interceptadores envolvem os jobs de fila, as atividades locais e as consultas que este pacote +executa. Tarefas entregues a workers de SDKs externos por meio das pontes de tarefas de worker executam +sob os próprios interceptadores desse SDK. A rota `execute` da ponte de worker, que +executa no próprio processo uma tarefa de workflow adquirida para um chamador da ponte, não executa +interceptadores de tarefa de workflow. Uma entrada em `workflows.v2.interceptors` que +não possa ser resolvida falha de um jeito diferente em cada caminho: uma tarefa de workflow enfileirada é +liberada e executada novamente, uma tentativa de atividade falha conforme sua política de novas tentativas, e uma +consulta lança uma exceção para quem a chamou. Verifique a lista ao implantar. O +[guia de interceptadores embarcados](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md) +traz o contrato completo. diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md index 87efe3e4ccd..966538739be 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -362,6 +362,154 @@ modo de serviço distribuída, incluindo drenagem e rollback. Use [Modos de implantação](/docs/polyglot/deployment-modes/) para a comparação mais ampla dos limites de runtime. +## Interceptadores de worker {#worker-interceptors} + +Os interceptadores de worker estão disponíveis a partir do SDK PHP 3.32.0. Passe +`interceptors` ordenados para `Worker::create()` (ou para o construtor de `Worker`) para adicionar +logs de auditoria, tags de métricas, contexto de tenant ou tracing em torno de cada tarefa uma única vez, +em vez de em cada handler. Cada interceptador implementa +`DurableWorkflow\Worker\Interceptor\WorkerInterceptor`; estenda +`PassthroughWorkerInterceptor` para implementar apenas os hooks de que precisar. O formato +dos hooks corresponde aos interceptadores dos SDKs [Python](./python.md#worker-interceptors) e +[Rust](./rust.md#worker-interceptors). + +Este interceptador de auditoria registra em log o resultado de cada tarefa de workflow e cada tentativa de atividade: + +```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 | Contexto | Retorno de `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (também `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` com uma cópia dos comandos | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | o resultado da atividade | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | o resultado da consulta | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` com `approved`, `reason`, `message`, `failureType`, `validationErrors` | + +Os interceptadores executam na ordem em que você os lista. O primeiro interceptador é o +wrapper mais externo: ele executa primeiro antes da tarefa e por último depois dela. Cada hook +chama `$next($context)` para continuar a cadeia. Quando o tracing está configurado, os +spans internos do worker permanecem como os mais externos, de modo que os interceptadores executam dentro do +span ativo da tarefa. + +Interceptadores de tarefa de workflow não conseguem quebrar o determinismo: + +- `executeWorkflowTask` envolve o código do workflow que produz os comandos de uma tarefa + de workflow, uma vez por tentativa da tarefa. `replaying` é `true` quando tarefas de workflow + anteriores já registraram comandos, de modo que o código do workflow reexecutou primeiro esse + prefixo confirmado. O resultado contém apenas os comandos que esta tarefa adiciona; + comandos reproduzidos nunca são reenviados. +- `replayState()` informa o mesmo como o `WorkflowReplayState` que + `WorkflowContext::replayState()` usa: `Replaying` ou `Executing`. +- Uma tentativa repetida (`workflowTaskAttempt > 1`) pode repetir um resultado cuja tarefa + falhou, portanto torne idempotentes as gravações de auditoria externas. +- Tarefas de atualização (com `updateId` definido) executam o handler de atualização sobre o estado confirmado + sem reexecutar o corpo do workflow; para elas, `replaying` apenas informa que + existem comandos anteriores. +- O worker envia exatamente os comandos que o código do workflow produziu. O + resultado é uma cópia; retornar um resultado diferente, ou passar um contexto + diferente para `$next`, não altera nada. +- Uma falha do código do workflow chega ao worker inalterada, mesmo que um + interceptador a capture e retorne normalmente. +- Uma exceção lançada por um interceptador faz a tarefa de workflow falhar. Nada é + registrado e o Server tenta executar a tarefa novamente. Pular `$next`, ou chamá-lo mais + de uma vez, faz a tarefa falhar com `WorkflowTaskInterceptorViolation`. + +Interceptadores de validação de atualização (`executeUpdateValidation()`) +envolvem a execução do validador de uma atualização antes que o Server aceite a +atualização. Eles veem a decisão como um `UpdateValidationOutcome` somente +leitura e não podem alterar a decisão, os argumentos da atualização nem o +histórico que o validador lê: o validador sempre executa em modo somente leitura +na sua própria Fiber, com a cópia da tarefa mantida pelo worker, e o worker +responde com a decisão do próprio validador. Uma exceção do interceptador, ou +pular `$next` ou chamá-lo mais de uma vez +(`UpdateValidationInterceptorViolation`), responde à tarefa com +`update_validation_worker_failed`, então a atualização não é aceita e quem +chamou pode tentar novamente. + +Interceptadores de atividade e de consulta podem alterar argumentos com +`$context->withArguments(...)` e podem alterar o valor retornado, porque +resultados de atividade são registrados uma única vez e consultas não registram nada. Exceções +de atividade passam por todos os interceptadores, a menos que um deles as trate. Interceptadores +de atividade envolvem atividades remotas e locais; `local` as diferencia. Com +cancelamento cooperativo, os callbacks de atividades remotas, locais cooperativas e locais preparadas +e seus interceptadores executam no processo filho da atividade, portanto alterações de memória +ali não chegam ao processo do worker. + +### Configuração de contêiner e de framework {#worker-interceptor-configuration} + +Passe instâncias ou nomes de classe de interceptadores. Nomes de classe são resolvidos a partir do +contêiner PSR-11 passado ao worker, da mesma forma que os handlers com atributos. +Sem um contêiner, um nome de classe não pode ter argumentos obrigatórios no construtor. + +No modo de serviço do Laravel e do Symfony, liste as classes de interceptadores em +`worker.interceptors`. Elas são resolvidas a partir do contêiner do framework nessa +ordem: + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +Workflows Laravel embarcados configuram seus próprios interceptadores em +`workflows.v2.interceptors`; consulte +[interceptadores de worker embarcados](../configuration/publishing-config.md#worker-interceptors). +A [referência do SDK PHP](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors) +traz o contrato completo dos interceptadores. + ## Resultados de consulta com valores binários {#query-binary-results} O PHP SDK 3.18.2 corrige a conclusão de consultas para resultados Avro válidos com bytes `AvroBinaryValue` aninhados. `result_envelope` continua sendo a representação autoritativa. O SDK omite apenas a projeção simples opcional `result` quando não pode ser codificada em JSON; resultados comuns compatíveis com JSON mantêm essa projeção. diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md index 35613399818..4739449457a 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -279,6 +279,138 @@ cargo run --features metrics-prometheus --example metrics_prometheus Para métricas OpenTelemetry, implemente o recorder com seu meter existente: contadores de unidade `1` e histogramas em segundos `s`, com nomes/tags exatos. Provider, agregação, rótulos de recursos e ciclo do exporter pertencem à aplicação. É separado do tracing de execução. Veja a [API recorder](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), [API Prometheus](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) e [contrato publicado](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Interceptadores de worker {#worker-interceptors} + +Os interceptadores de worker estão disponíveis a partir do SDK Rust 4.25.0. Eles adicionam +comportamento transversal, como logs de auditoria, tags de métricas ou contexto de tenant, +uma única vez para cada tarefa que um worker executa. Implemente `WorkerInterceptor` e registre-o +com `Worker::interceptor`, ou vários com `Worker::interceptors`. Todo hook +repassa a chamada por padrão, então implemente apenas os hooks de que precisar; +`PassthroughWorkerInterceptor` é um interceptador que não faz nada. O formato dos hooks corresponde +aos interceptadores dos SDKs [Python](./python.md#worker-interceptors) e +[PHP](./php.md#worker-interceptors). + +Este interceptador de auditoria registra em log o resultado de cada tarefa de workflow e cada tentativa de atividade: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +O +[exemplo `audit_interceptor`](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +do repositório executa o mesmo interceptador contra um Server auto-hospedado. + +| Hook | Executa em torno de | Contexto | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | uma tarefa de workflow, incluindo o replay | `WorkflowTaskInterceptorContext` | `next.run()` retorna um `WorkflowTaskOutcome` somente leitura | +| `execute_activity` | uma tentativa de atividade ou de atividade local | `ActivityInterceptorContext` | `next.run(context)` retorna o resultado da atividade | +| `execute_query_task` | uma tarefa de consulta | `QueryTaskInterceptorContext` | `next.run()` retorna o resultado da consulta ou `QueryTaskFailure` | +| `execute_update_validation_task` | uma tarefa de validação de atualização | `UpdateValidationInterceptorContext` | `next.run()` retorna um `UpdateValidationOutcome` somente leitura | + +Os contextos são somente leitura. Eles carregam o id do worker, a fila de tarefas, o namespace e a +identidade da tarefa: id da tarefa, id do workflow, id da execução, tipo do workflow ou da atividade, +tentativa e, para tarefas de workflow, o tamanho do histórico, o carrier de trace da tarefa e o +estado de replay. Um contexto de atividade também expõe os argumentos decodificados, se +a tentativa é de uma atividade local e o `ActivityContext` que o handler recebe. +Um contexto de validação de atualização carrega o id e a tentativa da tarefa de +validação, o id, o id da execução e o tipo do workflow, o nome da atualização e +o carrier de trace. + +Os interceptadores executam na ordem de registro. O primeiro registrado é o +mais externo: ele executa primeiro antes da tarefa e por último depois dela. Cada hook precisa chamar +`next` para continuar a cadeia; o `next` mais interno executa o tratamento próprio do SDK. +Erros da tarefa voltam por todos os interceptadores inalterados, a menos que +um interceptador de atividade ou de consulta os trate deliberadamente. Interceptadores +de atividade podem alterar argumentos com `context.with_args(..)` e transformar +resultados, e interceptadores de atividade e de consulta podem responder sem chamar `next`. +Os spans internos de `ExecutionTelemetry` permanecem como os mais externos em torno de toda a cadeia. + +Interceptadores de tarefa de workflow não conseguem alterar o que um workflow registra: + +- `next.run()` não recebe entrada, então a tarefa sempre executa como foi recebida. +- O worker envia exatamente os comandos que o workflow produziu. O resultado é + uma visão somente leitura deles. +- Se a tarefa falhar, o worker relata essa falha mesmo quando um interceptador + retorna `Ok`. Os interceptadores a veem como `Error::WorkflowTaskFailed`, uma + descrição somente leitura com `.kind()`, `.message()` e `.debug()`; o worker mantém o + erro original. +- Um erro de interceptador depois que a tarefa teve sucesso, ou retornar sem executar + `next`, faz a tarefa de workflow falhar com `Error::WorkflowTaskInterceptor`. Nada + é registrado e o Server tenta executar a tarefa novamente. O workflow não falha. +- Os interceptadores executam em toda tarefa de workflow. `context.replay_state()` é + `Replaying` quando a tarefa reexecutou comandos confirmados por tarefas anteriores antes + da nova execução, e `Executing` para uma tarefa sem histórico confirmado. O + worker nunca reenvia comandos reproduzidos, então os comandos de um resultado são sempre + novos para aquela tarefa: audite todo resultado bem-sucedido, qualquer que seja o estado de replay. +- Se uma tarefa falhar depois que um interceptador a observou, sua nova tentativa pode repetir o + mesmo resultado; `context.attempt()` acima de 1 identifica uma nova tentativa, portanto torne + idempotentes as gravações de auditoria externas. + +Interceptadores de validação de atualização não conseguem alterar se uma +atualização é aceita: + +- `next.run()` não recebe entrada, então o validador sempre executa sobre a + tarefa como foi recebida, e o worker envia a aprovação ou a rejeição do + próprio validador. O resultado é uma visão somente leitura: `is_approved()`, + `is_rejected()`, `is_worker_failure()`, `reason()` e `rejection()`. +- Um erro do interceptador, retornar ou falhar sem executar `next`, ou abandonar + a validação no meio faz o worker reportar `update_validation_worker_failed` em + vez disso. A atualização não é aceita, e a nova tentativa de quem chamou com o + mesmo id de requisição consulta o validador de novo. + +O `WorkflowEnvironment` offline executa os interceptadores de atividade registrados no +worker que ele envolve. Ele não tem tarefas de workflow nem de consulta, então esses hooks não executam +ali. Consulte o +[README do SDK Rust](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors) +para o contrato completo dos interceptadores. + ## Concorrência de tarefas do worker {#worker-task-concurrency} As faixas limitadas descritas aqui exigem Rust SDK **4.3.1 ou posterior**. Confira a versão em `Cargo.lock`: a instalação fixada acima pertence a outra tupla qualificada e pode selecionar um SDK anterior. A [aceitação do pacote publicado](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) verifica três slots configurados, uma quarta chamada admitida após a liberação de um slot e sete workflows concluídos, incluindo uma falha de atividade tratada. Os requisitos de protocolo do Server descritos acima continuam valendo. diff --git a/i18n/pt-BR/source-hashes.json b/i18n/pt-BR/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/pt-BR/source-hashes.json +++ b/i18n/pt-BR/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/uk/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index d47c3f617ef..df42814f420 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -330,3 +330,170 @@ final class WorkflowHistoryExportRedactor implements HistoryExportRedactor необов’язковий `signing_key_id` повідомляється як `key_id`. Зберігайте ключ підпису поза експортованим файлом і змінюйте ідентифікатор ключа, коли подальшим засобам перевірки потрібно розрізняти ключі. + +## Перехоплювачі worker {#worker-interceptors} + +Перехоплювачі worker доступні починаючи з Workflow 2.42.0. +Вбудований Durable Workflow запускає впорядковані перехоплювачі worker навколо +завдань workflow, activity, query та валідацій update, які він виконує в +процесах вашого застосунку. Використовуйте їх для журналу аудиту, міток метрик, +контексту tenant чи трасування, які ви хочете написати один раз, а не в кожному +workflow та activity. Форма hook відповідає перехоплювачам +[Python](../polyglot/python.md#worker-interceptors), +[PHP](../polyglot/php.md#worker-interceptors) і +[Rust](../polyglot/rust.md#worker-interceptors) SDK. + +Перелічіть класи перехоплювачів у `workflows.v2.interceptors` у +`config/workflows.php`. Вони розв’язуються з контейнера Laravel, тож впровадження +через конструктор працює, і виконуються в зазначеному порядку; перший є зовнішньою +обгорткою. + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +Кожен перехоплювач реалізує `Workflow\V2\Interceptors\WorkerInterceptor`. +Розширте `Workflow\V2\Interceptors\PassthroughWorkerInterceptor`, щоб реалізувати +лише потрібні hook, і викликайте `$next($context)`, щоб продовжити ланцюжок. Цей +перехоплювач аудиту журналює кожне зафіксоване завдання workflow і кожну спробу +activity: + +```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]); + } + } +} +``` + +Контейнер створює налаштовані перехоплювачі для кожного завдання. Прив’яжіть +перехоплювач як singleton, коли він має зберігати стан між завданнями. + +| Hook | Контекст | Повертає `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (також `replayState()`) | `WorkflowTaskOutcome` з `historyEventTypes`, `runStatus`, `nextTaskId` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | результат activity | +| `executeQueryTask($context, $next)` | `workerId` (завжди null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (завжди `Replaying`) | результат query | +| `executeUpdateValidation($context, $next)` | `workerId` (завжди null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()` (завжди `Replaying`) | `UpdateValidationOutcome` з `approved`, `rejectionMessage`, `exceptionType`, `validationErrors` | + +`task` є знімком узятого рядка завдання у вигляді масиву, а не самою моделлю. +`workerId` ідентифікує процес queue worker за хостом та ID процесу. Query та +валідації update виконуються у викликальному процесі, тому їхній `workerId` +дорівнює null. + +Перехоплювачі завдань workflow не можуть змінити те, що записує workflow: + +- `executeWorkflowTask` обгортає завдання workflow всередині його транзакції бази + даних, один раз на кожну спробу завдання. `replaying` має значення `true`, коли + попередні завдання workflow уже записали команди для run. Це не ключ + дедуплікації: `historyEventTypes` перелічує лише події, які додало це завдання. +- `replayState()` дає ту саму відповідь у вигляді + `Workflow\V2\Enums\WorkflowReplayState`, enum, який використовує + `Workflow::replayState()`; значення перехоплювача незмінне протягом завдання. +- Побічні ефекти hook виконуються до фіксації завдання й можуть повторитися під час + повторної спроби, тож відкладайте їх через `DB::afterCommit()` або прив’язуйте їх + до ключа з `taskId` і `workflowTaskAttempt`. +- Рушій фіксує історію, яку створив код workflow. Результат є поданням лише для + читання; повернення іншого результату чи передавання іншого контексту в `$next` + нічого не змінює. +- Помилка з коду workflow доходить до рушія без змін, навіть якщо перехоплювач + перехоплює її та повертається звичайним чином. +- Якщо перехоплювач кидає виняток за межі ланцюжка, пропускає `$next` або викликає + його більше одного разу, транзакція завдання відкочується, тож нічого не + записується. Завдання звільняється з `WorkflowTaskInterceptorFailed` як останньою + помилкою й повторюється після звичайного backoff відновлення. Зовнішній + перехоплювач усе ще може перехопити виняток, кинутий внутрішнім перехоплювачем + після `$next`, і дозволити завданню зафіксуватися; пропущений або повторений + `$next` завжди спричиняє збій завдання. +- Hook виконуються, поки рядки run і завдання заблоковані, тож робіть їх короткими. + Вони не повинні фіксувати чи відкочувати зовнішню транзакцію й не повинні + надсилати команди, як-от signal, run, який вони обгортають; зміна записаного + стану run спричиняє збій завдання за кожної спроби. +- Local activity виконуються всередині завдання workflow, тож hook, який постійно + завершується помилкою після `$next`, змушує кожну повторну спробу знову + виконувати ці local activity. + +Перехоплювачі валідації update обгортають replay і виклик валідатора, які +виконуються до прийняття update з `#[UpdateValidator]`. Для update без +валідатора hook не запускається. Hook спостерігають за рішенням, але не можуть +його змінити: + +- Рушій діє за власним результатом валідатора. Повернення іншого + `UpdateValidationOutcome` або передавання інших аргументів у `$next` нічого не + змінює; валідатор завжди отримує аргументи update. +- Якщо hook кидає виняток, пропускає `$next` або викликає його більше одного + разу, update відхиляється з `UpdateValidationFailedException` і нічого не + записується, тож hook ніколи не може пропустити update без валідації. +- Hook виконується всередині транзакції приймання update, поки рядки run + заблоковані, тому робіть його коротким. Відкладайте побічні ефекти через + `DB::afterCommit()`; записи, які робить hook, фіксуються або відкочуються + разом із прийманням. Код hook виконується поза fiber workflow, тому не може + планувати durable-роботу для run. + +Перехоплювачі activity та query можуть змінювати аргументи через +`$context->withArguments(...)` і змінювати повернене значення, оскільки результат +activity записується один раз, а query нічого не записує. Переписані аргументи query +знову перевіряються за контрактом query. Винятки activity проходять крізь кожен +перехоплювач, якщо жоден із них їх не обробить, а потім обробляються звичайною +політикою повторних спроб activity. Перехоплювачі activity обгортають activity з +черги та local activity; `local` розрізняє їх. Імітовані activity у +`WorkflowStub::fake()` не запускають перехоплювачів. + +Коли [вбудоване трасування](../monitoring.md#embedded-tracing) увімкнено, вбудовані +span workflow та activity залишаються зовнішніми, тож перехоплювачі виконуються +всередині активного span і можуть додавати атрибути чи дочірні span. + +Перехоплювачі обгортають завдання черги, local activity та query, які запускає цей +пакет. Завдання, передані зовнішнім SDK worker через мости завдань worker, +виконуються під власними перехоплювачами відповідного SDK. Маршрут `execute` мосту +worker, який виконує взяте завдання workflow у процесі для викликача мосту, не +запускає перехоплювачі завдань workflow. Запис у `workflows.v2.interceptors`, який +не вдається розв’язати, спричиняє збій кожного шляху по-своєму: завдання workflow із +черги звільняється й повторюється, спроба activity завершується помилкою відповідно +до своєї політики повторних спроб, а query кидає виняток своєму викликачу. +Перевіряйте список під час розгортання. +[Посібник із вбудованих перехоплювачів](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md) +містить повний контракт. diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md index 225c441b2c4..05d179770e6 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -357,6 +357,152 @@ service mode, включно з drain і rollback. Ширше порівняння меж runtime наведено в [режимах розгортання](/docs/polyglot/deployment-modes/). +## Перехоплювачі worker {#worker-interceptors} + +Перехоплювачі worker доступні починаючи з PHP SDK 3.32.0. Передайте +впорядкований список `interceptors` у `Worker::create()` (або конструктор `Worker`), +щоб один раз додати журнал аудиту, мітки метрик, контекст tenant чи трасування +навколо кожного завдання, а не в кожному обробнику. Кожен перехоплювач реалізує +`DurableWorkflow\Worker\Interceptor\WorkerInterceptor`; розширте +`PassthroughWorkerInterceptor`, щоб реалізувати лише потрібні hook. Форма hook +відповідає перехоплювачам [Python](./python.md#worker-interceptors) і +[Rust](./rust.md#worker-interceptors) SDK. + +Цей перехоплювач аудиту журналює результат кожного завдання workflow і кожну спробу activity: + +```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 | Контекст | Повертає `$next` | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying` (також `replayState()`), `updateId`, `observabilitySupported` | `WorkflowTaskOutcome` з копією команд | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | результат activity | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | результат query | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | `UpdateValidationOutcome` з `approved`, `reason`, `message`, `failureType`, `validationErrors` | + +Перехоплювачі працюють у порядку, в якому ви їх перелічили. Перший перехоплювач є +зовнішньою обгорткою: він виконується першим перед завданням і останнім після нього. +Кожен hook викликає `$next($context)`, щоб продовжити ланцюжок. Коли налаштовано +трасування, вбудовані span worker залишаються зовнішніми, тож перехоплювачі +виконуються всередині активного span завдання. + +Перехоплювачі завдань workflow не можуть порушити детермінованість: + +- `executeWorkflowTask` обгортає код workflow, який створює команди одного + завдання workflow, один раз на кожну спробу завдання. `replaying` має значення + `true`, коли попередні завдання workflow уже записали команди, тож код workflow + спершу повторно виконав цей зафіксований префікс. Результат містить лише команди, + які додає це завдання; команди з replay ніколи не надсилаються повторно. +- `replayState()` повідомляє те саме у вигляді `WorkflowReplayState`, який + використовує `WorkflowContext::replayState()`: `Replaying` або `Executing`. +- Повторна спроба (`workflowTaskAttempt > 1`) може повторити результат, завдання + якого завершилося помилкою, тому робіть зовнішні записи аудиту ідемпотентними. +- Завдання update (із заданим `updateId`) виконують обробник update над + зафіксованим станом без повторного виконання тіла workflow; для них `replaying` + лише повідомляє, що попередні команди існують. +- Worker надсилає рівно ті команди, які створив код workflow. Результат є копією; + повернення іншого результату чи передавання іншого контексту в `$next` нічого + не змінює. +- Помилка з коду workflow доходить до worker без змін, навіть якщо перехоплювач + перехоплює її та повертається звичайним чином. +- Виняток, кинутий перехоплювачем, спричиняє збій завдання workflow. Нічого не + записується, і Server повторює завдання. Пропуск `$next` або його виклик більше + одного разу спричиняє збій завдання з `WorkflowTaskInterceptorViolation`. + +Перехоплювачі валідації update (`executeUpdateValidation()`) обгортають запуск +валідатора update до того, як Server прийме update. Вони бачать рішення як +`UpdateValidationOutcome` лише для читання і не можуть змінити ні рішення, ні +аргументи update, ні історію, яку читає валідатор: валідатор завжди працює лише +для читання у власному Fiber з копією завдання, що належить worker, а worker +відповідає власним рішенням валідатора. Виняток із перехоплювача, пропуск +`$next` або його виклик більше одного разу +(`UpdateValidationInterceptorViolation`) дає відповідь на завдання з +`update_validation_worker_failed`, тож update не приймається, і викликач може +повторити спробу. + +Перехоплювачі activity та query можуть змінювати аргументи через +`$context->withArguments(...)` і змінювати повернене значення, оскільки результати +activity записуються один раз, а query нічого не записують. Винятки activity +проходять крізь кожен перехоплювач, якщо жоден із них їх не обробить. Перехоплювачі +activity обгортають віддалені та локальні activity; `local` розрізняє їх. За +кооперативного скасування callback віддалених, кооперативних локальних і +підготовлених локальних activity та їхні перехоплювачі виконуються в дочірньому +процесі activity, тож зміни пам’яті там не доходять до процесу worker. + +### Налаштування контейнера й фреймворку {#worker-interceptor-configuration} + +Передавайте екземпляри перехоплювачів або назви класів. Назви класів розв’язуються +з PSR-11 контейнера, переданого worker, так само як обробники з атрибутами. Без +контейнера клас не повинен мати обов’язкових аргументів конструктора. + +У сервісному режимі Laravel і Symfony перелічіть класи перехоплювачів у +`worker.interceptors`. Вони розв’язуються з контейнера фреймворку в такому порядку: + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +Вбудовані workflow Laravel налаштовують власні перехоплювачі в +`workflows.v2.interceptors`; див. +[перехоплювачі вбудованого worker](../configuration/publishing-config.md#worker-interceptors). +[Довідник PHP SDK](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors) +містить повний контракт перехоплювачів. + ## Результати запитів із бінарними значеннями {#query-binary-results} PHP SDK 3.18.2 виправляє завершення запитів для коректних результатів Avro із вкладеними байтами `AvroBinaryValue`. `result_envelope` залишається авторитетним поданням. SDK пропускає лише необов’язкову просту проєкцію `result`, коли її неможливо закодувати в JSON; звичайні JSON-сумісні результати зберігають цю проєкцію. diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md index 1b697e785c5..71b8a0f29ce 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -279,6 +279,138 @@ cargo run --features metrics-prometheus --example metrics_prometheus Для OpenTelemetry реалізуйте recorder через наявний meter: лічильники з одиницею `1` і гістограми секунд `s` з точними назвами/тегами вище. Provider, aggregation, resource labels і життєвий цикл exporter належать застосунку. Це окремо від execution tracing. Див. [recorder API](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html), [Prometheus API](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) і [опублікований контракт](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics). +## Перехоплювачі worker {#worker-interceptors} + +Перехоплювачі worker доступні починаючи з Rust SDK 4.25.0. Вони один +раз додають наскрізну поведінку, як-от журнал аудиту, мітки метрик чи контекст +tenant, для кожного завдання, яке виконує worker. Реалізуйте `WorkerInterceptor` і +зареєструйте його через `Worker::interceptor` або кілька через `Worker::interceptors`. +Кожен hook типово передає виклик далі, тож реалізуйте лише потрібні hook; +`PassthroughWorkerInterceptor` є перехоплювачем, що нічого не робить. Форма hook +відповідає перехоплювачам [Python](./python.md#worker-interceptors) і +[PHP](./php.md#worker-interceptors) SDK. + +Цей перехоплювач аудиту журналює результат кожного завдання workflow і кожну спробу activity: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +[Приклад `audit_interceptor`](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs) +у репозиторії запускає той самий перехоплювач із самостійно розгорнутим Server. + +| Hook | Що обгортає | Контекст | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | одне завдання workflow, включно з replay | `WorkflowTaskInterceptorContext` | `next.run()` повертає `WorkflowTaskOutcome` лише для читання | +| `execute_activity` | одну спробу activity або local activity | `ActivityInterceptorContext` | `next.run(context)` повертає результат activity | +| `execute_query_task` | одне завдання query | `QueryTaskInterceptorContext` | `next.run()` повертає результат query або `QueryTaskFailure` | +| `execute_update_validation_task` | одне завдання валідації update | `UpdateValidationInterceptorContext` | `next.run()` повертає `UpdateValidationOutcome` лише для читання | + +Контексти доступні лише для читання. Вони містять id worker, task queue, namespace +та ідентичність завдання: id завдання, id workflow, id run, тип workflow чи +activity, спробу, а для завдань workflow — довжину історії, trace carrier завдання +та стан replay. Контекст activity також надає декодовані аргументи, ознаку того, чи +є спроба local activity, і `ActivityContext`, який отримує обробник. +Контекст валідації update містить id та спробу завдання валідації, id workflow, +id run і тип workflow, назву update та trace carrier. + +Перехоплювачі виконуються в порядку реєстрації. Перший зареєстрований є зовнішнім: +він виконується першим перед завданням і останнім після нього. Кожен hook має +викликати `next`, щоб продовжити ланцюжок; найглибший `next` запускає власну обробку +SDK. Помилки завдання повертаються назовні крізь кожен перехоплювач без змін, якщо +перехоплювач activity чи query навмисно їх не обробить. Перехоплювачі activity +можуть змінювати аргументи через `context.with_args(..)` і перетворювати результати, +а перехоплювачі activity та query можуть відповідати без виклику `next`. +Вбудовані span `ExecutionTelemetry` залишаються зовнішніми навколо всього ланцюжка. + +Перехоплювачі завдань workflow не можуть змінити те, що записує workflow: + +- `next.run()` не приймає вхідних даних, тож завдання завжди виконується таким, + яким його отримано. +- Worker надсилає рівно ті команди, які створив workflow. Результат є поданням + цих команд лише для читання. +- Якщо завдання завершується помилкою, worker повідомляє про цю помилку, навіть + коли перехоплювач повертає `Ok`. Перехоплювачі бачать її як + `Error::WorkflowTaskFailed` — опис лише для читання з `.kind()`, `.message()` і + `.debug()`; worker зберігає початкову помилку. +- Помилка перехоплювача після успішного завдання або повернення без виконання + `next` спричиняє збій завдання workflow з `Error::WorkflowTaskInterceptor`. + Нічого не записується, і Server повторює завдання. Workflow не завершується помилкою. +- Перехоплювачі виконуються для кожного завдання workflow. `context.replay_state()` + має значення `Replaying`, коли завдання перед новим виконанням повторно виконало + команди, зафіксовані попередніми завданнями, і `Executing` для завдання без + зафіксованої історії. Worker ніколи не надсилає повторно команди з replay, тож + команди результату завжди нові для цього завдання: аудитуйте кожен успішний + результат незалежно від стану replay. +- Якщо завдання завершується помилкою після того, як перехоплювач його спостеріг, + його повторна спроба може повторити той самий результат; `context.attempt()` + більше 1 позначає повторну спробу, тому робіть зовнішні записи аудиту + ідемпотентними. + +Перехоплювачі валідації update не можуть змінити те, чи буде update прийнято: + +- `next.run()` не приймає вхідних даних, тому валідатор завжди працює із + завданням у тому вигляді, в якому його отримано, а worker надсилає власне + схвалення чи відхилення валідатора. Результат є поданням лише для читання: + `is_approved()`, `is_rejected()`, `is_worker_failure()`, `reason()` та + `rejection()`. +- Помилка перехоплювача, повернення чи збій без запуску `next` або переривання + валідації на півдорозі змушують worker натомість повідомити + `update_validation_worker_failed`. Update не приймається, а повторна спроба + викликача з тим самим id запиту знову звертається до валідатора. + +Офлайн-`WorkflowEnvironment` запускає перехоплювачі activity, зареєстровані на +worker, який він обгортає. У ньому немає завдань workflow чи query, тож ці hook там +не виконуються. Повний контракт перехоплювачів див. у +[README Rust SDK](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors). + ## Паралельність завдань worker {#worker-task-concurrency} Описані нижче обмежені лінії виконання потребують Rust SDK **4.3.1 або новішого**. Перевірте версію в `Cargo.lock`: наведена вище фіксація встановлення належить окремому кваліфікованому набору артефактів і може обирати старіший SDK. [Перевірка опублікованого пакета](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863) підтверджує три налаштовані слоти, допуск четвертого виклику після звільнення слота і сім завершених workflow, зокрема з обробленою помилкою activity. Вимоги протоколу Server вище залишаються чинними. diff --git a/i18n/uk/source-hashes.json b/i18n/uk/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/uk/source-hashes.json +++ b/i18n/uk/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/configuration/publishing-config.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/configuration/publishing-config.md index c6324a99257..69d3f1190ec 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/configuration/publishing-config.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/configuration/publishing-config.md @@ -237,3 +237,100 @@ final class WorkflowHistoryExportRedactor implements HistoryExportRedactor 脱敏器接收当前值,以及 `path`、`category`、`workflow_instance_id`、`workflow_run_id` 和 `workflow_type` 等上下文。导出会对工作流参数/输出载荷、历史事件载荷、命令载荷/上下文、更新载荷、任务载荷、活动载荷,以及故障消息/文件/堆栈诊断调用它。生成的包包含 `redaction.applied`、`redaction.policy` 和 `redaction.paths`,便于下游工具了解产物应用了哪种策略。 每次导出还包含脱敏后计算的 `integrity` 块。校验和使用 `canonicalization = json-recursive-ksort-v1` 和 `checksum_algorithm = sha256`;配置 `signing_key` 后,同一规范化载荷以 `signature_algorithm = hmac-sha256` 签名,可选的 `signing_key_id` 则报告为 `key_id`。签名密钥应保存在导出产物之外,下游验证器需要区分密钥时,应更新密钥 ID。 + +## Worker 拦截器 {#worker-interceptors} + +Worker 拦截器从 Workflow 2.42.0 开始提供。嵌入式 Durable Workflow 会围绕它在应用进程中执行的工作流任务、活动、查询和更新验证运行有序的 Worker 拦截器。审计日志、指标标签、租户上下文或追踪等逻辑只需编写一次,而无需在每个工作流和活动中重复实现。钩子的形式与 [Python](../polyglot/python.md#worker-interceptors)、[PHP](../polyglot/php.md#worker-interceptors) 和 [Rust](../polyglot/rust.md#worker-interceptors) SDK 拦截器一致。 + +在 `config/workflows.php` 的 `workflows.v2.interceptors` 下列出拦截器类。它们从 Laravel 容器中解析,因此支持构造函数注入,并按列出的顺序运行;第一个是最外层包装。 + +```php +'v2' => [ + // ... + 'interceptors' => [ + App\Workflows\AuditInterceptor::class, + ], +], +``` + +每个拦截器都实现 `Workflow\V2\Interceptors\WorkerInterceptor`。继承 `Workflow\V2\Interceptors\PassthroughWorkerInterceptor` 即可只实现所需的钩子,并调用 `$next($context)` 继续链。下面的审计拦截器会记录每个已提交的工作流任务和每次活动尝试: + +```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]); + } + } +} +``` + +容器会为每个任务构建配置的拦截器。如果拦截器必须在任务之间保留状态,请将其绑定为单例。 + +| 钩子 | 上下文 | `$next` 返回 | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying`(另有 `replayState()`) | 包含 `historyEventTypes`、`runStatus`、`nextTaskId` 的 `WorkflowTaskOutcome` | +| `executeActivity($context, $next)` | `workerId`, `connection`, `taskQueue`, `namespace`, `task`, `activityType`, `activityClass`, `arguments`, `attemptNumber`, `taskId`, `activityExecutionId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activity` | 活动结果 | +| `executeQueryTask($context, $next)` | `workerId`(始终为 null), `connection`, `taskQueue`, `namespace`, `task`, `queryName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()`(始终为 `Replaying`) | 查询结果 | +| `executeUpdateValidation($context, $next)` | `workerId`(始终为 null), `connection`, `taskQueue`, `namespace`, `updateName`, `workflowType`, `workflowId`, `runId`, `arguments`, `replayState()`(始终为 `Replaying`) | 包含 `approved`、`rejectionMessage`、`exceptionType`、`validationErrors` 的 `UpdateValidationOutcome` | + +`task` 是已认领任务行的数组快照,绝不是模型本身。`workerId` 通过主机和进程 ID 标识队列 Worker 进程。查询和更新验证在调用方进程中运行,因此其 `workerId` 为 null。 + +工作流任务拦截器无法改变工作流记录的内容: + +- `executeWorkflowTask` 在工作流任务的数据库事务内包裹该任务,每次任务尝试运行一次。当之前的工作流任务已为该运行记录命令时,`replaying` 为 `true`。它不是去重键:`historyEventTypes` 只列出本任务追加的事件。 +- `replayState()` 以 `Workflow\V2\Enums\WorkflowReplayState`(即 `Workflow::replayState()` 所用的枚举)给出相同的答案;拦截器看到的值在该任务内固定不变。 +- 钩子的副作用在任务提交之前运行,并且在尝试被重试时可能重复,因此请使用 `DB::afterCommit()` 延迟执行,或以 `taskId` 和 `workflowTaskAttempt` 作为键。 +- 引擎提交工作流代码生成的历史。结果是只读视图;返回不同的结果,或向 `$next` 传入不同的上下文,都不会产生任何改变。 +- 工作流代码产生的失败会原样到达引擎,即使拦截器捕获了它并正常返回。 +- 如果拦截器从链中抛出异常、跳过 `$next` 或多次调用它,任务的事务会回滚,因此不会记录任何内容。任务会以 `WorkflowTaskInterceptorFailed` 作为最后错误被释放,并在常规修复退避之后重试。外层拦截器仍可捕获内层拦截器在 `$next` 之后抛出的异常并让任务提交;跳过或重复调用 `$next` 则始终会使任务失败。 +- 钩子在运行行和任务行被锁定期间运行,因此请保持简短。钩子不得提交或回滚外层事务,也不得向其包裹的运行发送信号等命令;改变该运行的已记录状态会使任务在每次尝试中都失败。 +- 本地活动在工作流任务内运行,因此在 `$next` 之后持续失败的钩子会使每次重试都再次运行这些本地活动。 + +更新验证拦截器包裹在带有 `#[UpdateValidator]` 的更新被接受之前运行的重放和验证器调用。没有验证器的更新不会运行该钩子。钩子只能观察判定结果,无法改变它: + +- 引擎依据验证器自身的结果行事。返回不同的 `UpdateValidationOutcome`,或向 `$next` 传入不同的参数,都不会产生任何改变;验证器始终收到更新的参数。 +- 如果钩子抛出异常、跳过 `$next` 或多次调用它,更新会以 `UpdateValidationFailedException` 被拒绝,且不会记录任何内容,因此钩子绝不可能让未经验证的更新通过。 +- 钩子在更新的准入事务内运行,此时该运行的行已被锁定,因此请保持简短。请使用 `DB::afterCommit()` 延迟副作用;钩子所做的写入会随准入一起提交或回滚。钩子代码在工作流 Fiber 之外运行,因此无法为该运行调度持久工作。 + +活动拦截器和查询拦截器可以通过 `$context->withArguments(...)` 修改参数,也可以修改返回值,因为活动结果只记录一次,而查询不记录任何内容。改写后的查询参数会再次根据查询契约进行校验。活动异常会穿过所有拦截器,除非某个拦截器处理了它,然后按活动的常规重试策略处理。活动拦截器包裹队列活动和本地活动;`local` 用于区分二者。`WorkflowStub::fake()` 中被模拟的活动不会运行拦截器。 + +启用[嵌入式追踪](../monitoring.md#embedded-tracing)后,内置的工作流和活动 span 始终位于最外层,因此拦截器在当前活动的 span 内运行,并可添加属性或子 span。 + +拦截器包裹本包运行的队列作业、本地活动和查询。通过 Worker 任务桥接交给外部 SDK Worker 的任务,在该 SDK 自己的拦截器下运行。Worker 桥接的 `execute` 路由会为桥接调用方在进程内运行已认领的工作流任务,它不会运行工作流任务拦截器。`workflows.v2.interceptors` 中无法解析的条目会在各条路径上以各自的方式失败:队列中的工作流任务会被释放并重试,活动尝试会按其重试策略失败,查询则会向调用方抛出异常。部署时请检查该列表。完整契约见[嵌入式拦截器指南](https://github.com/durable-workflow/workflow/blob/main/docs/worker-interceptors.md)。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md index c36e946e344..e8979efeefb 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -252,6 +252,105 @@ Worker 会自动声明 `workflow_entry_arguments_validation`。在配套 Server 这些桥接不同于[嵌入式 Laravel 工作流](/docs/installation/);后者通过 `durable-workflow/workflow` 使 Laravel 应用自身管理持久状态并通过 Laravel 队列执行。参见 [Laravel 采用与运行时迁移](/docs/laravel-adoption/),了解同一个典型 Laravel 用例如何使用 v1、v2 嵌入式及已提供的服务模式桥接,包括排空和回滚。更全面的运行时边界比较见[部署模式](/docs/polyglot/deployment-modes/)。 +## Worker 拦截器 {#worker-interceptors} + +Worker 拦截器从 PHP SDK 3.32.0 开始提供。向 `Worker::create()`(或 `Worker` 构造函数)传入有序的 `interceptors`,即可围绕每个任务统一添加审计日志、指标标签、租户上下文或追踪,而无需在每个处理器中分别实现。每个拦截器都实现 `DurableWorkflow\Worker\Interceptor\WorkerInterceptor`;继承 `PassthroughWorkerInterceptor` 即可只实现所需的钩子。钩子的形式与 [Python](./python.md#worker-interceptors) 和 [Rust](./rust.md#worker-interceptors) SDK 拦截器一致。 + +下面的审计拦截器会记录每个工作流任务的结果和每次活动尝试: + +```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]); +``` + +| 钩子 | 上下文 | `$next` 返回 | +| --- | --- | --- | +| `executeWorkflowTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `workflowId`, `runId`, `workflowTaskAttempt`, `historyLength`, `replaying`(另有 `replayState()`), `updateId`, `observabilitySupported` | 包含命令副本的 `WorkflowTaskOutcome` | +| `executeActivity($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `activityType`, `arguments`, `attemptNumber`, `taskId`, `activityAttemptId`, `workflowId`, `runId`, `local`, `activityContext`, `observabilitySupported` | 活动结果 | +| `executeQueryTask($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `queryName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | 查询结果 | +| `executeUpdateValidation($context, $next)` | `workerId`, `taskQueue`, `namespace`, `task`, `taskId`, `workflowType`, `updateName`, `workflowId`, `runId`, `arguments`, `queryContext`, `observabilitySupported` | 包含 `approved`、`reason`、`message`、`failureType`、`validationErrors` 的 `UpdateValidationOutcome` | + +拦截器按列出的顺序运行。首个拦截器是最外层包装:它在任务之前最先运行,在任务之后最后运行。每个钩子调用 `$next($context)` 继续链。配置追踪后,内置 Worker span 始终位于最外层,因此拦截器在当前活动的任务 span 内运行。 + +工作流任务拦截器不会破坏确定性: + +- `executeWorkflowTask` 包裹生成一个工作流任务命令的工作流代码,每次任务尝试运行一次。当之前的工作流任务已记录命令时,`replaying` 为 `true`,此时工作流代码会先重新运行这段已提交的前缀。结果只包含本任务新增的命令;重放的命令绝不会被重新提交。 +- `replayState()` 以 `WorkflowContext::replayState()` 所用的 `WorkflowReplayState` 报告同样的信息:`Replaying` 或 `Executing`。 +- 重试的尝试(`workflowTaskAttempt > 1`)可能重复一个任务失败的结果,因此外部审计写入应保持幂等。 +- 更新任务(设置了 `updateId`)针对已提交状态运行更新处理器,不会重新运行工作流主体;对于这类任务,`replaying` 只表示之前已有命令。 +- Worker 准确提交工作流代码生成的命令。结果是一个副本;返回不同的结果,或向 `$next` 传入不同的上下文,都不会产生任何改变。 +- 工作流代码产生的失败会原样到达 Worker,即使拦截器捕获了它并正常返回。 +- 拦截器抛出的异常会使工作流任务失败。不会记录任何内容,Server 会重试该任务。跳过 `$next` 或多次调用它,会使任务以 `WorkflowTaskInterceptorViolation` 失败。 + +更新验证拦截器(`executeUpdateValidation()`)包裹在 Server 接受更新之前运行的更新验证器。它们以只读的 `UpdateValidationOutcome` 查看判定结果,但无法改变判定、更新的参数或验证器读取的历史:验证器始终使用 Worker 持有的任务副本,在自己的 Fiber 中以只读方式运行,Worker 以验证器自身的判定作答。拦截器抛出异常,或跳过 `$next`、多次调用它(`UpdateValidationInterceptorViolation`),都会以 `update_validation_worker_failed` 应答该任务,因此更新不会被接受,调用方可以重试。 + +活动拦截器和查询拦截器可以通过 `$context->withArguments(...)` 修改参数,也可以修改返回值,因为活动结果只记录一次,而查询不记录任何内容。活动异常会穿过所有拦截器,除非某个拦截器处理了它。活动拦截器包裹远程活动和本地活动;`local` 用于区分二者。启用协作式取消时,远程活动、协作式本地活动和预备本地活动的回调及其拦截器在活动的子进程中运行,因此那里的内存变更不会传回 Worker 进程。 + +### 容器与框架配置 {#worker-interceptor-configuration} + +可以传入拦截器实例或类名。类名通过传给 Worker 的 PSR-11 容器解析,方式与带属性的处理器相同。没有容器时,类名对应的类不能有必需的构造函数参数。 + +在 Laravel 和 Symfony 服务模式中,在 `worker.interceptors` 下列出拦截器类。它们会按该顺序从框架容器中解析: + +```php +// config/durable-workflow.php +'worker' => [ + 'interceptors' => [App\Durable\AuditInterceptor::class], +], +``` + +```yaml +# config/packages/durable_workflow.yaml +durable_workflow: + worker: + interceptors: + - App\Durable\AuditInterceptor +``` + +嵌入式 Laravel 工作流在 `workflows.v2.interceptors` 下配置自己的拦截器;参见[嵌入式 Worker 拦截器](../configuration/publishing-config.md#worker-interceptors)。完整的拦截器契约见 [PHP SDK 参考](https://github.com/durable-workflow/sdk-php/blob/main/docs/sdk-reference.md#worker-interceptors)。 + ## 含二进制值的查询结果 {#query-binary-results} PHP SDK 3.18.2 修复了包含嵌套 `AvroBinaryValue` 字节的有效 Avro 结果在查询完成时的问题。`result_envelope` 仍是权威表示。SDK 仅在无法编码为 JSON 时省略可选的普通 `result` 投影;普通 JSON 兼容结果保留该投影。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md index 17edcd5ec7a..4612db98f12 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -214,6 +214,92 @@ cargo run --features metrics-prometheus --example metrics_prometheus 使用 OpenTelemetry 指标时,通过现有 meter 实现 recorder:计数器单位为 `1`,直方图单位为秒 `s`,名称和标签严格使用上述值。provider、聚合、资源标签及 exporter 生命周期由应用负责。它与执行 tracing 独立。参见 [recorder API](https://rust.durable-workflow.com/durable_workflow/metrics/trait.MetricsRecorder.html)、[Prometheus API](https://rust.durable-workflow.com/durable_workflow/metrics/struct.PrometheusMetrics.html) 和[发布的指标契约](https://github.com/durable-workflow/sdk-rust/blob/4.7.0/README.md#client-and-worker-metrics)。 +## Worker 拦截器 {#worker-interceptors} + +Worker 拦截器从 Rust SDK 4.25.0 开始提供。它们为 Worker 运行的每个任务统一添加审计日志、指标标签或租户上下文等横切行为。实现 `WorkerInterceptor`,并通过 `Worker::interceptor` 注册,或通过 `Worker::interceptors` 注册多个。每个钩子默认直接传递调用,因此只需实现所需的钩子;`PassthroughWorkerInterceptor` 是不执行任何操作的拦截器。钩子的形式与 [Python](./python.md#worker-interceptors) 和 [PHP](./php.md#worker-interceptors) SDK 拦截器一致。 + +下面的审计拦截器会记录每个工作流任务的结果和每次活动尝试: + +```rust +use durable_workflow::interceptors::{ + ActivityInterceptorContext, ActivityNext, InterceptorFuture, + WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome, +}; +use durable_workflow::{AvroValue, Result, Worker, WorkerInterceptor}; + +struct AuditLog; + +impl WorkerInterceptor for AuditLog { + fn execute_workflow_task<'a>( + &'a self, + context: &'a WorkflowTaskInterceptorContext, + next: WorkflowTaskNext<'a>, + ) -> InterceptorFuture<'a, Result> { + Box::pin(async move { + let outcome = next.run().await; + match &outcome { + // The commands are new for this task even when it replayed + // history first. A retry of a failed task has attempt > 1. + Ok(outcome) => tracing::info!( + workflow_id = context.workflow_id(), + task_id = context.task_id(), + attempt = context.attempt(), + commands = outcome.commands().len(), + "workflow task completed" + ), + Err(error) => tracing::warn!(%error, "workflow task failed"), + } + outcome + }) + } + + fn execute_activity( + &self, + context: ActivityInterceptorContext, + next: ActivityNext, + ) -> InterceptorFuture<'_, Result> { + Box::pin(async move { + let activity_type = context.activity_type().to_owned(); + let attempt = context.attempt(); + let result = next.run(context).await; + tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt"); + result + }) + } +} + +let worker = Worker::new(client, "orders").interceptor(AuditLog); +``` + +仓库中的 [`audit_interceptor` 示例](https://github.com/durable-workflow/sdk-rust/blob/main/examples/audit_interceptor.rs)针对自托管 Server 运行同一个拦截器。 + +| 钩子 | 包裹范围 | 上下文 | `next` | +| --- | --- | --- | --- | +| `execute_workflow_task` | 一个工作流任务,包括重放 | `WorkflowTaskInterceptorContext` | `next.run()` 返回只读的 `WorkflowTaskOutcome` | +| `execute_activity` | 一次活动或本地活动尝试 | `ActivityInterceptorContext` | `next.run(context)` 返回活动结果 | +| `execute_query_task` | 一个查询任务 | `QueryTaskInterceptorContext` | `next.run()` 返回查询结果或 `QueryTaskFailure` | +| `execute_update_validation_task` | 一个更新验证任务 | `UpdateValidationInterceptorContext` | `next.run()` 返回只读的 `UpdateValidationOutcome` | + +上下文是只读的。它们携带 Worker ID、任务队列、命名空间以及任务标识:任务 ID、工作流 ID、运行 ID、工作流或活动类型、尝试次数;对于工作流任务,还包括历史长度、任务的追踪载体和重放状态。活动上下文还提供已解码的参数、该尝试是否为本地活动,以及处理器收到的 `ActivityContext`。更新验证上下文携带验证任务的 ID 和尝试次数、工作流 ID、运行 ID、工作流类型、更新名称以及追踪载体。 + +拦截器按注册顺序运行。最先注册的拦截器位于最外层:它在任务之前最先运行,在任务之后最后运行。每个钩子都必须调用 `next` 继续链;最内层的 `next` 运行 SDK 自身的处理逻辑。任务产生的错误会原样穿过每个拦截器向外传递,除非某个活动或查询拦截器有意处理它。活动拦截器可以通过 `context.with_args(..)` 修改参数并转换结果,活动和查询拦截器也可以不调用 `next` 直接作答。内置的 `ExecutionTelemetry` span 始终位于整个链的最外层。 + +工作流任务拦截器无法改变工作流记录的内容: + +- `next.run()` 不接受输入,因此任务始终按收到的内容运行。 +- Worker 准确提交工作流生成的命令。结果是这些命令的只读视图。 +- 如果任务失败,即使拦截器返回 `Ok`,Worker 也会报告该失败。拦截器看到的是 `Error::WorkflowTaskFailed`,这是一个只读描述,提供 `.kind()`、`.message()` 和 `.debug()`;Worker 保留原始错误。 +- 任务成功后拦截器返回错误,或未运行 `next` 就返回,会使工作流任务以 `Error::WorkflowTaskInterceptor` 失败。不会记录任何内容,Server 会重试该任务。工作流本身不会失败。 +- 拦截器在每个工作流任务上运行。当任务在新的执行之前重新运行了之前任务已提交的命令时,`context.replay_state()` 为 `Replaying`;对于没有已提交历史的任务,则为 `Executing`。Worker 绝不会重新提交重放的命令,因此结果中的命令对该任务而言始终是新的:无论重放状态如何,都应审计每个成功的结果。 +- 如果任务在拦截器观察到它之后失败,其重试可能重复同一个结果;`context.attempt()` 大于 1 表示重试,因此外部审计写入应保持幂等。 + +更新验证拦截器无法改变更新是否被接受: + +- `next.run()` 不接受输入,因此验证器始终按收到的任务运行,Worker 发送验证器自身的批准或拒绝。结果是只读视图:`is_approved()`、`is_rejected()`、`is_worker_failure()`、`reason()` 和 `rejection()`。 +- 拦截器返回错误、未运行 `next` 就返回或失败,或者中途丢弃验证,都会使 Worker 改为报告 `update_validation_worker_failed`。更新不会被接受,调用方使用相同请求 ID 重试时会再次询问验证器。 + +离线 `WorkflowEnvironment` 会运行在其包装的 Worker 上注册的活动拦截器。它没有工作流任务或查询任务,因此这些钩子不会在那里运行。完整的拦截器契约见 [Rust SDK README](https://github.com/durable-workflow/sdk-rust/blob/main/README.md#worker-interceptors)。 + ## Worker 任务并发 {#worker-task-concurrency} 以下有界执行通道需要 Rust SDK **4.3.1 或更高版本**。使用前检查 `Cargo.lock` 中的版本:上方的安装固定版本属于另一组已验证构件,可能选择较旧的 SDK。[已发布包验收](https://github.com/durable-workflow/sdk-rust/issues/107#issuecomment-6360719863)验证了三个配置槽位、释放槽位后第四次回调才被接纳,以及七个完成的工作流,其中包括已处理的活动失败。前述 Server 协议要求仍然适用。 diff --git a/i18n/zh-Hans/source-hashes.json b/i18n/zh-Hans/source-hashes.json index 90559b47a95..caa754f7a02 100644 --- a/i18n/zh-Hans/source-hashes.json +++ b/i18n/zh-Hans/source-hashes.json @@ -11,7 +11,7 @@ "configuration/microservices.md": "7421f8f18b62bc326601e2670ba15ba45fb02056da0d70e94ef89b3870f79cb0", "configuration/options.md": "d5079c5059aaa1072693ac09b3b8ea2be9176279820459370e5ebe6660d9f43b", "configuration/pruning-workflows.md": "6f6ee2be3bd185ffec764e86c3ed3cbd40c45f75d28671b4cd11226493e11afb", - "configuration/publishing-config.md": "c757acd749c0d2696a6e19484249c9298dd15970ce0cf2ae0e6d2dfd82c8b6d6", + "configuration/publishing-config.md": "3c84a87186db1eec8f59d25b81e6018ffabe3afb8ce2bb5011e66fccabb3221d", "constraints/activity-constraints.md": "5a953d0e95e750b6c02d1c72b72199fb3ff4687540cebc56aa3b216cf667bb05", "constraints/constraints-summary.md": "fb48d01502388fc3821eae3790f470ed29cec91545420450f96fc77b84e589f1", "constraints/execution-guarantees.md": "c5c9dbb3be4a10d115f308bd5b591d56a2a91159228808918d5c0edcf4c88a72", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", + "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", + "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2",