# effect-workflows ## What it teaches Combine XState's approval, deadlines, cancellation and retry with Effect's services, streams and resource management. These are the complete examples used by the [XState Effect guides](../../packages/xstate-effect/docs/quick-start.md). ## XState features used Parallel states, invoked actors, delayed transitions, typed input and events, emitted events, actor inspection and React subscriptions. Effect and its atom integration provide services, scoped resources and reactive consumers. ## Run it From the repository root: ```bash pnpm install pnpm --filter @xstate/example-effect-workflows start pnpm typecheck:examples effect-workflows pnpm --filter @xstate/example-effect-workflows test ``` The command runs `inspection.ts`, a local approval and publishing workflow. Services and streams are demos; no credentials or external APIs are needed. ## Inspect it ```bash INSPECT=1 pnpm --filter @xstate/example-effect-workflows start INSPECT=1 pnpm --filter @xstate/example-effect-workflows exec tsx src/custom-actions.ts ``` `@statelyai/sdk` opens the Stately inspector and sends machine definitions, snapshots and events to its hosted relay. Both `src/inspection.ts` and `src/custom-actions.ts` subscribe and wait for the inspector before sending events, then close it when their scopes end. Without the flag they run locally. ## Examples - `approval.ts`: approval, deadlines, cancellation and explicit retry. - `actor-service.ts`: an actor shared through a Layer and ManagedRuntime. - `observe.ts`, `emitted.ts` and `inspection.ts`: state history, final output, reminders and visual inspection. - `task.ts`, `latest-stream.ts` and `event-stream.ts`: tasks, upload progress and rollout health events. - `matching.ts` and `parallel.ts`: exhaustive state matching and parallel regions. - `actions.ts`, `custom-actions.ts` and `provided-actions.ts`: runtime schema validation, typed action arguments, background audits and service requirements after overrides. - `resources.ts`: invocation cleanup and resources retained with `withActorScope`. - `atoms.ts`, `input-atoms.ts`, `react.tsx` and `selector.tsx`: atom ownership, required input and React consumers. - `clock.ts`, `retry.ts`, `supervision.ts`, `errors.ts` and `failure-cause.ts`: deadlines, retries, typed failures and Cause inspection. - `boundaries.ts`: decode external input and events before synchronous validation. - `persistence.ts` and `persistence-codec.ts`: causal event receipts and schema-backed snapshots with rich values. - `cluster.ts`: a checkpoint-backed workflow hosted by an Effect Cluster entity. Run individual `.ts` examples with `pnpm --filter @xstate/example-effect-workflows exec tsx src/clock.ts`. The React components are exercised by the React tests. ## Effect Cluster workflow Each `ClusterWorkflow` entity runs one job, invokes an Effect, and waits one second before completing. It uses `xstate/durable` for transitions, checkpoints, and restored timers. Submit `Run` to enable automatic recovery with persistent Cluster message storage. Pass `{ discard: true }` to submit without waiting for the result. ```ts const client = yield* ClusterWorkflow.client; yield* client(jobId).Run({ requestId }, { discard: true }); ``` Cluster keeps the request pending until the terminal checkpoint commits. If the worker dies, the runner that takes over the shard receives the pending request and restores the job. An interrupted Effect can run again with the same job ID. Use that ID as the idempotency key for external writes. A restored timer uses its original deadline and fires on reactivation if that deadline has passed. The `completion` delay name stays the same across workers. Old checkpoints with a numeric timer key are migrated when loaded, preserving the deadline. Supply a `WorkflowStore` that commits the checkpoint and accepted request ID in one compare-and-swap write. The entity commits the active invocation before running the Effect. A different request ID is rejected once a job starts. `Start(requestId)` returns the state without waiting for completion. A replay can return the saved response. Use `Get()` to read the current state. ### Let a long timer wake an idle workflow Implement `WorkflowStore.commitWithWake` to write the checkpoint and the delayed Cluster message in the same SQL transaction. Run the supplied `saveWake` Effect inside the transaction using the same SQL client as Cluster message storage. Timers longer than `durableTimerThreshold` (60,000 ms by default) then use Cluster delivery and can wake an evicted entity on any runner that owns its shard. Delivery may lag the deadline by the storage poll interval while a runner is available. Deploy the entity schema with the `Wake` RPC to every runner before enabling `commitWithWake`. An older runner does not recognize that persisted message and can record a terminal failure instead of leaving it for an upgraded runner. The delayed message uses a wall-clock deadline. When the workflow uses a custom clock, the adapter converts the timer's remaining duration to that wall clock when it commits the wake-up. Submit with `Start` when the workflow should leave memory during the wait. `Run` keeps its request pending for the terminal reply. A crash before `Start` commits a durable timer still requires a request to resume. Short timers use the runner's clock. Pass `inspect` to `workflowLayer` to forward the durable actor tree to a Stately inspector. `ChangeTimer({ action: 'cancel' })` ends the workflow in `cancelled`. `ChangeTimer({ action: 'replace' })` starts a fresh wait. Both commands apply only while waiting. Delayed messages for superseded timers are acknowledged without changing the checkpoint. The integration tests use an in-process runner for duplicate delivery and checkpoint failures. The process tests share one SQLite database for Cluster messages and workflow checkpoints. They kill the first worker during an Effect or while the timer is pending. Timer recovery uses a different delay on the replacement worker and covers both named and legacy numeric keys. The tests read the terminal reply for the original `Run` request from Cluster storage. A separate case verifies eviction before the first worker stops, automatic delivery on its replacement, and ignored wake-ups for canceled and replaced timers. ```bash pnpm --filter @xstate/example-effect-workflows test cluster ``` ## Host an approval machine on Effect Cluster `cluster-host.ts` adapts an XState machine to a Cluster entity. Supply Effect Schema codecs for startup input and events, and a schema for the workflow output. `cluster-approval.ts` defines a machine with typed approval and a delayed completion. Register its `toLayer()` on each runner. Provide `clusterCheckpointSqlLayer` with the same SQL client as Cluster message storage so a checkpoint, request receipt, and timer wake-ups commit together. ```ts const host = approvalHost(); const workflow = yield* host.client; const approval = workflow('approval-1'); yield* approval.start({ reviewId: 'review-7' }); yield* approval.send('approve-1', { type: 'APPROVE', reviewer: 'Ada' }); ``` `start` and `send` return the committed revision. Reuse the same request ID when retrying a send. An accepted send returns its original revision on retry. A rejected send can be retried after its cause is resolved, for example after the workflow starts. Set a machine version and migrate stored checkpoints before changing that version on a running workflow. `host.read('approval-1')` needs only checkpoint storage. Use `snapshot` for the latest checkpoint, `changes` to poll for new revisions, or `join` to wait for the workflow output. Polling may skip intermediate revisions. These reads leave the entity idle. A persisted timer message wakes the current shard owner when the timer is due. This host supports root transitions and root timers. Store JSON-serializable context and output. Invoked and spawned actors, external sends, emits, and custom actions fall outside this host. The preceding example covers an interrupted invoked Effect. ## Update an example Edit and format the source, then run `pnpm --filter @xstate/example-effect-workflows docs:sync`. Tests compare every guide's TypeScript block with its runnable source, verify documented results and cover approval expiry, retry, interruption, inspector cleanup and React interactions. The root Vitest configuration includes this suite.