diff --git a/docs/constraints/workflow-constraints.md b/docs/constraints/workflow-constraints.md index 963df203341..ccaa5dcce48 100644 --- a/docs/constraints/workflow-constraints.md +++ b/docs/constraints/workflow-constraints.md @@ -15,9 +15,35 @@ Here are some examples of things you shouldn't do inside of a workflow class: ## Logging from workflow code {#workflow-logging} -A worker reconstructs committed workflow history after activations and cold replacement, so ordinary application logging can repeat earlier messages. Use the replay-aware logger documented for your binding when available. Rust service mode provides the [Rust SDK 4.17 workflow logger](../polyglot/rust.md#workflow-logging); other bindings retain their separately documented contracts. +The engine replays a workflow from its history every time it wakes up, so an ordinary log call in workflow code is written again for every completed step. A workflow with 50 steps logs its opening line 50 times. Use the replay-aware logger instead. It writes only when the code runs for the first time. The embedded, PHP SDK and Rust loggers also add the run's identity to each line: -Logging is a process observation. Keep durable workflow commands independent of replay-state observations and log delivery. Even a replay-aware logger can repeat a message from an uncommitted attempt after a crash or retry; it is not an exactly-once outbox. Keep host handlers bounded and nonblocking so logging does not stall the worker. Put durable business effects behind the appropriate activity or recorded workflow operation instead. +- Embedded workflows (Workflow 2.42.0 or later): `$this->logger()` returns a PSR-3 logger that writes through the Laravel logger, or through the channel you pass, as in `$this->logger('workflow')`. Each line carries `workflow_instance_id`, `workflow_run_id`, `workflow_type` and `namespace`. `$this->replayState()` returns `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` or `Unavailable`), and `$this->isReplaying()` is its boolean form. +- PHP SDK: `$context->logger()` writes through the `Worker`'s PSR-3 logger. See the [PHP SDK guide](../polyglot/php.md#workflow-logging). +- Rust SDK: `ctx.logger()`. See the [Rust SDK 4.17 workflow logger](../polyglot/rust.md#workflow-logging). +- Python SDK: `ctx.logger`, which is silent during replay but adds no run identity. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Queries and update validators never log, because they always replay. + +In embedded workflows, the lines are written after the workflow task's database transaction commits, so a task that rolls back writes nothing. Code that parks on a pending `select()` handle without recording a step logs once, in the task that moves past the await. Lines from a live update handler are written when the update is applied. In the PHP SDK, lines are written after the Server accepts the workflow task; see the [PHP SDK guide](../polyglot/php.md#workflow-logging). + +Logging is a process observation. Keep durable workflow commands independent of replay-state observations and log delivery. A replay-aware logger is not an exactly-once outbox: if an embedded or PHP SDK worker dies between the commit or acceptance and the write, those lines are lost, and the Rust logger can repeat a message from an uncommitted attempt after a crash or retry. Keep host handlers bounded and nonblocking so logging does not stall the worker. Put durable business effects behind the appropriate activity or recorded workflow operation instead. ## Boot-Time Guardrails diff --git a/docs/features/updates.md b/docs/features/updates.md index fff289b45cc..00be64e1b1d 100644 --- a/docs/features/updates.md +++ b/docs/features/updates.md @@ -14,6 +14,7 @@ Each accepted update: - Uses the declared durable update name in command history and webhook routing — `#[UpdateMethod('mark-approved')]` keeps the public callable name stable across PHP method renames. - Rejects against historical or already-closed runs rather than silently mutating the current run. - Rejects undeclared method names as `rejected_unknown_update` and contract-invalid arguments as `rejected_invalid_arguments` (with machine-readable `validation_errors`) before the handler runs. +- Rejects a request that your [update validator](#validate-updates-before-acceptance) refuses as `update_validator_rejected` before it is accepted. Like queries, updates replay committed history first. Unlike queries, updates are allowed to mutate replay-safe workflow state and return a value. @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` does not wait for workflow execution. It reloads the stored durable lifecycle and returns the current `UpdateResult`. +## Validate updates before acceptance {#validate-updates-before-acceptance} + +Without a validator, an update that breaks a business rule is accepted and then fails. It is recorded as a failed update, and the caller can't tell a bad request from a failed operation. Declare a validator to refuse the request before it is accepted. Validators require Workflow 2.42.0 or later. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` names the update by its durable name, or by its method name when the update has no alias. The validator takes the same arguments as the update. Before the update is accepted, the engine rebuilds the run's state from its history and calls only the validator: + +- Returning normally lets the update be accepted and applied as usual. +- Throwing, or returning `false`, rejects the update with the reason `update_validator_rejected` and the outcome `rejected_invalid_arguments`. `rejectedByValidator()` is true, `rejectionMessage()` returns the exception message, and `validationErrors()` returns the errors of a Laravel `ValidationException`. `update()` throws a `LogicException` that includes the reason and the validator's message. +- A rejected update is never accepted, its handler never runs and the workflow isn't woken. Like every other rejection, it is recorded only as an `UpdateRejected` audit event, which replay ignores. + +Validators are read-only. They can read the replayed workflow state, but any durable call (an activity, timer, child workflow, signal, side effect, `await`, `getVersion()`, `patched()`, continue-as-new, or memo or search-attribute upsert) throws `UpdateValidatorCommandException` and rejects the update. Changes a validator makes to the replayed state are discarded. A generator validator is rejected, because its body never runs. + +Validators aren't recorded in history and never run during replay, so they don't affect determinism. They see the state from committed history: an update that was accepted but not yet applied isn't visible to them. The replay and the validator run while the update's admission holds the run's locks, so keep validators fast. + +If the state can't be replayed, or the validator hits a database error, `UpdateValidationFailedException` is thrown and nothing is recorded. Webhook update routes answer it with a retryable `503` and `update_validation_failed`. Retry with the same request ID. + +A keyed retry of a rejected update returns the retained rejection without running the validator again. + +Worker interceptors wrap update validation through `executeUpdateValidation()`. They see the validator's decision but can't change it. + ## Recover after an uncertain response {#recover-after-an-uncertain-response} Durable admission, handler completion and an external business effect are diff --git a/docs/polyglot/php.md b/docs/polyglot/php.md index 3b8cb59d03d..a1940c649a0 100644 --- a/docs/polyglot/php.md +++ b/docs/polyglot/php.md @@ -151,6 +151,66 @@ Remote workers register workflow, activity, query, and update handlers through Use the generated [PHP SDK API reference](https://php.durable-workflow.com/api/) for complete parameters and return types. +## Update validators {#update-validators} + +PHP SDK 3.32.0 and later let a workflow refuse an update before it is accepted. Put `#[UpdateValidator]` on a method of the workflow class, next to its `#[Update]` handler. The low-level form is `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, called after `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +The validator takes a `QueryContext` with the run's committed history, followed by the update's arguments. The worker advertises the validator to the Server and polls workflow and update-validation tasks together. Registration is refused with `update_validation_tasks_unavailable` when the Server doesn't advertise synchronous update validation. For each validation task, the worker runs only the validator: + +- Returning normally approves the update, and the Server accepts it. +- Throwing, or returning `false`, rejects it with `update_validator_rejected`, the exception message and class, and any field errors from an `errors()` method on the exception. The update is never accepted and its handler never runs. The Server records the rejection only as an `UpdateRejected` audit event. +- Trying to schedule durable work is refused with `UpdateValidatorCommandRefused`, which rejects the update. + +On the client, `updateWorkflow()` throws `UpdateFailed`. `rejectedByValidator()` identifies a validator rejection and `validationErrors()` returns its field errors. `validationFailed()` is true when the Server couldn't get a decision in time; nothing was accepted, so retry with the same request ID. + +Validators never run during replay. Each validation sees only the history committed before its own task, so two validations running at the same time can both pass a check that only one of them should. A validator worker doesn't use carried workflow polls. Worker interceptors wrap update validation tasks through `executeUpdateValidation()`; they see the validator's decision but can't change it. + +## Replay-aware workflow logging {#workflow-logging} + +The worker replays a workflow from its history on every workflow task, so an ordinary log call in workflow code repeats once for every completed step. PHP SDK 3.32.0 and later provide `$context->logger()`. It returns a PSR-3 logger that writes through the logger you pass to the `Worker` (the named `logger` argument), and only when the code runs past the run's committed history: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Each line carries `namespace`, `workflow_type`, `workflow_id` and `workflow_run_id`. `$context->replayState()` returns `WorkflowReplayState::Replaying`, `Executing` or `Unavailable`, and `isReplaying()` is its boolean form. Use them for diagnostics only; never choose workflow commands from them. + +Lines are written only after the Worker submits the workflow task that ran the code and the Server accepts it. A superseded replay, a speculative replay the Server declines and a refused completion write nothing. Code that parks on a pending child or operation handle without recording a step logs once, in the task that moves past the wait. A `logger()` call inside a side-effect closure writes nothing. + +If the worker dies between the Server's acceptance and the write, those lines are lost. This is a process logger, not an outbox for business effects. Keep log handlers fast and non-blocking: a handler that waits on the network stalls the worker and can cost it the task lease. Logger failures are caught and never change the workflow's commands. + ## Activity retry context and owning run {#activity-retry-context} PHP SDK **3.6.1 or later** exposes `$context->retryInfo`, `$context->workflowId` and `$context->runId` in service-mode activities. Check `$context->retryInfo->isLastConfiguredAttempt() === true` for the final configured attempt of a bounded policy. `attemptNumber` preserves the original received attempt number. diff --git a/docs/polyglot/rust.md b/docs/polyglot/rust.md index 1efe815e4fc..ece6090dd6e 100644 --- a/docs/polyglot/rust.md +++ b/docs/polyglot/rust.md @@ -974,6 +974,47 @@ Workers register named handlers with `Worker::register_update`; use directly. An update is a durable, result-bearing workflow mutation. It is separate from fire-and-forget signals and read-only replayed queries. +### Update validators {#update-validators} + +Rust SDK 4.25.0 and later let a worker refuse an update before it is +accepted. Register a validator with `Worker::register_update_validator`, after +the update handler of the same name: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` takes Avro values. A replayed-state validator, +`register_replayed_update_validator::`, reads a detached copy of the +workflow's replayed state; it must use the same state type as the replayed +workflow. The worker advertises the validator, refuses registration when the +Server doesn't advertise synchronous update validation, and polls workflow and +update-validation tasks together. For each validation task, it runs only the +validator: + +- `Ok(())` approves the update and the Server accepts it. +- An `UpdateRejection` rejects it with `update_validator_rejected`, the + message, type and validation errors. The update is never accepted and its + handler never runs. The Server records the rejection only as an + `UpdateRejected` audit event. +- A validator that adds a workflow command is refused with + `UpdateValidatorCommandRefused`, and a panic or replay failure reports + `update_validation_worker_failed`. + +On the client, `Error::update_validator_rejection()` returns the rejection's +message, validation errors and IDs, and `Error::is_update_validation_failed()` +covers timeouts and worker failures. An ordinary failed update matches neither. +Validators never run during replay. Worker interceptors wrap update validation +tasks through `execute_update_validation_task`; they see the validator's decision +but can't change it. + ## Payload envelope Workflow input, signals, activities, queries, and results use the published diff --git a/i18n/de/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md b/i18n/de/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index 95a50da4b97..68176635786 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -15,9 +15,35 @@ Beispiele für Operationen, die nicht in den Workflow-Code gehören: ## Logging aus Workflow-Code {#workflow-logging} -Ein Worker rekonstruiert nach Aktivierungen und kaltem Austausch den persistierten Workflow-Verlauf. Gewöhnliches Anwendungslogging kann deshalb frühere Meldungen wiederholen. Verwenden Sie den für Ihr Binding dokumentierten replay-bewussten Logger, sofern verfügbar. Rust Service Mode bietet den [Workflow-Logger des Rust SDK 4.17](../polyglot/rust.md#workflow-logging); andere Bindings behalten ihre gesondert dokumentierten Verträge. +Die Engine spielt einen Workflow bei jedem Aufwachen aus seinem Verlauf erneut ab, daher wird ein gewöhnlicher Log-Aufruf im Workflow-Code für jeden abgeschlossenen Schritt erneut geschrieben. Ein Workflow mit 50 Schritten protokolliert seine erste Zeile 50-mal. Verwenden Sie stattdessen den replay-bewussten Logger. Er schreibt nur, wenn der Code zum ersten Mal ausgeführt wird. Die Logger für eingebettete Workflows, das PHP SDK und Rust ergänzen jede Zeile zusätzlich um die Identität des Laufs: -Logging ist eine Prozessbeobachtung. Halten Sie dauerhafte Workflow-Befehle unabhängig von Replay-Zustand und Log-Zustellung. Auch ein replay-bewusster Logger kann eine Meldung aus einem nicht persistierten Versuch nach Absturz oder Retry wiederholen; er ist keine Outbox mit Exactly-once-Garantie. Host-Handler müssen begrenzt und nicht blockierend bleiben, damit Logging den Worker nicht aufhält. Dauerhafte Geschäftseffekte gehören stattdessen in eine passende Activity oder aufgezeichnete Workflow-Operation. +- Eingebettete Workflows (Workflow 2.42.0 oder neuer): `$this->logger()` liefert einen PSR-3-Logger, der über den Laravel-Logger oder über den übergebenen Kanal schreibt, etwa `$this->logger('workflow')`. Jede Zeile enthält `workflow_instance_id`, `workflow_run_id`, `workflow_type` und `namespace`. `$this->replayState()` liefert `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` oder `Unavailable`), und `$this->isReplaying()` ist die boolesche Form. +- PHP SDK: `$context->logger()` schreibt über den PSR-3-Logger des `Worker`. Siehe den [PHP-SDK-Leitfaden](../polyglot/php.md#workflow-logging). +- Rust SDK: `ctx.logger()`. Siehe den [Workflow-Logger des Rust SDK 4.17](../polyglot/rust.md#workflow-logging). +- Python SDK: `ctx.logger`, der während eines Replays schweigt, aber keine Identität des Laufs ergänzt. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Abfragen und Update-Validatoren protokollieren nie, weil sie immer ein Replay sind. + +In eingebetteten Workflows werden die Zeilen geschrieben, nachdem die Datenbanktransaktion des Workflow-Tasks committet wurde; ein Task, der zurückgerollt wird, schreibt also nichts. Code, der auf einem ausstehenden `select()`-Handle wartet, ohne einen Schritt aufzuzeichnen, protokolliert einmal, und zwar in dem Task, der über das Warten hinauskommt. Zeilen aus einem live ausgeführten Update-Handler werden geschrieben, wenn das Update angewendet wird. Im PHP SDK werden die Zeilen geschrieben, nachdem der Server den Workflow-Task angenommen hat; siehe den [PHP-SDK-Leitfaden](../polyglot/php.md#workflow-logging). + +Logging ist eine Prozessbeobachtung. Halten Sie dauerhafte Workflow-Befehle unabhängig von Replay-Zustandsbeobachtungen und der Log-Zustellung. Ein replay-bewusster Logger ist kein Exactly-once-Outbox: Stirbt ein eingebetteter Worker oder ein Worker des PHP SDK zwischen dem Commit bzw. der Annahme und dem Schreiben, gehen diese Zeilen verloren, und der Rust-Logger kann eine Meldung aus einem nicht committeten Versuch nach einem Absturz oder Retry wiederholen. Halten Sie Host-Handler begrenzt und nicht blockierend, damit Logging den Worker nicht aufhält. Legen Sie dauerhafte Geschäftseffekte stattdessen in die passende Aktivität oder aufgezeichnete Workflow-Operation. ## Prüfungen beim Anwendungsstart {#boot-time-guardrails} diff --git a/i18n/de/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/de/docusaurus-plugin-content-docs/current/features/updates.md index 05f4353adaa..d678228720c 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/features/updates.md @@ -16,6 +16,7 @@ Jedes angenommene Update: - verwendet den deklarierten dauerhaften Updatenamen in Befehlshistorie und Webhook-Routing. `#[UpdateMethod('mark-approved')]` hält den öffentlichen aufrufbaren Namen über PHP-Methodenumbenennungen hinweg stabil; - wird für historische oder bereits geschlossene Läufe abgelehnt, statt still den aktuellen Lauf zu verändern; - lehnt nicht deklarierte Methodennamen als `rejected_unknown_update` und vertragswidrige Argumente als `rejected_invalid_arguments` (mit maschinenlesbaren `validation_errors`) vor Ausführung des Handlers ab. +- lehnt eine Anfrage, die Ihr [Update-Validator](#validate-updates-before-acceptance) ablehnt, vor der Annahme als `update_validator_rejected` ab. Wie Abfragen spielen Updates zuerst festgeschriebene Historie erneut ab. Anders als Abfragen dürfen sie Replay-sicheren Workflow-Zustand ändern und @@ -132,6 +133,53 @@ $latest->closedAt(); // null until the lifecycle closes gespeicherten dauerhaften Lebenszyklus neu und gibt das aktuelle `UpdateResult` zurück. +## Updates vor der Annahme validieren {#validate-updates-before-acceptance} + +Ohne Validator wird ein Update, das gegen eine Geschäftsregel verstößt, zuerst angenommen und schlägt dann fehl. Es wird als fehlgeschlagenes Update aufgezeichnet, und der Aufrufer kann eine fehlerhafte Anfrage nicht von einer fehlgeschlagenen Operation unterscheiden. Deklarieren Sie einen Validator, um die Anfrage vor der Annahme abzulehnen. Validatoren erfordern Workflow 2.42.0 oder neuer. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` benennt das Update über seinen dauerhaften Namen oder, wenn das Update keinen Alias hat, über seinen Methodennamen. Der Validator erhält dieselben Argumente wie das Update. Bevor das Update angenommen wird, rekonstruiert die Engine den Zustand des Laufs aus seinem Verlauf und ruft nur den Validator auf: + +- Kehrt er normal zurück, wird das Update wie gewohnt angenommen und angewendet. +- Wirft er eine Exception oder gibt `false` zurück, wird das Update mit dem Grund `update_validator_rejected` und dem Ergebnis `rejected_invalid_arguments` abgelehnt. `rejectedByValidator()` ist dann wahr, `rejectionMessage()` liefert die Exception-Meldung, und `validationErrors()` liefert die Fehler einer Laravel-`ValidationException`. `update()` wirft eine `LogicException`, die den Grund und die Meldung des Validators enthält. +- Ein abgelehntes Update wird nie angenommen, sein Handler läuft nie, und der Workflow wird nicht geweckt. Wie jede andere Ablehnung wird es nur als Audit-Ereignis `UpdateRejected` aufgezeichnet, das der Replay ignoriert. + +Validatoren sind schreibgeschützt. Sie können den wiederhergestellten Workflow-Zustand lesen, aber jeder dauerhafte Aufruf (eine Aktivität, ein Timer, ein Child-Workflow, ein Signal, ein Side Effect, `await`, `getVersion()`, `patched()`, Continue-as-New oder ein Upsert von Memo oder Suchattributen) wirft `UpdateValidatorCommandException` und lehnt das Update ab. Änderungen, die ein Validator am wiederhergestellten Zustand vornimmt, werden verworfen. Ein Generator-Validator wird abgelehnt, weil sein Rumpf nie ausgeführt wird. + +Validatoren werden nicht im Verlauf aufgezeichnet und laufen nie während eines Replays, daher beeinflussen sie den Determinismus nicht. Sie sehen den Zustand aus dem persistierten Verlauf: Ein Update, das angenommen, aber noch nicht angewendet wurde, ist für sie nicht sichtbar. Replay und Validator laufen, während die Annahme des Updates die Sperren des Laufs hält; halten Sie Validatoren deshalb schnell. + +Kann der Zustand nicht wiederhergestellt werden oder trifft der Validator auf einen Datenbankfehler, wird `UpdateValidationFailedException` geworfen, und nichts wird aufgezeichnet. Webhook-Routen für Updates beantworten das mit einem wiederholbaren `503` und `update_validation_failed`. Wiederholen Sie die Anfrage mit derselben Request-ID. + +Eine Wiederholung eines abgelehnten Updates mit demselben Schlüssel liefert die gespeicherte Ablehnung, ohne den Validator erneut auszuführen. + +Worker-Interceptors umschließen die Update-Validierung über `executeUpdateValidation()`. Sie sehen die Entscheidung des Validators, können sie aber nicht ändern. + ## Nach einer ungewissen Antwort wiederherstellen {#recover-after-an-uncertain-response} Dauerhafte Annahme, Handler-Abschluss und ein externer Geschäftseffekt sind 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 b4fbf71cfd8..2c7859032e6 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -154,6 +154,66 @@ Entfernte Worker registrieren Workflow-, Aktivitäts-, Abfrage- und Update-Handl Vollständige Parameter und Rückgabetypen stehen in der generierten [PHP-SDK-API-Referenz](https://php.durable-workflow.com/api/). +## Update-Validatoren {#update-validators} + +Ab PHP SDK 3.32.0 kann ein Workflow ein Update ablehnen, bevor es angenommen wird. Setzen Sie `#[UpdateValidator]` auf eine Methode der Workflow-Klasse, neben ihren `#[Update]`-Handler. Die Low-Level-Form ist `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, aufgerufen nach `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +Der Validator erhält einen `QueryContext` mit dem persistierten Verlauf des Laufs, gefolgt von den Argumenten des Updates. Der Worker meldet den Validator beim Server an und fragt Workflow- und Update-Validierungs-Tasks gemeinsam ab. Die Registrierung wird mit `update_validation_tasks_unavailable` abgelehnt, wenn der Server keine synchrone Update-Validierung anbietet. Für jeden Validierungs-Task führt der Worker nur den Validator aus: + +- Kehrt er normal zurück, genehmigt er das Update, und der Server nimmt es an. +- Wirft er eine Exception oder gibt `false` zurück, wird das Update mit `update_validator_rejected`, der Exception-Meldung und -Klasse sowie etwaigen Feldfehlern aus einer `errors()`-Methode der Exception abgelehnt. Das Update wird nie angenommen, und sein Handler läuft nie. Der Server zeichnet die Ablehnung nur als Audit-Ereignis `UpdateRejected` auf. +- Der Versuch, dauerhafte Arbeit einzuplanen, wird mit `UpdateValidatorCommandRefused` verweigert und lehnt das Update ab. + +Auf dem Client wirft `updateWorkflow()` eine `UpdateFailed`. `rejectedByValidator()` erkennt eine Validator-Ablehnung, und `validationErrors()` liefert ihre Feldfehler. `validationFailed()` ist wahr, wenn der Server nicht rechtzeitig eine Entscheidung erhalten konnte; es wurde nichts angenommen, also wiederholen Sie mit derselben Request-ID. + +Validatoren laufen nie während eines Replays. Jede Validierung sieht nur den Verlauf, der vor ihrem eigenen Task persistiert wurde, daher können zwei gleichzeitige Validierungen beide eine Prüfung bestehen, die nur eine von ihnen bestehen sollte. Ein Worker mit Validatoren verwendet keine mitgeführten Workflow-Polls. Worker-Interceptors umschließen Update-Validierungs-Tasks über `executeUpdateValidation()`; sie sehen die Entscheidung des Validators, können sie aber nicht ändern. + +## Replay-bewusstes Workflow-Logging {#workflow-logging} + +Der Worker spielt einen Workflow bei jedem Workflow-Task aus seinem Verlauf erneut ab, daher wiederholt sich ein gewöhnlicher Log-Aufruf im Workflow-Code für jeden abgeschlossenen Schritt. Ab PHP SDK 3.32.0 gibt es `$context->logger()`. Es liefert einen PSR-3-Logger, der über den Logger schreibt, den Sie dem `Worker` übergeben (das benannte Argument `logger`), und zwar nur, wenn der Code über den persistierten Verlauf des Laufs hinaus ausgeführt wird: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Jede Zeile enthält `namespace`, `workflow_type`, `workflow_id` und `workflow_run_id`. `$context->replayState()` liefert `WorkflowReplayState::Replaying`, `Executing` oder `Unavailable`, und `isReplaying()` ist die boolesche Form. Verwenden Sie sie nur zur Diagnose; wählen Sie Workflow-Befehle nie danach aus. + +Zeilen werden erst geschrieben, nachdem der Worker den Workflow-Task, der den Code ausgeführt hat, übermittelt und der Server ihn angenommen hat. Ein überholtes Replay, ein spekulatives Replay, das der Server ablehnt, und ein verweigerter Abschluss schreiben nichts. Code, der auf einem ausstehenden Child- oder Operations-Handle wartet, ohne einen Schritt aufzuzeichnen, protokolliert einmal, und zwar in dem Task, der über das Warten hinauskommt. Ein `logger()`-Aufruf innerhalb einer Side-Effect-Closure schreibt nichts. + +Stirbt der Worker zwischen der Annahme durch den Server und dem Schreiben, gehen diese Zeilen verloren. Dies ist ein Prozess-Logger, kein Outbox für Geschäftseffekte. Halten Sie Log-Handler schnell und nicht blockierend: Ein Handler, der auf das Netzwerk wartet, blockiert den Worker und kann ihn die Task-Lease kosten. Fehler des Loggers werden abgefangen und ändern nie die Befehle des Workflows. + ## Wiederholungskontext und zugehöriger Lauf einer Aktivität {#activity-retry-context} Das PHP SDK **ab 3.6.1** stellt `$context->retryInfo`, `$context->workflowId` und `$context->runId` in Aktivitäten im Service-Modus bereit. Mit `$context->retryInfo->isLastConfiguredAttempt() === true` erkennen Sie den letzten konfigurierten Versuch einer begrenzten Richtlinie. `attemptNumber` bewahrt die ursprünglich empfangene Versuchsnummer. 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 2f2ce338c0e..b69acc1bbff 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -976,6 +976,49 @@ Worker registrieren benannte Handler mit `Worker::register_update`. liefern. Ein Update ist eine dauerhafte Workflow-Änderung mit Ergebnis, getrennt von Fire-and-forget-Signalen und schreibgeschützten Abfragen mit Replay. +### Update-Validatoren {#update-validators} + +Ab Rust SDK 4.25.0 kann ein Worker ein Update ablehnen, bevor es angenommen +wird. Registrieren Sie einen Validator mit `Worker::register_update_validator` +nach dem gleichnamigen Update-Handler: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` nimmt Avro-Werte entgegen. Ein Validator +mit wiederhergestelltem Zustand, `register_replayed_update_validator::`, liest +eine abgetrennte Kopie des wiederhergestellten Workflow-Zustands; er muss +denselben Zustandstyp wie der wiederhergestellte Workflow verwenden. Der Worker +meldet den Validator an, lehnt die Registrierung ab, wenn der Server keine +synchrone Update-Validierung anbietet, und fragt Workflow- und +Update-Validierungs-Tasks gemeinsam ab. Für jeden Validierungs-Task führt er nur +den Validator aus: + +- `Ok(())` genehmigt das Update, und der Server nimmt es an. +- Eine `UpdateRejection` lehnt es mit `update_validator_rejected`, der Meldung, + dem Typ und den Validierungsfehlern ab. Das Update wird nie angenommen, und + sein Handler läuft nie. Der Server zeichnet die Ablehnung nur als + Audit-Ereignis `UpdateRejected` auf. +- Ein Validator, der einen Workflow-Befehl hinzufügt, wird mit + `UpdateValidatorCommandRefused` verweigert; eine Panic oder ein fehlgeschlagenes + Replay meldet `update_validation_worker_failed`. + +Auf dem Client liefert `Error::update_validator_rejection()` die Meldung, die +Validierungsfehler und die IDs der Ablehnung, und +`Error::is_update_validation_failed()` deckt Timeouts und Worker-Fehler ab. Ein +gewöhnlich fehlgeschlagenes Update erfüllt keines von beiden. Validatoren laufen +nie während eines Replays. Worker-Interceptors umschließen Update-Validierungs-Tasks +über `execute_update_validation_task`; sie sehen die Entscheidung des Validators, +können sie aber nicht ändern. + ## Nutzlast-Envelope {#payload-envelope} Workflow-Eingaben, Signale, Aktivitäten, Abfragen und Ergebnisse verwenden den diff --git a/i18n/de/source-hashes.json b/i18n/de/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/de/source-hashes.json +++ b/i18n/de/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/es/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index 1f58304af81..c7bca508759 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -26,9 +26,35 @@ Ten en cuenta estas reglas al escribir un workflow: ## Logging desde el código del workflow {#workflow-logging} -Un worker reconstruye el historial confirmado del workflow tras activaciones y reemplazos en frío, por lo que el logging normal de la aplicación puede repetir mensajes anteriores. Use el logger consciente del replay documentado para su binding cuando esté disponible. El modo servicio Rust ofrece el [logger de workflow de Rust SDK 4.17](../polyglot/rust.md#workflow-logging); los demás bindings conservan sus contratos documentados por separado. +El motor reproduce un workflow a partir de su historial cada vez que se despierta, así que una llamada de log ordinaria en el código del workflow se vuelve a escribir por cada paso completado. Un workflow con 50 pasos registra su primera línea 50 veces. Usa en su lugar el logger consciente de la reproducción. Solo escribe cuando el código se ejecuta por primera vez. Los loggers de los workflows embebidos, del PHP SDK y de Rust también añaden la identidad de la ejecución a cada línea: -El logging es una observación del proceso. Mantenga los comandos durables del workflow independientes de las observaciones de replay y de la entrega de logs. Incluso un logger consciente del replay puede repetir un mensaje de un intento no confirmado tras un fallo o retry; no es un outbox exactamente una vez. Los handlers del host deben estar acotados y no bloquear para no detener al worker. Sitúe los efectos de negocio durables en la actividad u operación de workflow registrada adecuada. +- Workflows embebidos (Workflow 2.42.0 o posterior): `$this->logger()` devuelve un logger PSR-3 que escribe a través del logger de Laravel, o del canal que indiques, como en `$this->logger('workflow')`. Cada línea incluye `workflow_instance_id`, `workflow_run_id`, `workflow_type` y `namespace`. `$this->replayState()` devuelve `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` o `Unavailable`), y `$this->isReplaying()` es su forma booleana. +- PHP SDK: `$context->logger()` escribe a través del logger PSR-3 del `Worker`. Consulta la [guía del PHP SDK](../polyglot/php.md#workflow-logging). +- Rust SDK: `ctx.logger()`. Consulta el [logger de workflow del Rust SDK 4.17](../polyglot/rust.md#workflow-logging). +- Python SDK: `ctx.logger`, que guarda silencio durante la reproducción pero no añade la identidad de la ejecución. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Las consultas y los validadores de actualización nunca registran logs, porque siempre son una reproducción. + +En los workflows embebidos, las líneas se escriben después de que se confirme la transacción de base de datos de la tarea de workflow, así que una tarea que se revierte no escribe nada. El código que espera en un handle `select()` pendiente sin registrar un paso registra una sola vez, en la tarea que supera la espera. Las líneas de un handler de actualización en vivo se escriben cuando se aplica la actualización. En el PHP SDK, las líneas se escriben después de que el Server acepta la tarea de workflow; consulta la [guía del PHP SDK](../polyglot/php.md#workflow-logging). + +El logging es una observación del proceso. Mantén los comandos durables del workflow independientes de las observaciones del estado de reproducción y de la entrega de logs. Un logger consciente de la reproducción no es un outbox exactly-once: si un worker embebido o del PHP SDK muere entre la confirmación o la aceptación y la escritura, esas líneas se pierden, y el logger de Rust puede repetir un mensaje de un intento no confirmado tras una caída o un reintento. Mantén los handlers del host acotados y no bloqueantes para que el logging no detenga el worker. Coloca los efectos de negocio durables en la actividad adecuada o en una operación de workflow registrada. ## Comprobaciones al iniciar la aplicación {#boot-time-guardrails} diff --git a/i18n/es/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/es/docusaurus-plugin-content-docs/current/features/updates.md index 1f87e19a94d..75f973801f8 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ Cada actualización aceptada: - Usa el nombre duradero declarado en el historial y en las rutas webhook. `#[UpdateMethod('mark-approved')]` mantiene estable el nombre público aunque cambie el método PHP. - Se rechaza para ejecuciones históricas o cerradas, sin modificar silenciosamente la actual. - Rechaza nombres no declarados con `rejected_unknown_update` y argumentos contrarios al contrato con `rejected_invalid_arguments` y `validation_errors` legibles por máquinas antes de ejecutar el manejador. +- Rechaza como `update_validator_rejected`, antes de aceptarla, una solicitud que tu [validador de actualización](#validate-updates-before-acceptance) rechaza. Como las consultas, primero reproduce historial confirmado. A diferencia de ellas, puede modificar estado seguro para la reproducción y devolver un valor. @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` no espera a la ejecución. Recarga el ciclo duradero y devuelve el `UpdateResult` actual. +## Validar actualizaciones antes de aceptarlas {#validate-updates-before-acceptance} + +Sin un validador, una actualización que incumple una regla de negocio se acepta y después falla. Queda registrada como una actualización fallida, y quien llama no puede distinguir una solicitud incorrecta de una operación fallida. Declara un validador para rechazar la solicitud antes de que se acepte. Los validadores requieren Workflow 2.42.0 o posterior. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` identifica la actualización por su nombre durable, o por el nombre de su método cuando la actualización no tiene alias. El validador recibe los mismos argumentos que la actualización. Antes de aceptar la actualización, el motor reconstruye el estado de la ejecución a partir de su historial y llama solo al validador: + +- Si retorna con normalidad, la actualización se acepta y se aplica como de costumbre. +- Si lanza una excepción o devuelve `false`, la actualización se rechaza con el motivo `update_validator_rejected` y el resultado `rejected_invalid_arguments`. `rejectedByValidator()` es verdadero, `rejectionMessage()` devuelve el mensaje de la excepción y `validationErrors()` devuelve los errores de una `ValidationException` de Laravel. `update()` lanza una `LogicException` que incluye el motivo y el mensaje del validador. +- Una actualización rechazada nunca se acepta, su handler nunca se ejecuta y el workflow no se despierta. Como cualquier otro rechazo, solo se registra como un evento de auditoría `UpdateRejected`, que la reproducción ignora. + +Los validadores son de solo lectura. Pueden leer el estado reconstruido del workflow, pero cualquier llamada durable (una actividad, un temporizador, un workflow hijo, una señal, un side effect, `await`, `getVersion()`, `patched()`, continue-as-new o un upsert de memo o de atributos de búsqueda) lanza `UpdateValidatorCommandException` y rechaza la actualización. Los cambios que un validador hace en el estado reconstruido se descartan. Un validador generador se rechaza, porque su cuerpo nunca se ejecuta. + +Los validadores no se registran en el historial y nunca se ejecutan durante la reproducción, así que no afectan al determinismo. Ven el estado del historial confirmado: una actualización aceptada pero aún no aplicada no es visible para ellos. La reproducción y el validador se ejecutan mientras la admisión de la actualización mantiene los bloqueos de la ejecución, así que mantén los validadores rápidos. + +Si el estado no puede reconstruirse, o el validador encuentra un error de base de datos, se lanza `UpdateValidationFailedException` y no se registra nada. Las rutas de webhook de actualización responden con un `503` reintentable y `update_validation_failed`. Reintenta con el mismo ID de solicitud. + +Un reintento con clave de una actualización rechazada devuelve el rechazo conservado sin volver a ejecutar el validador. + +Los interceptores del worker envuelven la validación de actualizaciones mediante `executeUpdateValidation()`. Ven la decisión del validador, pero no pueden cambiarla. + ## Recuperarse tras una respuesta incierta {#recover-after-an-uncertain-response} La admisión duradera, la finalización del manejador y un efecto de negocio externo son hechos separados. El plazo de quien llama puede vencer mientras una actualización aceptada sigue ejecutándose, y una respuesta perdida puede ocultar un resultado ya confirmado. Un rechazo posterior a enviar otra actualización no aclara el resultado original. 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 102389b7b11..d42eacfd353 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -152,6 +152,66 @@ actualización mediante `registerWorkflow`, `registerActivity`, `registerQuery` y `registerUpdate`. Consulta la [referencia generada del SDK de PHP](https://php.durable-workflow.com/api/) para los parámetros y tipos de retorno completos. +## Validadores de actualización {#update-validators} + +PHP SDK 3.32.0 y posteriores permiten que un workflow rechace una actualización antes de aceptarla. Pon `#[UpdateValidator]` en un método de la clase del workflow, junto a su handler `#[Update]`. La forma de bajo nivel es `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, llamada después de `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +El validador recibe un `QueryContext` con el historial confirmado de la ejecución, seguido de los argumentos de la actualización. El worker anuncia el validador al Server y consulta juntas las tareas de workflow y de validación de actualizaciones. El registro se rechaza con `update_validation_tasks_unavailable` cuando el Server no anuncia la validación síncrona de actualizaciones. Para cada tarea de validación, el worker ejecuta solo el validador: + +- Si retorna con normalidad, aprueba la actualización y el Server la acepta. +- Si lanza una excepción o devuelve `false`, la rechaza con `update_validator_rejected`, el mensaje y la clase de la excepción, y los errores de campo de un método `errors()` de la excepción. La actualización nunca se acepta y su handler nunca se ejecuta. El Server registra el rechazo solo como un evento de auditoría `UpdateRejected`. +- Intentar programar trabajo durable se rechaza con `UpdateValidatorCommandRefused`, lo que rechaza la actualización. + +En el cliente, `updateWorkflow()` lanza `UpdateFailed`. `rejectedByValidator()` identifica un rechazo del validador y `validationErrors()` devuelve sus errores de campo. `validationFailed()` es verdadero cuando el Server no pudo obtener una decisión a tiempo; no se aceptó nada, así que reintenta con el mismo ID de solicitud. + +Los validadores nunca se ejecutan durante la reproducción. Cada validación solo ve el historial confirmado antes de su propia tarea, así que dos validaciones simultáneas pueden superar ambas una comprobación que solo una debería superar. Un worker con validadores no usa sondeos de workflow arrastrados. Los interceptores del worker envuelven las tareas de validación de actualizaciones mediante `executeUpdateValidation()`; ven la decisión del validador, pero no pueden cambiarla. + +## Logging de workflow consciente de la reproducción {#workflow-logging} + +El worker reproduce un workflow a partir de su historial en cada tarea de workflow, así que una llamada de log ordinaria en el código del workflow se repite una vez por cada paso completado. PHP SDK 3.32.0 y posteriores ofrecen `$context->logger()`. Devuelve un logger PSR-3 que escribe a través del logger que pasas al `Worker` (el argumento con nombre `logger`), y solo cuando el código se ejecuta más allá del historial confirmado de la ejecución: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Cada línea incluye `namespace`, `workflow_type`, `workflow_id` y `workflow_run_id`. `$context->replayState()` devuelve `WorkflowReplayState::Replaying`, `Executing` o `Unavailable`, e `isReplaying()` es su forma booleana. Úsalos solo para diagnóstico; nunca elijas comandos de workflow a partir de ellos. + +Las líneas se escriben solo después de que el Worker envía la tarea de workflow que ejecutó el código y el Server la acepta. Una reproducción sustituida, una reproducción especulativa que el Server declina y una finalización rechazada no escriben nada. El código que espera en un handle pendiente de un hijo o de una operación sin registrar un paso registra una sola vez, en la tarea que supera la espera. Una llamada a `logger()` dentro de un closure de side effect no escribe nada. + +Si el worker muere entre la aceptación del Server y la escritura, esas líneas se pierden. Es un logger de proceso, no un outbox para efectos de negocio. Mantén los handlers de log rápidos y no bloqueantes: un handler que espera a la red bloquea el worker y puede costarle el lease de la tarea. Los fallos del logger se capturan y nunca cambian los comandos del workflow. + ## Contexto de reintentos y ejecución propietaria de una actividad {#activity-retry-context} El SDK de PHP **3.6.1 o posterior** expone `$context->retryInfo`, `$context->workflowId` y `$context->runId` en las actividades en modo servicio. Compruebe `$context->retryInfo->isLastConfiguredAttempt() === true` para detectar el último intento configurado de una política limitada. `attemptNumber` conserva el número de intento recibido originalmente. 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 3ce18b048bd..57413a420f6 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -770,6 +770,48 @@ Rust admite actualizaciones duraderas en las funciones de cliente de aplicación Los workers registran manejadores con nombre mediante `Worker::register_update`; utiliza `register_update_avro_value` si el manejador consume y devuelve valores Avro directamente. Una actualización modifica el workflow de forma duradera y devuelve un resultado. Es distinta de las señales sin espera y las consultas de solo lectura mediante reproducción. +### Validadores de actualización {#update-validators} + +Rust SDK 4.25.0 y posteriores permiten que un worker rechace una actualización +antes de aceptarla. Registra un validador con `Worker::register_update_validator`, +después del handler de actualización con el mismo nombre: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` recibe valores Avro. Un validador de estado +reproducido, `register_replayed_update_validator::`, lee una copia separada +del estado reproducido del workflow; debe usar el mismo tipo de estado que el +workflow reproducido. El worker anuncia el validador, rechaza el registro cuando +el Server no anuncia la validación síncrona de actualizaciones y consulta juntas +las tareas de workflow y de validación de actualizaciones. Para cada tarea de +validación, ejecuta solo el validador: + +- `Ok(())` aprueba la actualización y el Server la acepta. +- Un `UpdateRejection` la rechaza con `update_validator_rejected`, el mensaje, + el tipo y los errores de validación. La actualización nunca se acepta y su + handler nunca se ejecuta. El Server registra el rechazo solo como un evento de + auditoría `UpdateRejected`. +- Un validador que añade un comando de workflow se rechaza con + `UpdateValidatorCommandRefused`, y un panic o un fallo de reproducción informa + `update_validation_worker_failed`. + +En el cliente, `Error::update_validator_rejection()` devuelve el mensaje, los +errores de validación y los IDs del rechazo, y `Error::is_update_validation_failed()` +cubre los tiempos de espera agotados y los fallos del worker. Una actualización +fallida ordinaria no coincide con ninguno. Los validadores nunca se ejecutan +durante la reproducción. Los interceptores del worker envuelven las tareas de +validación de actualizaciones mediante `execute_update_validation_task`; ven la +decisión del validador, pero no pueden cambiarla. + ## Sobre de cargas útiles {#payload-envelope} Las entradas de workflow, señales, actividades, consultas y resultados utilizan el contrato publicado `PayloadEnvelope`: un `codec` y un `blob` codificado. La ruta predeterminada `avro` del SDK utiliza su dependencia declarada `apache-avro` y el esquema Value fijo y versionado de la plataforma; no construyas el blob manualmente ni sustituyas el sobre por un registro específico de implementación. diff --git a/i18n/es/source-hashes.json b/i18n/es/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/es/source-hashes.json +++ b/i18n/es/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/fr/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index 5a56762ec25..68b562b56d9 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -17,9 +17,35 @@ Dans le corps d’un workflow : ## Journaliser depuis le code de workflow {#workflow-logging} -Un worker reconstruit l’historique validé du workflow après les activations et remplacements à froid ; la journalisation ordinaire de l’application peut donc répéter les messages précédents. Utilisez le logger conscient du replay documenté pour votre binding lorsqu’il existe. Le mode service Rust fournit le [logger de workflow de Rust SDK 4.17](../polyglot/rust.md#workflow-logging) ; les autres bindings conservent leurs contrats documentés séparément. +Le moteur relit un workflow à partir de son historique à chaque réveil ; un appel de journalisation ordinaire dans le code du workflow est donc réécrit pour chaque étape terminée. Un workflow de 50 étapes journalise sa première ligne 50 fois. Utilisez plutôt le logger conscient de la relecture. Il n’écrit que lorsque le code s’exécute pour la première fois. Les loggers des workflows embarqués, du PHP SDK et de Rust ajoutent en outre l’identité de l’exécution à chaque ligne : -La journalisation est une observation du processus. Gardez les commandes durables indépendantes des observations du replay et de la livraison des logs. Même un logger conscient du replay peut répéter un message d’une tentative non validée après un crash ou un retry ; ce n’est pas une outbox garantissant exactement une fois. Les handlers hôtes doivent rester bornés et non bloquants pour ne pas immobiliser le worker. Placez les effets métier durables dans l’activité ou l’opération de workflow enregistrée appropriée. +- Workflows embarqués (Workflow 2.42.0 ou ultérieur) : `$this->logger()` retourne un logger PSR-3 qui écrit via le logger Laravel, ou via le canal que vous passez, comme dans `$this->logger('workflow')`. Chaque ligne contient `workflow_instance_id`, `workflow_run_id`, `workflow_type` et `namespace`. `$this->replayState()` retourne `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` ou `Unavailable`), et `$this->isReplaying()` en est la forme booléenne. +- PHP SDK : `$context->logger()` écrit via le logger PSR-3 du `Worker`. Voir le [guide du PHP SDK](../polyglot/php.md#workflow-logging). +- Rust SDK : `ctx.logger()`. Voir le [logger de workflow du Rust SDK 4.17](../polyglot/rust.md#workflow-logging). +- Python SDK : `ctx.logger`, silencieux pendant la relecture mais sans identité d’exécution. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Les requêtes de lecture et les validateurs de mise à jour ne journalisent jamais, car ils sont toujours une relecture. + +Dans les workflows embarqués, les lignes sont écrites après la validation de la transaction de base de données de la tâche de workflow ; une tâche annulée n’écrit donc rien. Le code qui attend sur un handle `select()` en suspens sans enregistrer d’étape journalise une seule fois, dans la tâche qui dépasse l’attente. Les lignes d’un handler de mise à jour exécuté en direct sont écrites lorsque la mise à jour est appliquée. Dans le PHP SDK, les lignes sont écrites après que le Server a accepté la tâche de workflow ; voir le [guide du PHP SDK](../polyglot/php.md#workflow-logging). + +La journalisation est une observation du processus. Gardez les commandes durables du workflow indépendantes des observations de l’état de relecture et de la livraison des journaux. Un logger conscient de la relecture n’est pas une outbox exactly-once : si un worker embarqué ou du PHP SDK meurt entre la validation ou l’acceptation et l’écriture, ces lignes sont perdues, et le logger Rust peut répéter un message issu d’une tentative non validée après un plantage ou une nouvelle tentative. Gardez les handlers de l’hôte bornés et non bloquants pour que la journalisation ne bloque pas le worker. Placez plutôt les effets métier durables dans l’activité appropriée ou une opération de workflow enregistrée. ## Contrôles au démarrage {#boot-time-guardrails} diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/fr/docusaurus-plugin-content-docs/current/features/updates.md index 6c31bfbc4ba..598da1a6d2e 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ Chaque mise à jour acceptée : - Utilise le nom durable déclaré dans l’historique des commandes et le routage webhook. `#[UpdateMethod('mark-approved')]` conserve un nom public stable malgré les renommages de méthodes PHP. - Est rejetée pour une exécution historique ou déjà clôturée au lieu de modifier silencieusement l’exécution courante. - Rejette les noms de méthodes non déclarés avec `rejected_unknown_update` et les arguments non conformes au contrat avec `rejected_invalid_arguments` (et des `validation_errors` lisibles par machine) avant d’exécuter le gestionnaire. +- Rejette comme `update_validator_rejected`, avant de l’accepter, une demande que votre [validateur de mise à jour](#validate-updates-before-acceptance) refuse. Comme les requêtes de lecture, les mises à jour relisent d’abord l’historique validé. Elles peuvent toutefois modifier un état de workflow sûr à relire et renvoyer une valeur. @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` n’attend pas l’exécution du workflow. Il recharge le cycle de vie durable stocké et renvoie le `UpdateResult` courant. +## Valider les mises à jour avant leur acceptation {#validate-updates-before-acceptance} + +Sans validateur, une mise à jour qui enfreint une règle métier est acceptée puis échoue. Elle est enregistrée comme mise à jour en échec, et l’appelant ne peut pas distinguer une demande incorrecte d’une opération qui a échoué. Déclarez un validateur pour refuser la demande avant qu’elle soit acceptée. Les validateurs nécessitent Workflow 2.42.0 ou une version ultérieure. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` désigne la mise à jour par son nom durable, ou par le nom de sa méthode lorsque la mise à jour n’a pas d’alias. Le validateur reçoit les mêmes arguments que la mise à jour. Avant que la mise à jour soit acceptée, le moteur reconstruit l’état de l’exécution à partir de son historique et n’appelle que le validateur : + +- S’il retourne normalement, la mise à jour est acceptée et appliquée comme d’habitude. +- S’il lève une exception ou retourne `false`, la mise à jour est rejetée avec la raison `update_validator_rejected` et le résultat `rejected_invalid_arguments`. `rejectedByValidator()` est vrai, `rejectionMessage()` retourne le message de l’exception et `validationErrors()` retourne les erreurs d’une `ValidationException` Laravel. `update()` lève une `LogicException` qui contient la raison et le message du validateur. +- Une mise à jour rejetée n’est jamais acceptée, son handler ne s’exécute jamais et le workflow n’est pas réveillé. Comme tout autre rejet, elle n’est enregistrée que sous la forme d’un événement d’audit `UpdateRejected`, que la relecture ignore. + +Les validateurs sont en lecture seule. Ils peuvent lire l’état reconstruit du workflow, mais tout appel durable (une activité, un temporisateur, un workflow enfant, un signal, un side effect, `await`, `getVersion()`, `patched()`, continue-as-new ou un upsert de mémo ou d’attributs de recherche) lève `UpdateValidatorCommandException` et rejette la mise à jour. Les modifications qu’un validateur apporte à l’état reconstruit sont abandonnées. Un validateur générateur est rejeté, car son corps ne s’exécute jamais. + +Les validateurs ne sont pas enregistrés dans l’historique et ne s’exécutent jamais pendant la relecture ; ils n’affectent donc pas le déterminisme. Ils voient l’état issu de l’historique validé : une mise à jour acceptée mais pas encore appliquée ne leur est pas visible. La relecture et le validateur s’exécutent pendant que l’admission de la mise à jour détient les verrous de l’exécution ; gardez donc les validateurs rapides. + +Si l’état ne peut pas être reconstruit, ou si le validateur rencontre une erreur de base de données, `UpdateValidationFailedException` est levée et rien n’est enregistré. Les routes webhook de mise à jour y répondent par un `503` réessayable et `update_validation_failed`. Réessayez avec le même identifiant de requête. + +Une nouvelle tentative avec clé d’une mise à jour rejetée retourne le rejet conservé sans réexécuter le validateur. + +Les intercepteurs du worker enveloppent la validation de mise à jour via `executeUpdateValidation()`. Ils voient la décision du validateur, mais ne peuvent pas la modifier. + ## Récupérer après une réponse incertaine {#recover-after-an-uncertain-response} L’admission durable, la fin du gestionnaire et un effet métier externe sont 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 836c3c85b35..1fc6d526352 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -157,6 +157,66 @@ requêtes de lecture et mises à jour via `registerWorkflow`, La [référence d’API générée du SDK PHP](https://php.durable-workflow.com/api/) donne tous les paramètres et types de retour. +## Validateurs de mise à jour {#update-validators} + +À partir du PHP SDK 3.32.0, un workflow peut refuser une mise à jour avant qu’elle soit acceptée. Placez `#[UpdateValidator]` sur une méthode de la classe du workflow, à côté de son handler `#[Update]`. La forme de bas niveau est `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, appelée après `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +Le validateur reçoit un `QueryContext` contenant l’historique validé de l’exécution, suivi des arguments de la mise à jour. Le worker annonce le validateur au Server et interroge ensemble les tâches de workflow et de validation de mise à jour. L’enregistrement est refusé avec `update_validation_tasks_unavailable` lorsque le Server n’annonce pas la validation synchrone des mises à jour. Pour chaque tâche de validation, le worker n’exécute que le validateur : + +- S’il retourne normalement, il approuve la mise à jour et le Server l’accepte. +- S’il lève une exception ou retourne `false`, il la rejette avec `update_validator_rejected`, le message et la classe de l’exception, ainsi que les erreurs de champ d’une méthode `errors()` de l’exception. La mise à jour n’est jamais acceptée et son handler ne s’exécute jamais. Le Server n’enregistre le rejet que sous la forme d’un événement d’audit `UpdateRejected`. +- Toute tentative de planifier un travail durable est refusée avec `UpdateValidatorCommandRefused`, ce qui rejette la mise à jour. + +Côté client, `updateWorkflow()` lève `UpdateFailed`. `rejectedByValidator()` identifie un rejet du validateur et `validationErrors()` retourne ses erreurs de champ. `validationFailed()` est vrai lorsque le Server n’a pas pu obtenir de décision à temps ; rien n’a été accepté, réessayez donc avec le même identifiant de requête. + +Les validateurs ne s’exécutent jamais pendant la relecture. Chaque validation ne voit que l’historique validé avant sa propre tâche ; deux validations simultanées peuvent donc toutes deux réussir un contrôle qu’une seule devrait réussir. Un worker avec validateurs n’utilise pas les interrogations de workflow transportées. Les intercepteurs du worker enveloppent les tâches de validation de mise à jour via `executeUpdateValidation()` ; ils voient la décision du validateur, mais ne peuvent pas la modifier. + +## Journalisation de workflow consciente de la relecture {#workflow-logging} + +Le worker relit un workflow à partir de son historique à chaque tâche de workflow ; un appel de journalisation ordinaire dans le code du workflow se répète donc une fois par étape terminée. Le PHP SDK 3.32.0 et versions ultérieures fournissent `$context->logger()`. Il retourne un logger PSR-3 qui écrit via le logger que vous passez au `Worker` (l’argument nommé `logger`), et uniquement lorsque le code s’exécute au-delà de l’historique validé de l’exécution : + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Chaque ligne contient `namespace`, `workflow_type`, `workflow_id` et `workflow_run_id`. `$context->replayState()` retourne `WorkflowReplayState::Replaying`, `Executing` ou `Unavailable`, et `isReplaying()` en est la forme booléenne. Utilisez-les uniquement pour le diagnostic ; ne choisissez jamais de commandes de workflow d’après elles. + +Les lignes ne sont écrites qu’après que le Worker a soumis la tâche de workflow qui a exécuté le code et que le Server l’a acceptée. Une relecture remplacée, une relecture spéculative que le Server décline et une complétion refusée n’écrivent rien. Le code qui attend sur un handle d’enfant ou d’opération en suspens sans enregistrer d’étape journalise une seule fois, dans la tâche qui dépasse l’attente. Un appel à `logger()` dans une closure de side effect n’écrit rien. + +Si le worker meurt entre l’acceptation par le Server et l’écriture, ces lignes sont perdues. C’est un logger de processus, pas une outbox pour les effets métier. Gardez les handlers de journalisation rapides et non bloquants : un handler qui attend le réseau bloque le worker et peut lui coûter le bail de la tâche. Les échecs du logger sont interceptés et ne modifient jamais les commandes du workflow. + ## Contexte de reprise et exécution propriétaire d’une activité {#activity-retry-context} Le SDK PHP **3.6.1 ou ultérieur** expose `$context->retryInfo`, `$context->workflowId` et `$context->runId` dans les activités en mode service. Vérifiez `$context->retryInfo->isLastConfiguredAttempt() === true` pour reconnaître la dernière tentative configurée d’une politique limitée. `attemptNumber` conserve le numéro de tentative reçu à l’origine. 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 98b3e459e58..261932acf89 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -986,6 +986,49 @@ Une mise à jour est une mutation durable de workflow qui produit un résultat. Elle se distingue des signaux sans attente de réponse et des requêtes de lecture relues sans mutation. +### Validateurs de mise à jour {#update-validators} + +À partir du Rust SDK 4.25.0, un worker peut refuser une mise à jour avant +qu’elle soit acceptée. Enregistrez un validateur avec +`Worker::register_update_validator`, après le handler de mise à jour du même nom : + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` reçoit des valeurs Avro. Un validateur à +état relu, `register_replayed_update_validator::`, lit une copie détachée de +l’état relu du workflow ; il doit utiliser le même type d’état que le workflow +relu. Le worker annonce le validateur, refuse l’enregistrement lorsque le Server +n’annonce pas la validation synchrone des mises à jour et interroge ensemble les +tâches de workflow et de validation de mise à jour. Pour chaque tâche de +validation, il n’exécute que le validateur : + +- `Ok(())` approuve la mise à jour et le Server l’accepte. +- Un `UpdateRejection` la rejette avec `update_validator_rejected`, le message, + le type et les erreurs de validation. La mise à jour n’est jamais acceptée et + son handler ne s’exécute jamais. Le Server n’enregistre le rejet que sous la + forme d’un événement d’audit `UpdateRejected`. +- Un validateur qui ajoute une commande de workflow est refusé avec + `UpdateValidatorCommandRefused`, et une panique ou un échec de relecture + signale `update_validation_worker_failed`. + +Côté client, `Error::update_validator_rejection()` retourne le message, les +erreurs de validation et les identifiants du rejet, et +`Error::is_update_validation_failed()` couvre les délais dépassés et les échecs du +worker. Une mise à jour en échec ordinaire ne correspond à aucun des deux. Les +validateurs ne s’exécutent jamais pendant la relecture. Les intercepteurs du +worker enveloppent les tâches de validation de mise à jour via +`execute_update_validation_task` ; ils voient la décision du validateur, mais ne +peuvent pas la modifier. + ## Enveloppe de données utiles {#payload-envelope} Les entrées de workflow, signaux, activités, requêtes de lecture et résultats diff --git a/i18n/fr/source-hashes.json b/i18n/fr/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/fr/source-hashes.json +++ b/i18n/fr/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/ja/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index 579f1440949..0189cc233b6 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -17,9 +17,35 @@ description: リプレイの決定性を保ち、起動時に安全でない呼 ## ワークフローコードからのロギング {#workflow-logging} -worker は起動ごとの再開やコールド置換後に確定済みワークフロー履歴を再構築するため、通常のアプリケーションログは以前のメッセージを繰り返し得ます。利用可能なら、その binding で文書化されたリプレイ対応ロガーを使ってください。Rust サービスモードには [Rust SDK 4.17 のワークフローロガー](../polyglot/rust.md#workflow-logging)があります。他の binding はそれぞれの文書化された契約に従います。 +エンジンはワークフローが起動するたびに履歴からリプレイするため、ワークフローコード内の通常のログ呼び出しは完了したステップごとに書き直されます。50 ステップのワークフローは最初の行を 50 回記録します。代わりにリプレイ対応ロガーを使ってください。コードが初めて実行されるときだけ書き込みます。組み込みワークフロー、PHP SDK、Rust のロガーは、各行に実行の識別情報も付けます。 -ロギングはプロセスの観測です。永続ワークフローコマンドを、replay state の観測やログ配送に依存させないでください。リプレイ対応ロガーでも、未確定試行のメッセージはクラッシュや retry 後に重複し得ます。exactly-once outbox ではありません。ホスト handler は有界かつ非ブロッキングにし、worker を停止させないようにしてください。永続的な業務効果は、適切な activity または記録されるワークフロー操作に置いてください。 +- 組み込みワークフロー(Workflow 2.42.0 以降): `$this->logger()` は PSR-3 ロガーを返し、Laravel のロガー、または `$this->logger('workflow')` のように渡したチャネルを通じて書き込みます。各行には `workflow_instance_id`、`workflow_run_id`、`workflow_type`、`namespace` が含まれます。`$this->replayState()` は `Workflow\V2\Enums\WorkflowReplayState`(`Replaying`、`Executing`、`Unavailable`)を返し、`$this->isReplaying()` はその真偽値版です。 +- PHP SDK: `$context->logger()` は `Worker` の PSR-3 ロガーを通じて書き込みます。[PHP SDK ガイド](../polyglot/php.md#workflow-logging)を参照してください。 +- Rust SDK: `ctx.logger()`。[Rust SDK 4.17 のワークフローロガー](../polyglot/rust.md#workflow-logging)を参照してください。 +- Python SDK: `ctx.logger`。リプレイ中は何も書き込みませんが、実行の識別情報は付けません。 + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +クエリと更新バリデーターは常にリプレイなので、ログを書きません。 + +組み込みワークフローでは、ワークフロータスクのデータベーストランザクションがコミットされた後に行が書き込まれるため、ロールバックされたタスクは何も書き込みません。ステップを記録せずに保留中の `select()` ハンドルで待機するコードは、その待機を抜けたタスクで一度だけログを書きます。ライブで実行された更新ハンドラーの行は、更新が適用されたときに書き込まれます。PHP SDK では、Server がワークフロータスクを受理した後に行が書き込まれます。[PHP SDK ガイド](../polyglot/php.md#workflow-logging)を参照してください。 + +ロギングはプロセスの観測です。永続ワークフローコマンドを、リプレイ状態の観測やログ配送に依存させないでください。リプレイ対応ロガーは exactly-once outbox ではありません。組み込みまたは PHP SDK の Worker がコミットまたは受理と書き込みの間に停止すると、それらの行は失われます。Rust のロガーは、クラッシュや再試行の後に未確定の試行のメッセージを繰り返すことがあります。ホストのハンドラーは有界かつ非ブロッキングにして、ロギングで Worker を止めないでください。永続的な業務効果は、適切なアクティビティまたは記録されるワークフロー操作に置いてください。 ## 起動時のチェック {#boot-time-guardrails} diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/ja/docusaurus-plugin-content-docs/current/features/updates.md index 5334f6c2514..56c8a8e4cd3 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ sidebar_position: 3 - 履歴と Webhook ルーティングには宣言した永続更新名を使います。`#[UpdateMethod('mark-approved')]` は PHP メソッド名を変更しても公開呼び出し名を維持します。 - 過去や終了済みの実行に対しては、現在の実行を黙って変更せず拒否します。 - ハンドラー実行前に、未宣言の名前を `rejected_unknown_update`、契約に合わない引数を機械可読な `validation_errors` 付きの `rejected_invalid_arguments` で拒否します。 +- [更新バリデーター](#validate-updates-before-acceptance)が拒否したリクエストを、受理前に `update_validator_rejected` として拒否します。 クエリと同じく、更新はまずコミット済み履歴をリプレイします。クエリとは異なり、安全にリプレイできる状態を変更して値を返せます。 @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` はワークフロー実行を待ちません。保存された永続ライフサイクルを再読込し、現在の `UpdateResult` を返します。 +## 受理前に更新を検証する {#validate-updates-before-acceptance} + +バリデーターがない場合、業務ルールに反する更新はいったん受理されてから失敗します。失敗した更新として記録され、呼び出し側は不正なリクエストと失敗した操作を区別できません。バリデーターを宣言すると、受理前にリクエストを拒否できます。バリデーターには Workflow 2.42.0 以降が必要です。 + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` は、更新を永続名で指定します。更新にエイリアスがない場合はメソッド名で指定します。バリデーターは更新と同じ引数を受け取ります。更新を受理する前に、エンジンは履歴から実行の状態を再構築し、バリデーターだけを呼び出します。 + +- 通常どおり戻った場合、更新はいつもどおり受理・適用されます。 +- 例外を投げるか `false` を返した場合、更新は理由 `update_validator_rejected`、結果 `rejected_invalid_arguments` で拒否されます。`rejectedByValidator()` は true になり、`rejectionMessage()` は例外メッセージを、`validationErrors()` は Laravel の `ValidationException` のエラーを返します。`update()` は理由とバリデーターのメッセージを含む `LogicException` を投げます。 +- 拒否された更新は受理されず、ハンドラーも実行されず、ワークフローも起こされません。ほかの拒否と同様に、記録されるのは監査イベント `UpdateRejected` だけで、リプレイはこれを無視します。 + +バリデーターは読み取り専用です。再構築されたワークフロー状態は読めますが、永続的な呼び出し(アクティビティ、タイマー、子ワークフロー、シグナル、side effect、`await`、`getVersion()`、`patched()`、continue-as-new、memo または検索属性の upsert)はすべて `UpdateValidatorCommandException` を投げ、更新を拒否します。バリデーターが再構築された状態に加えた変更は破棄されます。ジェネレーターのバリデーターは本体が実行されないため、拒否されます。 + +バリデーターは履歴に記録されず、リプレイ中にも実行されないため、決定性に影響しません。バリデーターが見るのは確定済み履歴の状態です。受理済みでまだ適用されていない更新は見えません。リプレイとバリデーターは、更新の受理処理が実行のロックを保持している間に動くため、バリデーターは高速に保ってください。 + +状態を再構築できない場合や、バリデーターがデータベースエラーに遭遇した場合は、`UpdateValidationFailedException` が投げられ、何も記録されません。更新用の webhook ルートは、再試行可能な `503` と `update_validation_failed` で応答します。同じリクエスト ID で再試行してください。 + +拒否された更新をキー付きで再試行すると、バリデーターを再実行せずに保持済みの拒否が返ります。 + +Worker のインターセプターは `executeUpdateValidation()` を通じて更新検証をラップします。バリデーターの判定は見えますが、変更はできません。 + ## 応答が不確かな場合の復旧 {#recover-after-an-uncertain-response} 永続的な受理、ハンドラーの完了、外部の業務上の作用は別々の事実です。呼び出し元がタイムアウトしても受理済み更新が動き続ける場合があり、応答喪失によりコミット済み結果を見失う場合もあります。後の新規更新の拒否だけでは元の結果は確定しません。 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 9d981c6daea..6f7a428a1a1 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -89,6 +89,66 @@ SDK 所有のクイックスタートは、空の Composer プロジェクトを リモート Worker は `registerWorkflow`、`registerActivity`、`registerQuery`、`registerUpdate` でワークフロー、アクティビティ、クエリ、更新のハンドラーを登録します。完全なパラメーターと戻り値の型は、生成された [PHP SDK API リファレンス](https://php.durable-workflow.com/api/)を使ってください。 +## 更新バリデーター {#update-validators} + +PHP SDK 3.32.0 以降では、ワークフローは更新を受理前に拒否できます。ワークフロークラスのメソッドに、`#[Update]` ハンドラーと並べて `#[UpdateValidator]` を付けます。低レベルの形式は `Worker::registerUpdateValidator($workflowType, $updateName, $callable)` で、`registerUpdate()` の後に呼び出します。 + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +バリデーターは、実行の確定済み履歴を持つ `QueryContext` と、それに続く更新の引数を受け取ります。Worker はバリデーターを Server に通知し、ワークフロータスクと更新検証タスクをまとめてポーリングします。Server が同期的な更新検証を通知しない場合、登録は `update_validation_tasks_unavailable` で拒否されます。各検証タスクで、Worker はバリデーターだけを実行します。 + +- 通常どおり戻ると更新を承認し、Server がそれを受理します。 +- 例外を投げるか `false` を返すと、`update_validator_rejected`、例外のメッセージとクラス、例外の `errors()` メソッドが返すフィールドエラーで更新を拒否します。更新は受理されず、ハンドラーも実行されません。Server は拒否を監査イベント `UpdateRejected` としてだけ記録します。 +- 永続的な処理をスケジュールしようとすると `UpdateValidatorCommandRefused` で拒否され、更新も拒否されます。 + +クライアントでは、`updateWorkflow()` が `UpdateFailed` を投げます。`rejectedByValidator()` でバリデーターによる拒否を判別でき、`validationErrors()` がそのフィールドエラーを返します。`validationFailed()` は、Server が時間内に判断を得られなかった場合に true です。何も受理されていないので、同じリクエスト ID で再試行してください。 + +バリデーターはリプレイ中に実行されません。各検証は自分のタスクより前に確定した履歴だけを見るため、同時に実行される 2 つの検証が、本来は片方だけが通るべきチェックを両方とも通ることがあります。バリデーターを持つ Worker は持ち越しのワークフローポーリングを使いません。Worker のインターセプターは `executeUpdateValidation()` を通じて更新検証タスクをラップし、バリデーターの判定は見えますが、変更はできません。 + +## リプレイ対応のワークフローロギング {#workflow-logging} + +Worker はワークフロータスクごとに履歴からワークフローをリプレイするため、ワークフローコード内の通常のログ呼び出しは完了したステップごとに繰り返されます。PHP SDK 3.32.0 以降には `$context->logger()` があります。これは PSR-3 ロガーを返し、`Worker` に渡したロガー(名前付き引数 `logger`)を通じて、コードが実行の確定済み履歴を越えて動くときだけ書き込みます。 + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +各行には `namespace`、`workflow_type`、`workflow_id`、`workflow_run_id` が含まれます。`$context->replayState()` は `WorkflowReplayState::Replaying`、`Executing`、`Unavailable` のいずれかを返し、`isReplaying()` はその真偽値版です。診断にだけ使い、これをもとにワークフローコマンドを選ばないでください。 + +行が書き込まれるのは、Worker がコードを実行したワークフロータスクを送信し、Server がそれを受理した後だけです。置き換えられたリプレイ、Server が辞退した投機的リプレイ、拒否された完了は何も書き込みません。ステップを記録せずに保留中の子ワークフローまたは操作のハンドルで待機するコードは、その待機を抜けたタスクで一度だけログを書きます。side effect のクロージャー内の `logger()` 呼び出しは何も書き込みません。 + +Server の受理から書き込みまでの間に Worker が停止すると、それらの行は失われます。これはプロセスのロガーであり、業務効果のための outbox ではありません。ログハンドラーは高速かつ非ブロッキングに保ってください。ネットワークを待つハンドラーは Worker を止め、タスクのリースを失わせることがあります。ロガーの失敗は捕捉され、ワークフローのコマンドを変えることはありません。 + ## アクティビティの再試行コンテキストと所属する実行 {#activity-retry-context} PHP SDK **3.6.1 以降**では、サービスモードのアクティビティで `$context->retryInfo`、`$context->workflowId`、`$context->runId` を参照できます。回数制限のあるポリシーの最後の設定済み試行は、`$context->retryInfo->isLastConfiguredAttempt() === true` で判定します。`attemptNumber` は、受信した元の試行番号を保持します。 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 3261618a665..e80f1290b89 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -756,6 +756,29 @@ Rust はアプリケーションクライアント、選択ハンドル、Worker Worker は `Worker::register_update` で名前付きハンドラーを登録します。Avro 値を直接受け取り返すハンドラーには `register_update_avro_value` を使います。更新は永続的で結果を伴うワークフロー変更です。送信後に結果を待たないシグナルや、読み取り専用でリプレイされるクエリとは別です。 +### 更新バリデーター {#update-validators} + +Rust SDK 4.25.0 以降では、Worker は更新を受理前に拒否できます。同じ名前の更新ハンドラーの後で、`Worker::register_update_validator` によりバリデーターを登録します。 + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` は Avro 値を受け取ります。リプレイ済み状態のバリデーター `register_replayed_update_validator::` は、ワークフローのリプレイ済み状態の切り離されたコピーを読みます。リプレイされるワークフローと同じ状態型を使う必要があります。Worker はバリデーターを通知し、Server が同期的な更新検証を通知しない場合は登録を拒否し、ワークフロータスクと更新検証タスクをまとめてポーリングします。各検証タスクでは、バリデーターだけを実行します。 + +- `Ok(())` は更新を承認し、Server がそれを受理します。 +- `UpdateRejection` は `update_validator_rejected`、メッセージ、型、検証エラーで更新を拒否します。更新は受理されず、ハンドラーも実行されません。Server は拒否を監査イベント `UpdateRejected` としてだけ記録します。 +- ワークフローコマンドを追加するバリデーターは `UpdateValidatorCommandRefused` で拒否され、panic やリプレイの失敗は `update_validation_worker_failed` を報告します。 + +クライアントでは、`Error::update_validator_rejection()` が拒否のメッセージ、検証エラー、ID を返し、`Error::is_update_validation_failed()` がタイムアウトと Worker の失敗を扱います。通常の失敗した更新はどちらにも該当しません。バリデーターはリプレイ中に実行されません。Worker のインターセプターは `execute_update_validation_task` を通じて更新検証タスクをラップし、バリデーターの判定は見えますが、変更はできません。 + ## ペイロードエンベロープ {#payload-envelope} ワークフロー入力、シグナル、アクティビティ、クエリ、結果は、`codec` とエンコード済み `blob` から成る公開 `PayloadEnvelope` 契約を使います。SDK の既定の `avro` 経路は、宣言した `apache-avro` 依存関係とプラットフォームの固定バージョン付き Value スキーマを使います。blob を独自実装したり、実装固有のレコードでエンベロープを置き換えたりしないでください。 diff --git a/i18n/ja/source-hashes.json b/i18n/ja/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/ja/source-hashes.json +++ b/i18n/ja/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index e2b5a644e17..981cfb0cddf 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -17,9 +17,35 @@ Evite estas operações dentro de uma classe de workflow: ## Logging no código do workflow {#workflow-logging} -Um worker reconstrói o histórico confirmado após ativações e substituição a frio, por isso o logging comum da aplicação pode repetir mensagens anteriores. Use o logger consciente de replay documentado para seu binding quando disponível. O modo serviço Rust oferece o [logger de workflow do Rust SDK 4.17](../polyglot/rust.md#workflow-logging); outros bindings mantêm seus contratos documentados separadamente. +O motor faz o replay de um workflow a partir do histórico toda vez que ele acorda, então uma chamada de log comum no código do workflow é gravada novamente a cada passo concluído. Um workflow com 50 passos registra sua primeira linha 50 vezes. Use, em vez disso, o logger ciente do replay. Ele só grava quando o código é executado pela primeira vez. Os loggers de workflows embarcados, do PHP SDK e do Rust também acrescentam a identidade da execução a cada linha: -Logging é uma observação do processo. Mantenha os comandos duráveis independentes das observações de replay e da entrega dos logs. Mesmo um logger consciente de replay pode repetir uma mensagem de tentativa não confirmada após falha ou retry; ele não é um outbox exatamente uma vez. Os handlers do host devem ser limitados e não bloqueantes para não parar o worker. Coloque efeitos duráveis de negócio na atividade ou operação registrada do workflow apropriada. +- Workflows embarcados (Workflow 2.42.0 ou posterior): `$this->logger()` retorna um logger PSR-3 que grava pelo logger do Laravel, ou pelo canal que você informar, como em `$this->logger('workflow')`. Cada linha traz `workflow_instance_id`, `workflow_run_id`, `workflow_type` e `namespace`. `$this->replayState()` retorna `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` ou `Unavailable`), e `$this->isReplaying()` é sua forma booleana. +- PHP SDK: `$context->logger()` grava pelo logger PSR-3 do `Worker`. Veja o [guia do PHP SDK](../polyglot/php.md#workflow-logging). +- Rust SDK: `ctx.logger()`. Veja o [logger de workflow do Rust SDK 4.17](../polyglot/rust.md#workflow-logging). +- Python SDK: `ctx.logger`, que fica em silêncio durante o replay, mas não acrescenta a identidade da execução. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Consultas e validadores de atualização nunca registram logs, porque são sempre um replay. + +Em workflows embarcados, as linhas são gravadas depois que a transação de banco de dados da tarefa de workflow é confirmada, então uma tarefa revertida não grava nada. Código que aguarda um handle `select()` pendente sem registrar um passo registra uma única vez, na tarefa que passa da espera. Linhas de um handler de atualização executado ao vivo são gravadas quando a atualização é aplicada. No PHP SDK, as linhas são gravadas depois que o Server aceita a tarefa de workflow; veja o [guia do PHP SDK](../polyglot/php.md#workflow-logging). + +Logging é uma observação do processo. Mantenha os comandos duráveis do workflow independentes das observações do estado de replay e da entrega de logs. Um logger ciente do replay não é um outbox exactly-once: se um worker embarcado ou do PHP SDK morrer entre a confirmação ou a aceitação e a gravação, essas linhas se perdem, e o logger do Rust pode repetir uma mensagem de uma tentativa não confirmada após uma falha ou um retry. Mantenha os handlers do host limitados e não bloqueantes para que o logging não trave o worker. Coloque efeitos de negócio duráveis na atividade adequada ou em uma operação de workflow registrada. ## Verificações na inicialização {#boot-time-guardrails} diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/features/updates.md index 6cb419e4041..2f51f97272c 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ Cada atualização aceita: - Usa o nome durável declarado da atualização no histórico de comandos e no roteamento de webhooks. `#[UpdateMethod('mark-approved')]` mantém o nome público estável entre renomeações do método PHP. - É rejeitada em execuções históricas ou já encerradas, em vez de alterar silenciosamente a execução atual. - Rejeita nomes de métodos não declarados como `rejected_unknown_update` e argumentos incompatíveis com o contrato como `rejected_invalid_arguments` (com `validation_errors` legíveis por máquina), antes de executar o handler. +- Rejeita como `update_validator_rejected`, antes de aceitá-la, uma solicitação que o seu [validador de atualização](#validate-updates-before-acceptance) recusa. Assim como consultas, atualizações primeiro reproduzem o histórico confirmado. Diferentemente das consultas, atualizações podem alterar o estado do workflow seguro para replay e retornar um valor. @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` não espera a execução do workflow. Recarrega o ciclo de vida durável armazenado e retorna o `UpdateResult` atual. +## Validar atualizações antes da aceitação {#validate-updates-before-acceptance} + +Sem um validador, uma atualização que viola uma regra de negócio é aceita e depois falha. Ela é registrada como atualização com falha, e quem chama não consegue distinguir uma solicitação inválida de uma operação que falhou. Declare um validador para recusar a solicitação antes que ela seja aceita. Validadores exigem Workflow 2.42.0 ou posterior. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` identifica a atualização pelo seu nome durável, ou pelo nome do método quando a atualização não tem alias. O validador recebe os mesmos argumentos da atualização. Antes de a atualização ser aceita, o motor reconstrói o estado da execução a partir do histórico e chama apenas o validador: + +- Se ele retornar normalmente, a atualização é aceita e aplicada como de costume. +- Se ele lançar uma exceção ou retornar `false`, a atualização é rejeitada com o motivo `update_validator_rejected` e o resultado `rejected_invalid_arguments`. `rejectedByValidator()` é verdadeiro, `rejectionMessage()` retorna a mensagem da exceção e `validationErrors()` retorna os erros de uma `ValidationException` do Laravel. `update()` lança uma `LogicException` que inclui o motivo e a mensagem do validador. +- Uma atualização rejeitada nunca é aceita, seu handler nunca é executado e o workflow não é acordado. Como qualquer outra rejeição, ela é registrada apenas como um evento de auditoria `UpdateRejected`, que o replay ignora. + +Validadores são somente leitura. Eles podem ler o estado reconstruído do workflow, mas qualquer chamada durável (uma atividade, um temporizador, um workflow filho, um sinal, um side effect, `await`, `getVersion()`, `patched()`, continue-as-new ou um upsert de memo ou de atributos de busca) lança `UpdateValidatorCommandException` e rejeita a atualização. Alterações que um validador faz no estado reconstruído são descartadas. Um validador gerador é rejeitado, porque seu corpo nunca é executado. + +Validadores não são registrados no histórico e nunca são executados durante o replay, portanto não afetam o determinismo. Eles veem o estado do histórico confirmado: uma atualização aceita, mas ainda não aplicada, não é visível para eles. O replay e o validador são executados enquanto a admissão da atualização mantém os bloqueios da execução, então mantenha os validadores rápidos. + +Se o estado não puder ser reconstruído, ou se o validador encontrar um erro de banco de dados, `UpdateValidationFailedException` é lançada e nada é registrado. As rotas de webhook de atualização respondem com um `503` que pode ser repetido e `update_validation_failed`. Repita com o mesmo ID de solicitação. + +Uma nova tentativa com chave de uma atualização rejeitada retorna a rejeição retida sem executar o validador novamente. + +Os interceptadores do worker envolvem a validação de atualização por meio de `executeUpdateValidation()`. Eles veem a decisão do validador, mas não podem alterá-la. + ## Recuperação após uma resposta incerta {#recover-after-an-uncertain-response} Admissão durável, conclusão do handler e um efeito externo de negócio são 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 359c3d24191..87efe3e4ccd 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 @@ -156,6 +156,66 @@ atualização por `registerWorkflow`, `registerActivity`, `registerQuery` e `registerUpdate`. Use a [referência gerada da API do SDK PHP](https://php.durable-workflow.com/api/) para parâmetros e tipos de retorno completos. +## Validadores de atualização {#update-validators} + +A partir do PHP SDK 3.32.0, um workflow pode recusar uma atualização antes que ela seja aceita. Coloque `#[UpdateValidator]` em um método da classe do workflow, ao lado do handler `#[Update]`. A forma de baixo nível é `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, chamada depois de `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +O validador recebe um `QueryContext` com o histórico confirmado da execução, seguido dos argumentos da atualização. O worker anuncia o validador ao Server e consulta juntas as tarefas de workflow e de validação de atualização. O registro é recusado com `update_validation_tasks_unavailable` quando o Server não anuncia a validação síncrona de atualizações. Para cada tarefa de validação, o worker executa apenas o validador: + +- Se ele retornar normalmente, aprova a atualização e o Server a aceita. +- Se ele lançar uma exceção ou retornar `false`, a atualização é rejeitada com `update_validator_rejected`, a mensagem e a classe da exceção e os erros de campo de um método `errors()` da exceção. A atualização nunca é aceita e seu handler nunca é executado. O Server registra a rejeição apenas como um evento de auditoria `UpdateRejected`. +- Tentar agendar trabalho durável é recusado com `UpdateValidatorCommandRefused`, o que rejeita a atualização. + +No cliente, `updateWorkflow()` lança `UpdateFailed`. `rejectedByValidator()` identifica uma rejeição do validador e `validationErrors()` retorna seus erros de campo. `validationFailed()` é verdadeiro quando o Server não conseguiu obter uma decisão a tempo; nada foi aceito, então repita com o mesmo ID de solicitação. + +Validadores nunca são executados durante o replay. Cada validação vê apenas o histórico confirmado antes da própria tarefa, então duas validações simultâneas podem passar em uma verificação que apenas uma delas deveria passar. Um worker com validadores não usa polls de workflow transportados. Os interceptadores do worker envolvem as tarefas de validação de atualização por meio de `executeUpdateValidation()`; eles veem a decisão do validador, mas não podem alterá-la. + +## Logging de workflow ciente do replay {#workflow-logging} + +O worker faz o replay de um workflow a partir do histórico a cada tarefa de workflow, então uma chamada de log comum no código do workflow se repete uma vez por passo concluído. O PHP SDK 3.32.0 e posteriores oferecem `$context->logger()`. Ele retorna um logger PSR-3 que grava pelo logger passado ao `Worker` (o argumento nomeado `logger`), e apenas quando o código é executado além do histórico confirmado da execução: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Cada linha traz `namespace`, `workflow_type`, `workflow_id` e `workflow_run_id`. `$context->replayState()` retorna `WorkflowReplayState::Replaying`, `Executing` ou `Unavailable`, e `isReplaying()` é sua forma booleana. Use-os apenas para diagnóstico; nunca escolha comandos de workflow com base neles. + +As linhas só são gravadas depois que o Worker envia a tarefa de workflow que executou o código e o Server a aceita. Um replay substituído, um replay especulativo que o Server recusa e uma conclusão rejeitada não gravam nada. Código que aguarda um handle pendente de filho ou de operação sem registrar um passo registra uma única vez, na tarefa que passa da espera. Uma chamada a `logger()` dentro de uma closure de side effect não grava nada. + +Se o worker morrer entre a aceitação pelo Server e a gravação, essas linhas se perdem. Este é um logger de processo, não um outbox para efeitos de negócio. Mantenha os handlers de log rápidos e não bloqueantes: um handler que espera pela rede trava o worker e pode custar a ele o lease da tarefa. Falhas do logger são capturadas e nunca alteram os comandos do workflow. + ## Contexto de novas tentativas e execução proprietária da atividade {#activity-retry-context} O SDK PHP **3.6.1 ou posterior** expõe `$context->retryInfo`, `$context->workflowId` e `$context->runId` nas atividades em modo de serviço. Verifique `$context->retryInfo->isLastConfiguredAttempt() === true` para identificar a última tentativa configurada de uma política limitada. `attemptNumber` preserva o número da tentativa recebido originalmente. 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 c4b9b561020..35613399818 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 @@ -963,6 +963,48 @@ Workers registram handlers nomeados com `Worker::register_update`; use diretamente. Uma atualização é uma mutação durável de workflow com resultado. É separada dos sinais sem espera de resposta e das consultas somente leitura com replay. +### Validadores de atualização {#update-validators} + +A partir do Rust SDK 4.25.0, um worker pode recusar uma atualização antes que ela +seja aceita. Registre um validador com `Worker::register_update_validator`, +depois do handler de atualização com o mesmo nome: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` recebe valores Avro. Um validador de +estado reconstruído, `register_replayed_update_validator::`, lê uma cópia +separada do estado do workflow após o replay; ele precisa usar o mesmo tipo de +estado do workflow reconstruído. O worker anuncia o validador, recusa o registro +quando o Server não anuncia a validação síncrona de atualizações e consulta +juntas as tarefas de workflow e de validação de atualização. Para cada tarefa de +validação, ele executa apenas o validador: + +- `Ok(())` aprova a atualização e o Server a aceita. +- Um `UpdateRejection` a rejeita com `update_validator_rejected`, a mensagem, o + tipo e os erros de validação. A atualização nunca é aceita e seu handler nunca + é executado. O Server registra a rejeição apenas como um evento de auditoria + `UpdateRejected`. +- Um validador que adiciona um comando de workflow é recusado com + `UpdateValidatorCommandRefused`, e um panic ou uma falha de replay informa + `update_validation_worker_failed`. + +No cliente, `Error::update_validator_rejection()` retorna a mensagem, os erros de +validação e os IDs da rejeição, e `Error::is_update_validation_failed()` cobre +timeouts e falhas do worker. Uma atualização com falha comum não corresponde a +nenhum dos dois. Validadores nunca são executados durante o replay. Os interceptadores +do worker envolvem as tarefas de validação de atualização por meio de +`execute_update_validation_task`; eles veem a decisão do validador, mas não podem +alterá-la. + ## Envelope de payload {#payload-envelope} Entradas de workflow, sinais, atividades, consultas e resultados usam o diff --git a/i18n/pt-BR/source-hashes.json b/i18n/pt-BR/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/pt-BR/source-hashes.json +++ b/i18n/pt-BR/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/uk/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index 6e1364711db..212dc7aa5c0 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -28,9 +28,35 @@ sidebar_position: 2 ## Журналювання з коду workflow {#workflow-logging} -Worker відновлює зафіксовану історію workflow після активацій і холодної заміни, тому звичайне журналювання застосунку може повторювати попередні повідомлення. За наявності використовуйте документований для вашого binding logger з урахуванням replay. Rust service mode надає [logger workflow у Rust SDK 4.17](../polyglot/rust.md#workflow-logging); інші binding зберігають окремо документовані контракти. +Рушій відтворює workflow з його історії щоразу, коли той пробуджується, тож звичайний виклик логування в коді workflow записується повторно для кожного завершеного кроку. Workflow із 50 кроками записує свій перший рядок 50 разів. Натомість використовуйте логер, що враховує replay. Він пише лише тоді, коли код виконується вперше. Логери вбудованих workflow, PHP SDK і Rust також додають до кожного рядка ідентичність запуску: -Журналювання — це спостереження процесу. Довговічні команди workflow мають бути незалежними від спостережень replay-state та доставки журналу. Навіть logger з урахуванням replay може повторити повідомлення незафіксованої спроби після збою чи retry; це не outbox із гарантією exactly-once. Обробники хоста мають бути обмеженими й неблокувальними, щоб журналювання не затримувало worker. Довговічні бізнес-ефекти розміщуйте у відповідній activity або записаній операції workflow. +- Вбудовані workflow (Workflow 2.42.0 або новіший): `$this->logger()` повертає PSR-3 логер, що пише через логер Laravel або через переданий канал, як-от `$this->logger('workflow')`. Кожен рядок містить `workflow_instance_id`, `workflow_run_id`, `workflow_type` і `namespace`. `$this->replayState()` повертає `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` або `Unavailable`), а `$this->isReplaying()` — його булеву форму. +- PHP SDK: `$context->logger()` пише через PSR-3 логер `Worker`. Див. [посібник PHP SDK](../polyglot/php.md#workflow-logging). +- Rust SDK: `ctx.logger()`. Див. [логер workflow у Rust SDK 4.17](../polyglot/rust.md#workflow-logging). +- Python SDK: `ctx.logger`, який мовчить під час replay, але не додає ідентичності запуску. + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +Query і валідатори update ніколи не логують, бо завжди є replay. + +У вбудованих workflow рядки записуються після фіксації транзакції бази даних задачі workflow, тож задача, яку відкочено, нічого не пише. Код, що чекає на незавершеному дескрипторі `select()` без запису кроку, логує один раз — у задачі, яка проходить це очікування. Рядки з обробника update, виконаного наживо, записуються, коли update застосовано. У PHP SDK рядки записуються після того, як Server прийме задачу workflow; див. [посібник PHP SDK](../polyglot/php.md#workflow-logging). + +Логування — це спостереження за процесом. Тримайте довговічні команди workflow незалежними від спостережень за станом replay і від доставки логів. Логер, що враховує replay, не є exactly-once outbox: якщо вбудований worker або worker PHP SDK завершиться між фіксацією чи прийняттям і записом, ці рядки буде втрачено, а логер Rust може повторити повідомлення з незафіксованої спроби після збою чи повтору. Тримайте обробники хоста обмеженими й неблокувальними, щоб логування не зупиняло worker. Розміщуйте довговічні бізнес-ефекти у відповідній activity або записаній операції workflow. ## Перевірки під час запуску застосунку {#boot-time-guardrails} diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/uk/docusaurus-plugin-content-docs/current/features/updates.md index 29a1e40f50e..e8b7f18a688 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ Update дають змогу одночасно отримати інформа - Використовує оголошену стійку назву update в історії команд і маршрутизації webhook. `#[UpdateMethod('mark-approved')]` зберігає публічну назву виклику за перейменування PHP-методу. - Відхиляється для історичних або вже закритих запусків замість непомітної зміни поточного запуску. - До виконання обробника відхиляє неоголошені назви методів як `rejected_unknown_update`, а аргументи, що порушують контракт, як `rejected_invalid_arguments` із машиночитаними `validation_errors`. +- Відхиляє як `update_validator_rejected` ще до прийняття запит, який відхиляє ваш [валідатор update](#validate-updates-before-acceptance). Як і query, update спочатку відтворюють зафіксовану історію. На відміну від query, update можуть змінювати безпечний щодо replay стан workflow і повертати значення. @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` не очікує на виконання workflow. Він повторно завантажує збережений стійкий життєвий цикл і повертає поточний `UpdateResult`. +## Валідація update до прийняття {#validate-updates-before-acceptance} + +Без валідатора update, що порушує бізнес-правило, спочатку приймається, а потім завершується помилкою. Він записується як невдалий update, і викликач не може відрізнити хибний запит від невдалої операції. Оголосіть валідатор, щоб відхилити запит ще до прийняття. Валідатори потребують Workflow 2.42.0 або новішої версії. + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` вказує update за його довговічним іменем або за іменем методу, якщо update не має псевдоніма. Валідатор отримує ті самі аргументи, що й update. Перед прийняттям update рушій відновлює стан запуску з його історії та викликає лише валідатор: + +- Якщо він завершується звичайно, update приймається й застосовується як завжди. +- Якщо він кидає виняток або повертає `false`, update відхиляється з причиною `update_validator_rejected` і результатом `rejected_invalid_arguments`. `rejectedByValidator()` повертає true, `rejectionMessage()` повертає повідомлення винятку, а `validationErrors()` повертає помилки Laravel `ValidationException`. `update()` кидає `LogicException`, що містить причину й повідомлення валідатора. +- Відхилений update ніколи не приймається, його обробник ніколи не виконується, і workflow не пробуджується. Як і будь-яке інше відхилення, він записується лише як аудиторська подія `UpdateRejected`, яку replay ігнорує. + +Валідатори доступні лише для читання. Вони можуть читати відновлений стан workflow, але будь-який довговічний виклик (activity, timer, дочірній workflow, signal, side effect, `await`, `getVersion()`, `patched()`, continue-as-new або upsert memo чи атрибутів пошуку) кидає `UpdateValidatorCommandException` і відхиляє update. Зміни, які валідатор вносить у відновлений стан, відкидаються. Валідатор-генератор відхиляється, бо його тіло ніколи не виконується. + +Валідатори не записуються в історію й ніколи не виконуються під час replay, тож не впливають на детермінізм. Вони бачать стан із зафіксованої історії: update, який уже прийнято, але ще не застосовано, для них невидимий. Replay і валідатор виконуються, поки прийняття update утримує блокування запуску, тому валідатори мають бути швидкими. + +Якщо стан не вдається відновити або валідатор натрапляє на помилку бази даних, кидається `UpdateValidationFailedException` і нічого не записується. Webhook-маршрути update відповідають на це повторюваним `503` з `update_validation_failed`. Повторіть запит із тим самим ідентифікатором запиту. + +Повторний запит із ключем для відхиленого update повертає збережене відхилення без повторного виконання валідатора. + +Interceptor-и worker обгортають валідацію update через `executeUpdateValidation()`. Вони бачать рішення валідатора, але не можуть його змінити. + ## Відновлення після невизначеної відповіді {#recover-after-an-uncertain-response} Durable-приймання, завершення обробника й зовнішній бізнес-ефект є окремими 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 d1f4fa72f14..225c441b2c4 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -154,6 +154,66 @@ Bootstrap звільняє користувача від вибору шляху та `registerUpdate`. Повні параметри й типи результатів наведено у [згенерованому довіднику PHP SDK API](https://php.durable-workflow.com/api/). +## Валідатори update {#update-validators} + +Починаючи з PHP SDK 3.32.0, workflow може відхилити update ще до його прийняття. Додайте `#[UpdateValidator]` до методу класу workflow поруч з його обробником `#[Update]`. Низькорівнева форма — `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, яку викликають після `registerUpdate()`. + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +Валідатор отримує `QueryContext` із зафіксованою історією запуску, а за ним — аргументи update. Worker оголошує валідатор Server і опитує задачі workflow та валідації update разом. Реєстрацію відхилено з `update_validation_tasks_unavailable`, якщо Server не оголошує синхронну валідацію update. Для кожної задачі валідації worker виконує лише валідатор: + +- Якщо він завершується звичайно, він схвалює update, і Server його приймає. +- Якщо він кидає виняток або повертає `false`, update відхиляється з `update_validator_rejected`, повідомленням і класом винятку та помилками полів із методу `errors()` винятку. Update ніколи не приймається, і його обробник ніколи не виконується. Server записує відхилення лише як аудиторську подію `UpdateRejected`. +- Спробу запланувати довговічну роботу відхилено з `UpdateValidatorCommandRefused`, що відхиляє update. + +На клієнті `updateWorkflow()` кидає `UpdateFailed`. `rejectedByValidator()` визначає відхилення валідатором, а `validationErrors()` повертає його помилки полів. `validationFailed()` повертає true, коли Server не зміг вчасно отримати рішення; нічого не прийнято, тож повторіть запит із тим самим ідентифікатором. + +Валідатори ніколи не виконуються під час replay. Кожна валідація бачить лише історію, зафіксовану до її власної задачі, тож дві одночасні валідації можуть обидві пройти перевірку, яку мала б пройти лише одна. Worker із валідаторами не використовує перенесені опитування workflow. Interceptor-и worker обгортають задачі валідації update через `executeUpdateValidation()`; вони бачать рішення валідатора, але не можуть його змінити. + +## Логування workflow з урахуванням replay {#workflow-logging} + +Worker відтворює workflow з історії в кожній задачі workflow, тож звичайний виклик логування в коді workflow повторюється для кожного завершеного кроку. PHP SDK 3.32.0 і новіші надають `$context->logger()`. Він повертає PSR-3 логер, що пише через логер, переданий у `Worker` (іменований аргумент `logger`), і лише тоді, коли код виконується за межами зафіксованої історії запуску: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +Кожен рядок містить `namespace`, `workflow_type`, `workflow_id` і `workflow_run_id`. `$context->replayState()` повертає `WorkflowReplayState::Replaying`, `Executing` або `Unavailable`, а `isReplaying()` — його булеву форму. Використовуйте їх лише для діагностики; ніколи не обирайте команди workflow на їхній основі. + +Рядки записуються лише після того, як Worker надішле задачу workflow, що виконала код, і Server її прийме. Замінений replay, спекулятивний replay, який Server відхилив, і відхилене завершення нічого не пишуть. Код, що чекає на незавершеному дескрипторі дочірнього workflow чи операції без запису кроку, логує один раз — у задачі, яка проходить це очікування. Виклик `logger()` усередині замикання side effect нічого не пише. + +Якщо worker завершиться між прийняттям Server і записом, ці рядки буде втрачено. Це логер процесу, а не outbox для бізнес-ефектів. Тримайте обробники логів швидкими й неблокувальними: обробник, що чекає на мережу, зупиняє worker і може коштувати йому оренди задачі. Збої логера перехоплюються й ніколи не змінюють команди workflow. + ## Контекст повторних спроб і вихідний запуск активності {#activity-retry-context} PHP SDK **3.6.1 або новіший** надає `$context->retryInfo`, `$context->workflowId` і `$context->runId` в активностях у сервісному режимі. Перевірка `$context->retryInfo->isLastConfiguredAttempt() === true` визначає останню налаштовану спробу політики з обмеженням кількості спроб. `attemptNumber` зберігає початковий отриманий номер спроби. 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 28c0c61b9ca..1b697e785c5 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -974,6 +974,46 @@ Workers реєструють іменовані обробники через `W з результатом. Він відрізняється від signals без очікування відповіді та read-only queries із replay. +### Валідатори update {#update-validators} + +Починаючи з Rust SDK 4.25.0, worker може відхилити update ще до його прийняття. +Зареєструйте валідатор через `Worker::register_update_validator` після +обробника update з тим самим іменем: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` приймає значення Avro. Валідатор із +відновленим станом, `register_replayed_update_validator::`, читає від'єднану +копію відновленого стану workflow; він має використовувати той самий тип стану, +що й відновлений workflow. Worker оголошує валідатор, відхиляє реєстрацію, якщо +Server не оголошує синхронну валідацію update, і опитує задачі workflow та +валідації update разом. Для кожної задачі валідації він виконує лише валідатор: + +- `Ok(())` схвалює update, і Server його приймає. +- `UpdateRejection` відхиляє його з `update_validator_rejected`, повідомленням, + типом і помилками валідації. Update ніколи не приймається, і його обробник + ніколи не виконується. Server записує відхилення лише як аудиторську подію + `UpdateRejected`. +- Валідатор, що додає команду workflow, відхиляється з + `UpdateValidatorCommandRefused`, а panic чи збій replay повідомляє + `update_validation_worker_failed`. + +На клієнті `Error::update_validator_rejection()` повертає повідомлення, помилки +валідації та ідентифікатори відхилення, а `Error::is_update_validation_failed()` +охоплює тайм-аути та збої worker. Звичайний невдалий update не відповідає жодному +з них. Валідатори ніколи не виконуються під час replay. Interceptor-и worker обгортають +задачі валідації update через `execute_update_validation_task`; вони бачать +рішення валідатора, але не можуть його змінити. + ## Оболонка payload {#payload-envelope} Вхідні дані workflow, signals, activities, queries та результати diff --git a/i18n/uk/source-hashes.json b/i18n/uk/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/uk/source-hashes.json +++ b/i18n/uk/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "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/constraints/workflow-constraints.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md index d1c8dc12837..a0a318d1b5a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/constraints/workflow-constraints.md @@ -17,9 +17,35 @@ description: 保持重放的确定性,并在应用启动时发现不安全的 ## 从 workflow 代码记录日志 {#workflow-logging} -worker 在激活和冷替换后重建已提交的 workflow 历史,因此普通应用日志可能重复先前的消息。若对应 binding 提供了已文档化的重放感知 logger,请使用该接口。Rust 服务模式提供 [Rust SDK 4.17 workflow logger](../polyglot/rust.md#workflow-logging);其他 binding 保留各自文档中的契约。 +引擎每次唤醒工作流时都会从历史中重放它,因此工作流代码中的普通日志调用会在每个已完成的步骤中再次写入。一个有 50 个步骤的工作流会把第一行日志写 50 次。请改用感知重放的日志记录器。它只在代码首次运行时写入。嵌入式工作流、PHP SDK 和 Rust 的日志记录器还会在每一行中加入运行的标识: -日志是进程观测。持久 workflow 命令应独立于重放状态观测和日志投递。即使使用重放感知 logger,未提交尝试的消息也可能在崩溃或 retry 后重复;它不是 exactly-once outbox。主机 handler 应有界且非阻塞,避免日志阻塞 worker。应通过合适的 activity 或有记录的 workflow 操作执行持久业务效果。 +- 嵌入式工作流(Workflow 2.42.0 或更高版本):`$this->logger()` 返回一个 PSR-3 日志记录器,它通过 Laravel 日志记录器或你传入的通道写入,例如 `$this->logger('workflow')`。每一行都包含 `workflow_instance_id`、`workflow_run_id`、`workflow_type` 和 `namespace`。`$this->replayState()` 返回 `Workflow\V2\Enums\WorkflowReplayState`(`Replaying`、`Executing` 或 `Unavailable`),`$this->isReplaying()` 是其布尔形式。 +- PHP SDK:`$context->logger()` 通过 `Worker` 的 PSR-3 日志记录器写入。参见 [PHP SDK 指南](../polyglot/php.md#workflow-logging)。 +- Rust SDK:`ctx.logger()`。参见 [Rust SDK 4.17 工作流日志记录器](../polyglot/rust.md#workflow-logging)。 +- Python SDK:`ctx.logger`,它在重放期间保持静默,但不会加入运行的标识。 + +```php +use function Workflow\V2\activity; +use Workflow\V2\Workflow; + +final class ShipOrderWorkflow extends Workflow +{ + public function handle(string $orderId): string + { + $this->logger()->info('Shipping started', ['order_id' => $orderId]); + $label = activity(PrintLabelActivity::class, $orderId); + $this->logger()->info('Label printed', ['label' => $label]); + + return $label; + } +} +``` + +查询和更新验证器从不写日志,因为它们始终是重放。 + +在嵌入式工作流中,日志行会在工作流任务的数据库事务提交之后写入,因此回滚的任务不会写入任何内容。在未记录步骤的情况下等待某个挂起的 `select()` 句柄的代码只记录一次,由越过该等待的任务写入。实时运行的更新处理程序中的日志行会在更新被应用时写入。在 PHP SDK 中,日志行会在 Server 接受工作流任务之后写入;参见 [PHP SDK 指南](../polyglot/php.md#workflow-logging)。 + +日志是对进程的观察。请让持久的工作流命令独立于重放状态的观察和日志投递。感知重放的日志记录器不是 exactly-once outbox:如果嵌入式或 PHP SDK 的 Worker 在提交或接受与写入之间终止,这些日志行会丢失;而 Rust 日志记录器在崩溃或重试后可能会重复来自未提交尝试的消息。请让宿主处理程序有界且非阻塞,以免日志阻塞 Worker。请把持久的业务效果放在合适的活动或已记录的工作流操作中。 ## 启动时检查 {#boot-time-guardrails} diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/features/updates.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/features/updates.md index 341980872cf..c9e19120db1 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/features/updates.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/features/updates.md @@ -14,6 +14,7 @@ sidebar_position: 3 - 在命令历史和 Webhook 路由中使用声明的持久更新名称。`#[UpdateMethod('mark-approved')]` 使公开可调用名称在 PHP 方法重命名后仍保持稳定。 - 拒绝针对历史运行或已关闭运行的请求,不会悄然修改当前运行。 - 在处理器运行前,将未声明方法名以 `rejected_unknown_update` 拒绝,将不符合契约的参数以 `rejected_invalid_arguments` 拒绝,并提供机器可读的 `validation_errors`。 +- 在接受之前,把被你的[更新验证器](#validate-updates-before-acceptance)拒绝的请求作为 `update_validator_rejected` 拒绝。 更新与查询一样,先重放已提交历史。与查询不同,更新允许修改可安全重放的工作流状态,并返回一个值。 @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes `inspectUpdate()` 不等待工作流执行。它重新加载已存储的持久生命周期,并返回当前 `UpdateResult`。 +## 在接受之前验证更新 {#validate-updates-before-acceptance} + +如果没有验证器,违反业务规则的更新会先被接受,然后才失败。它会被记录为失败的更新,调用方无法区分错误的请求和失败的操作。声明一个验证器,即可在接受之前拒绝该请求。验证器需要 Workflow 2.42.0 或更高版本。 + +```php +use Workflow\UpdateMethod; +use Workflow\UpdateValidator; +use Workflow\V2\Workflow; + +final class CartWorkflow extends Workflow +{ + private array $items = []; + + #[UpdateMethod('add-item')] + public function addItem(string $item): array + { + $this->items[] = $item; + + return $this->items; + } + + #[UpdateValidator('add-item')] + public function validateAddItem(string $item): void + { + if (count($this->items) >= 10) { + throw new \RuntimeException('The cart is full.'); + } + } +} +``` + +`#[UpdateValidator]` 通过持久名称指定更新;如果更新没有别名,则使用其方法名。验证器接收与更新相同的参数。在接受更新之前,引擎会从历史中重建运行的状态,并且只调用验证器: + +- 正常返回时,更新会照常被接受并应用。 +- 抛出异常或返回 `false` 时,更新会以原因 `update_validator_rejected` 和结果 `rejected_invalid_arguments` 被拒绝。`rejectedByValidator()` 为 true,`rejectionMessage()` 返回异常消息,`validationErrors()` 返回 Laravel `ValidationException` 的错误。`update()` 会抛出包含原因和验证器消息的 `LogicException`。 +- 被拒绝的更新永远不会被接受,其处理程序永远不会运行,工作流也不会被唤醒。与其他拒绝一样,它只被记录为审计事件 `UpdateRejected`,重放会忽略该事件。 + +验证器是只读的。它们可以读取重建后的工作流状态,但任何持久调用(活动、定时器、子工作流、信号、side effect、`await`、`getVersion()`、`patched()`、continue-as-new,或 memo、搜索属性的 upsert)都会抛出 `UpdateValidatorCommandException` 并拒绝更新。验证器对重建状态所做的修改会被丢弃。生成器形式的验证器会被拒绝,因为它的函数体永远不会执行。 + +验证器不会记录到历史中,也不会在重放时运行,因此不影响确定性。它们看到的是已提交历史中的状态:已接受但尚未应用的更新对它们不可见。重放和验证器会在更新准入持有运行锁期间执行,因此请让验证器保持快速。 + +如果无法重建状态,或验证器遇到数据库错误,会抛出 `UpdateValidationFailedException`,并且不会记录任何内容。更新的 webhook 路由会以可重试的 `503` 和 `update_validation_failed` 响应。请使用同一个请求 ID 重试。 + +对被拒绝的更新使用相同键重试时,会返回保留的拒绝结果,而不会再次运行验证器。 + +Worker 拦截器通过 `executeUpdateValidation()` 包裹更新验证。它们能看到验证器的决定,但无法更改。 + ## 响应不确定后的恢复 {#recover-after-an-uncertain-response} 持久接收、处理器完成和外部业务效果是独立的事实。调用方超时后,已接受的更新可能仍在运行;响应丢失也可能掩盖已经提交的结果。之后重新提交更新被拒绝,并不能确定原操作的结果。 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 95b5910e3d3..c36e946e344 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 @@ -89,6 +89,66 @@ SDK 维护的快速入门创建干净的 Composer 项目,定义带特性的工 远程 Worker 通过 `registerWorkflow`、`registerActivity`、`registerQuery` 和 `registerUpdate` 注册工作流、活动、查询及更新处理器。完整参数及返回类型见生成的 [PHP SDK API 参考](https://php.durable-workflow.com/api/)。 +## 更新验证器 {#update-validators} + +从 PHP SDK 3.32.0 起,工作流可以在接受更新之前拒绝它。在工作流类的方法上、紧挨其 `#[Update]` 处理程序添加 `#[UpdateValidator]`。底层形式是 `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`,需在 `registerUpdate()` 之后调用。 + +```php +use DurableWorkflow\Attribute\Update; +use DurableWorkflow\Attribute\UpdateValidator; +use DurableWorkflow\Worker\QueryContext; + +final class OrderWorkflow +{ + #[Update('approve')] + public function approve(QueryContext $context, int $amount): int + { + return $amount; + } + + #[UpdateValidator('approve')] + public function validateApprove(QueryContext $context, int $amount): void + { + if ($amount <= 0) { + throw new \DomainException('The amount must be positive.'); + } + } +} +``` + +验证器接收一个包含运行已提交历史的 `QueryContext`,后面跟着更新的参数。Worker 会向 Server 声明验证器,并同时轮询工作流任务和更新验证任务。如果 Server 没有声明同步更新验证,注册会以 `update_validation_tasks_unavailable` 被拒绝。对每个验证任务,Worker 只运行验证器: + +- 正常返回即批准更新,Server 随后接受它。 +- 抛出异常或返回 `false` 时,会以 `update_validator_rejected`、异常消息和类名,以及异常 `errors()` 方法返回的字段错误拒绝更新。更新永远不会被接受,其处理程序也永远不会运行。Server 只把拒绝记录为审计事件 `UpdateRejected`。 +- 尝试调度持久工作会被 `UpdateValidatorCommandRefused` 拒绝,从而拒绝该更新。 + +在客户端,`updateWorkflow()` 会抛出 `UpdateFailed`。`rejectedByValidator()` 用于识别验证器拒绝,`validationErrors()` 返回其字段错误。当 Server 未能及时得到决定时,`validationFailed()` 为 true;此时没有任何内容被接受,请使用同一个请求 ID 重试。 + +验证器从不在重放期间运行。每次验证只能看到在其自身任务之前提交的历史,因此两个同时进行的验证可能都通过一项本应只有一个通过的检查。带验证器的 Worker 不使用携带的工作流轮询。Worker 拦截器通过 `executeUpdateValidation()` 包裹更新验证任务,能看到验证器的决定,但无法更改。 + +## 感知重放的工作流日志 {#workflow-logging} + +Worker 在每个工作流任务中都会从历史重放工作流,因此工作流代码中的普通日志调用会为每个已完成的步骤重复一次。PHP SDK 3.32.0 及更高版本提供 `$context->logger()`。它返回一个 PSR-3 日志记录器,通过你传给 `Worker` 的日志记录器(命名参数 `logger`)写入,并且只在代码运行到运行的已提交历史之外时写入: + +```php +use DurableWorkflow\Worker\WorkflowContext; + +function approve(WorkflowContext $context, string $orderId): string +{ + $context->logger()->info('Approval started', ['order_id' => $orderId]); + $decision = $context->activity('review', [$orderId]); + $context->logger()->info('Review finished', ['decision' => $decision]); + + return $decision; +} +``` + +每一行都包含 `namespace`、`workflow_type`、`workflow_id` 和 `workflow_run_id`。`$context->replayState()` 返回 `WorkflowReplayState::Replaying`、`Executing` 或 `Unavailable`,`isReplaying()` 是其布尔形式。它们仅用于诊断;切勿据此选择工作流命令。 + +只有在 Worker 提交运行该代码的工作流任务并且 Server 接受之后,才会写入日志行。被取代的重放、被 Server 拒绝的推测性重放以及被拒绝的完成都不会写入任何内容。在未记录步骤的情况下等待挂起的子工作流或操作句柄的代码只记录一次,由越过该等待的任务写入。在 side effect 闭包内调用 `logger()` 不会写入任何内容。 + +如果 Worker 在 Server 接受与写入之间终止,这些日志行会丢失。这是一个进程日志记录器,而不是用于业务效果的 outbox。请让日志处理程序保持快速且非阻塞:等待网络的处理程序会阻塞 Worker,并可能使其丢失任务租约。日志记录器的失败会被捕获,绝不会改变工作流的命令。 + ## 活动重试上下文与所属运行 {#activity-retry-context} PHP SDK **3.6.1 及以上版本**在服务模式活动中提供 `$context->retryInfo`、`$context->workflowId` 和 `$context->runId`。对于有次数上限的策略,使用 `$context->retryInfo->isLastConfiguredAttempt() === true` 判断是否已到达配置的最后一次尝试。`attemptNumber` 保留最初收到的尝试编号。 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 7a474167c1f..17edcd5ec7a 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 @@ -748,6 +748,29 @@ Rust 在应用客户端、选定句柄及 Worker 编写角色中均支持持久 Worker 用 `Worker::register_update` 注册具名处理器;处理器直接消费和返回 Avro 值时,使用 `register_update_avro_value`。更新是持久的、带结果的工作流变更,区别于发送后无需等待的信号和只读的经重放查询。 +### 更新验证器 {#update-validators} + +从 Rust SDK 4.25.0 起,Worker 可以在接受更新之前拒绝它。在同名的更新处理程序之后,使用 `Worker::register_update_validator` 注册验证器: + +```rust,ignore +worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) }); +worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| { + if args[0].as_u64() == Some(0) { + return Err(UpdateRejection::new("amount must be positive") + .with_validation_error("amount", "must be positive")); + } + Ok(()) +}); +``` + +`register_update_validator_avro_value` 接收 Avro 值。基于重放状态的验证器 `register_replayed_update_validator::` 读取工作流重放状态的一份分离副本;它必须使用与被重放工作流相同的状态类型。Worker 会声明验证器,在 Server 未声明同步更新验证时拒绝注册,并同时轮询工作流任务和更新验证任务。对每个验证任务,它只运行验证器: + +- `Ok(())` 批准更新,Server 随后接受它。 +- `UpdateRejection` 以 `update_validator_rejected`、消息、类型和验证错误拒绝更新。更新永远不会被接受,其处理程序也永远不会运行。Server 只把拒绝记录为审计事件 `UpdateRejected`。 +- 添加工作流命令的验证器会被 `UpdateValidatorCommandRefused` 拒绝;panic 或重放失败会报告 `update_validation_worker_failed`。 + +在客户端,`Error::update_validator_rejection()` 返回拒绝的消息、验证错误和 ID,`Error::is_update_validation_failed()` 涵盖超时和 Worker 失败。普通的失败更新不匹配这两者中的任何一个。验证器从不在重放期间运行。Worker 拦截器通过 `execute_update_validation_task` 包裹更新验证任务,能看到验证器的决定,但无法更改。 + ## 负载封装 {#payload-envelope} 工作流输入、信号、活动、查询及结果使用已发布的 `PayloadEnvelope` 契约:`codec` 加编码后的 `blob`。SDK 默认的 `avro` 路径使用其声明的 `apache-avro` 依赖及平台固定的带版本 Value 模式;不要手工拼装 blob,也不要用实现专有记录替换封装。 diff --git a/i18n/zh-Hans/source-hashes.json b/i18n/zh-Hans/source-hashes.json index a51e85dc5c4..90559b47a95 100644 --- a/i18n/zh-Hans/source-hashes.json +++ b/i18n/zh-Hans/source-hashes.json @@ -18,7 +18,7 @@ "constraints/idempotent-vs-deterministic.md": "f7396f01a4111ce187e751b009c1efb96f5538e8a602006eed24f7b1d8f44adf", "constraints/overview.md": "fd6c842c6c22d6f0df37a52de15ca74b34664f5ecd78af0c08b1e0cdb9a2be1f", "constraints/structural-limits.md": "5c7b7f6c86c5ca547eb3f200400ceab3b589f32d83866914f44e3a5a7d81e964", - "constraints/workflow-constraints.md": "f6c734fdacf78b599f60ff2d2b6ee70ae3ff4001539fb55ac1cfa168673b21a7", + "constraints/workflow-constraints.md": "33808ba0ab83184a476a6b63c2a9a80ca5a444694b67d5d821e42de808d6fd86", "contribute-a-sample.md": "d250d8c63d448e32d3160ff7a2900e7a270dcbd9cda22cf3af46cdf219395ea3", "conversational-workflows.md": "d155b4af3d83293802cfa765bb28de7b3fc52345509f4f3d02e16318d825a675", "defining-workflows/activities.md": "05b46f73477a0bbd5f21d17ac37def8a8eac53f1e629155805c98cc46e75b418", @@ -55,7 +55,7 @@ "features/sticky-execution.md": "d54fe85283d633d5cba10a03c716a707bf3b6a4e6d47ec9859e17f5f676a89b8", "features/timeouts.md": "c0d2d4108b195d10a759a4cc5368e0d13a48bde4a46005601ec15d58198f409a", "features/timers.md": "8ef45889325eb3358dd7c894511dfbd647e2813fd2eb368069f17d56c90a5d27", - "features/updates.md": "eda79f320ab6aaa5379f0638b77cb3c2d782869a97fac7883b1b8519a89a524a", + "features/updates.md": "37866ab321b74be259604d4b451fdec97df808c6036f5fcf550ad106142ae981", "features/versioning.md": "7f9d97fab5811167c00fcb8b0be76bcb6bc402cbb5949a770878e098d0a7785e", "features/webhooks.md": "edcdfc05ccb0d34a77c51594f85bc3cab343e787f8e0e08d2cd4ddebd048e8c8", "features/worker-sessions.md": "5065368fb5b93599dbd08d97cb9ac312576eb42fee14f081db663aa9f78fb68c", @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "debb0495b1d28ec4c7f2f754f30df9a099bc83b3d350f0b8bf188633794caf8c", + "polyglot/php.md": "ba69ff091bbc66e20357229409ff8e28e6ea920a463e2590b024a91e242d1b3f", "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": "ce974509c5524ab9d524bc5671cc70030dd8267a54aa97370cc9803e2e1c1db6", + "polyglot/rust.md": "9b865fd59a57b2f4dba7fe15b63559ac43ba56b7286cbe95878062182dfe8844", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2",