From 32f80c2f15bccb5ccb435841add310a2e7fe8f5c Mon Sep 17 00:00:00 2001 From: SandroMaglione Date: Wed, 25 Nov 2026 19:02:32 +1300 Subject: [PATCH] Add ClusterMachine shardGroup, Entity.toLayer options, and transactional onCommit --- .changeset/cluster-entity-options.md | 9 + LLMS.md | 14 +- ai-docs/src/35_cluster/index.md | 14 +- .../src/internal/machine/cluster.ts | 113 ++++++- .../src/internal/machine/clusterInstance.ts | 66 +++- .../src/unstable/cluster/ClusterMachine.ts | 103 +++++- .../cluster/ClusterMachineOptions.test.ts | 294 ++++++++++++++++++ .../cluster/SqlMachineStorage.test.ts | 74 +++++ .../unstable/cluster/ClusterMachine.tst.ts | 33 +- 9 files changed, 677 insertions(+), 43 deletions(-) create mode 100644 .changeset/cluster-entity-options.md create mode 100644 packages/effect-machine/test/unstable/cluster/ClusterMachineOptions.test.ts diff --git a/.changeset/cluster-entity-options.md b/.changeset/cluster-entity-options.md new file mode 100644 index 0000000..a306a51 --- /dev/null +++ b/.changeset/cluster-entity-options.md @@ -0,0 +1,9 @@ +--- +"@typeonce/effect-machine": minor +--- + +Expose Cluster `Entity` tuning options, `shardGroup` routing, and a transactional `onCommit` hook on `ClusterMachine`. + +- `ClusterMachine.make` now accepts an optional `shardGroup?: (entityId: EntityId) => string` option, annotating both the entity and any invoked child entities with `ClusterSchema.ShardGroup`. +- `ClusterMachine.toLayer` now accepts `LayerOptions`, forwarding Effect Cluster's `Entity.toLayer` options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`, `disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and its children. +- Added `LayerOptions.onCommit` and `CommitEvent`, which run inside the same `MessageStorage` transaction immediately after each checkpoint commit (active, done, or failed) so SQL read-model projections and audit tables commit or roll back atomically with the checkpoint. diff --git a/LLMS.md b/LLMS.md index 1536609..1eeaa90 100644 --- a/LLMS.md +++ b/LLMS.md @@ -1668,7 +1668,19 @@ const InvoiceLive = Invoice.toLayer().pipe( `version` is stored with every checkpoint. A checkpoint written by another definition id or version is refused, so change it together with a migration of -the stored checkpoints. +the stored checkpoints. Pass `shardGroup` to `ClusterMachine.make` to route +entities (and their invoked child entities) to named Cluster shard groups. + +`adapter.toLayer(options)` forwards standard Effect Cluster `Entity.toLayer` +options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`, +`disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and +its children. It also accepts transactional hooks that run inside the same +`MessageStorage` transaction as the checkpoint write: + +- `enqueue(event)` durably writes emitted events to an outbox table. +- `onCommit({ entityId, checkpoint, snapshot })` runs after every committed + checkpoint (active, done, failed), so SQL read-model projections or audit + tables commit or roll back atomically with the machine state. State values, completion outputs, startup input, and public input events must have JSON encoded forms. A schema that does not is a compile error that names diff --git a/ai-docs/src/35_cluster/index.md b/ai-docs/src/35_cluster/index.md index e2c7fba..0200248 100644 --- a/ai-docs/src/35_cluster/index.md +++ b/ai-docs/src/35_cluster/index.md @@ -40,7 +40,19 @@ const InvoiceLive = Invoice.toLayer().pipe( `version` is stored with every checkpoint. A checkpoint written by another definition id or version is refused, so change it together with a migration of -the stored checkpoints. +the stored checkpoints. Pass `shardGroup` to `ClusterMachine.make` to route +entities (and their invoked child entities) to named Cluster shard groups. + +`adapter.toLayer(options)` forwards standard Effect Cluster `Entity.toLayer` +options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`, +`disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and +its children. It also accepts transactional hooks that run inside the same +`MessageStorage` transaction as the checkpoint write: + +- `enqueue(event)` durably writes emitted events to an outbox table. +- `onCommit({ entityId, checkpoint, snapshot })` runs after every committed + checkpoint (active, done, failed), so SQL read-model projections or audit + tables commit or roll back atomically with the machine state. State values, completion outputs, startup input, and public input events must have JSON encoded forms. A schema that does not is a compile error that names diff --git a/packages/effect-machine/src/internal/machine/cluster.ts b/packages/effect-machine/src/internal/machine/cluster.ts index ab71b4e..cc6f0b7 100644 --- a/packages/effect-machine/src/internal/machine/cluster.ts +++ b/packages/effect-machine/src/internal/machine/cluster.ts @@ -10,10 +10,16 @@ import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" import * as Option from "effect/Option" import { Rpc } from "effect/rpc" +import type * as Schedule from "effect/Schedule" import * as Schema from "effect/Schema" import type * as Machine from "../../Machine.js" -import type { Checkpoint } from "../../unstable/cluster/ClusterMachine.js" -import type { Client, ClientError, ClusterMachine } from "../../unstable/cluster/ClusterMachine.js" +import type { + Checkpoint, + Client, + ClientError, + ClusterMachine, + LayerOptions +} from "../../unstable/cluster/ClusterMachine.js" import * as ClusterChild from "./clusterChild.js" import * as ClusterInstance from "./clusterInstance.js" import { CommitResult, Rejected, SendResult, Storage } from "./clusterProtocol.js" @@ -189,6 +195,7 @@ export const make = < options: { readonly version: string readonly readInterval?: Duration.Input | undefined + readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined }, ...input: readonly [] | [...Machine.Machine.InputArgs] ): ClusterMachine< @@ -229,6 +236,62 @@ interface Parent { readonly snapshots: boolean } +/** Entity layer tuning options forwarded to `Entity.toLayer`. */ +interface EntityLayerOptions { + readonly maxIdleTime?: Duration.Input | undefined + readonly concurrency?: number | "unbounded" | undefined + readonly mailboxCapacity?: number | "unbounded" | undefined + readonly mailboxMetrics?: boolean | undefined + readonly disableFatalDefects?: boolean | undefined + readonly defectRetryPolicy?: Schedule.Schedule | undefined + readonly spanAttributes?: Record | undefined +} + +const pickEntityLayerOptions = ( + options: LayerOptions | undefined +): EntityLayerOptions | undefined => { + if (options === undefined) return undefined + const out: { + maxIdleTime?: Duration.Input + concurrency?: number | "unbounded" + mailboxCapacity?: number | "unbounded" + mailboxMetrics?: boolean + disableFatalDefects?: boolean + defectRetryPolicy?: Schedule.Schedule + spanAttributes?: Record + } = {} + let hasAny = false + if (options.maxIdleTime !== undefined) { + out.maxIdleTime = options.maxIdleTime + hasAny = true + } + if (options.concurrency !== undefined) { + out.concurrency = options.concurrency + hasAny = true + } + if (options.mailboxCapacity !== undefined) { + out.mailboxCapacity = options.mailboxCapacity + hasAny = true + } + if (options.mailboxMetrics !== undefined) { + out.mailboxMetrics = options.mailboxMetrics + hasAny = true + } + if (options.disableFatalDefects !== undefined) { + out.disableFatalDefects = options.disableFatalDefects + hasAny = true + } + if (options.defectRetryPolicy !== undefined) { + out.defectRetryPolicy = options.defectRetryPolicy + hasAny = true + } + if (options.spanAttributes !== undefined) { + out.spanAttributes = options.spanAttributes + hasAny = true + } + return hasAny ? out : undefined +} + /** An adapter, and the adapters of the child machines that its states invoke. */ interface Built { readonly machine: Machine.Machine.Any @@ -236,9 +299,7 @@ interface Built { readonly protocol: ClusterTarget.Protocol readonly client: Effect.Effect<(entityId: string) => Client, never, Sharding.Sharding> readonly target: (entityId: string) => ClusterTarget.Target - readonly toLayer: (layerOptions?: { - readonly enqueue?: (event: any) => Effect.Effect - }) => Layer.Layer + readonly toLayer: (layerOptions?: LayerOptions) => Layer.Layer } const build = ( @@ -247,6 +308,7 @@ const build = ( options: { readonly version: string readonly readInterval?: Duration.Input | undefined + readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined }, input: ReadonlyArray, parent: Parent | undefined @@ -262,7 +324,7 @@ const build = ( // `deliver` carries an event another machine sends, `wake` is the delayed // message of a long timer, `start` and `stop` come from the parent of a // child, and `ended` and `snapshot` from a child. Only machines send them. - const entity = Entity.make(type, [ + const rawEntity = Entity.make(type, [ rpc, deliver, ClusterWake.WakeRpc, @@ -271,6 +333,9 @@ const build = ( ClusterChild.EndedRpc, ClusterChild.SnapshotRpc ]) + const entity = options.shardGroup === undefined + ? rawEntity + : rawEntity.annotate(ClusterSchema.ShardGroup, options.shardGroup) const definitionId = machine.id ?? type const publicTags: ReadonlySet = new Set(Reflect.ownKeys(machine.events)) @@ -308,25 +373,39 @@ const build = ( } const target = (entityId: string): ClusterTarget.Target => new ClusterTarget.Target(protocol, entityId) - // Each child runs as an entity of its own, with the version of its parent. + // Each child runs as an entity of its own, with the version and shard group of its parent. const snapshots = ClusterChild.snapshotsOf(toImpl(machine).handlers) const children = Array.from( ClusterChild.childrenOf(toImpl(machine).handlers), - ([childId, child]) => - [ + ([childId, child]) => { + const childShardGroup = options.shardGroup === undefined + ? undefined + : (childEntityId: EntityId.EntityId) => { + const parentId = ClusterChild.parentEntityIdOf(childEntityId, childId) + return options.shardGroup!(parentId === undefined ? childEntityId : EntityId.make(parentId)) + } + return [ childId, - build(ClusterChild.entityTypeOf(type, childId), child.machine, { version: options.version }, [], { - protocol, - childId, - snapshots: snapshots.has(childId) - }) + build( + ClusterChild.entityTypeOf(type, childId), + child.machine, + { version: options.version, shardGroup: childShardGroup }, + [], + { + protocol, + childId, + snapshots: snapshots.has(childId) + } + ) ] as const + } ) const childProtocols: ReadonlyMap = new Map( children.map(([childId, child]) => [childId, child.protocol]) ) const toLayer: Built["toLayer"] = (layerOptions) => { + const entityLayerOptions = pickEntityLayerOptions(layerOptions) // Each live entity builds its own handlers, and so owns its own instance. const layer = entity.toLayer( Effect.gen(function*() { @@ -345,6 +424,7 @@ const build = ( messageStorage, // A child has no observers, so what it emits reaches nobody. enqueue: parent === undefined ? layerOptions?.enqueue : () => Effect.void, + onCommit: parent === undefined ? layerOptions?.onCommit : undefined, keepAlive: yield* makeKeepAlive, wake: { threshold: yield* ClusterWake.threshold, @@ -382,11 +462,12 @@ const build = ( }) } return entity.of(handlers as never) - }) + }), + entityLayerOptions ) return children.length === 0 ? layer - : Layer.mergeAll(layer, ...children.map(([, child]) => child.toLayer())) + : Layer.mergeAll(layer, ...children.map(([, child]) => child.toLayer(entityLayerOptions))) } const client = Effect.gen(function*() { diff --git a/packages/effect-machine/src/internal/machine/clusterInstance.ts b/packages/effect-machine/src/internal/machine/clusterInstance.ts index d4372be..436cc5f 100644 --- a/packages/effect-machine/src/internal/machine/clusterInstance.ts +++ b/packages/effect-machine/src/internal/machine/clusterInstance.ts @@ -17,7 +17,7 @@ import * as Schedule from "effect/Schedule" import type * as Scope from "effect/Scope" import * as Semaphore from "effect/Semaphore" import type * as Machine from "../../Machine.js" -import type { Checkpoint } from "../../unstable/cluster/ClusterMachine.js" +import type { Checkpoint, CommitEvent, Snapshot as ClusterSnapshot } from "../../unstable/cluster/ClusterMachine.js" import { ChildMachineRuntime } from "./capability.js" import * as CapturedInvocation from "./capturedInvocation.js" import { isChildMachine } from "./child.js" @@ -175,6 +175,7 @@ export interface Options { readonly storage: Storage["Service"] readonly messageStorage: MessageStorage.MessageStorage["Service"] readonly enqueue: ((event: any) => Effect.Effect) | undefined + readonly onCommit?: ((event: CommitEvent) => Effect.Effect) | undefined /** `Entity.keepAlive` for the entity of the instance. */ readonly keepAlive: (enabled: boolean) => Effect.Effect /** @@ -398,7 +399,7 @@ const accepted = new Accepted({}) /** @internal */ export const make = (options: Options): Effect.Effect, never, R | Scope.Scope> => Effect.gen(function*() { - const { address, definitionId, enqueue, machine, messageStorage, storage, version } = options + const { address, definitionId, enqueue, machine, messageStorage, onCommit, storage, version } = options // Work acts on the children that run when it acts, read from memory or, // while a turn changes memory, from `Storage`. const childRuntime: ChildMachineRuntime["Service"] = { @@ -782,6 +783,31 @@ export const make = (options: Options): Effect.Effect, : [{ target: parent, tag: "snapshot", payload: { entityId: address.entityId, snapshot } }] } + const snapshotForCommit = Effect.fnUntraced(function*( + checkpoint: Checkpoint, + state: Snapshot + ): Effect.fn.Return, unknown, R> { + if (checkpoint.status._tag === "Failed") { + return { status: "failed", revision: checkpoint.revision, state, failure: checkpoint.status.failure } + } + if (checkpoint.status._tag === "Stopped") { + return { status: "stopped", revision: checkpoint.revision, state } + } + if (!internalMachine.isFinal(machine, state)) { + return { status: "active", revision: checkpoint.revision, state } + } + const output = yield* Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent) + return { status: "done", revision: checkpoint.revision, state, output } + }) + + const notifyCommit = (checkpoint: Checkpoint, state: Snapshot): Effect.Effect => + onCommit === undefined + ? Effect.void + : Effect.flatMap( + snapshotForCommit(checkpoint, state), + (snapshot) => onCommit({ entityId: address.entityId, checkpoint, snapshot }) + ) + const saveOutgoing = (outgoing: ReadonlyArray): Effect.Effect => Effect.forEach( outgoing, @@ -970,6 +996,11 @@ export const make = (options: Options): Effect.Effect, Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }) ) + // In the transaction of the checkpoint, so projections commit or roll back with it. + yield* notifyCommit(checkpoint, planned.state).pipe( + Effect.mapError((error) => reject("PersistenceFailure", String(error))), + refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }) + ) return { memory: next, stored: { @@ -994,14 +1025,15 @@ export const make = (options: Options): Effect.Effect, refuse({ memory: base, confirm: true, stage: "Decision" }) ) const revision = base.revision + 1 - const committed = yield* storage.commit(address, { + const checkpoint: Checkpoint = { definitionId, version, revision, origin: { _tag: "Request", requestId }, snapshot, status: { _tag: "Stopped" } - }).pipe( + } + const committed = yield* storage.commit(address, checkpoint).pipe( Effect.mapError(persistenceFailure), refuse({ memory: undefined, confirm: true, stage: "Infrastructure" }) ) @@ -1012,6 +1044,10 @@ export const make = (options: Options): Effect.Effect, Effect.mapError((error) => reject("PersistenceFailure", String(error))), refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }) ) + yield* notifyCommit(checkpoint, base.state).pipe( + Effect.mapError((error) => reject("PersistenceFailure", String(error))), + refuse({ memory: undefined, confirm: false, stage: "Infrastructure" }) + ) return { memory: { _tag: "Stopped", revision }, stored: undefined } }) @@ -1188,14 +1224,14 @@ export const make = (options: Options): Effect.Effect, // Makes the work and the keep-alive match the known memory. `stored` is the // step that led to it from the previous state. - const align = (restore: Restore, stored: StoredStep | undefined): Effect.Effect => + const align = (restore: Restore, stored: StoredStep | undefined): Effect.Effect => Effect.andThen( // The runner reads the events the step sent now, rather than at its next poll. stored?.sent === true && options.sends !== undefined ? options.sends.poll : Effect.void, alignStored(restore, stored) ) - const alignStored = (restore: Restore, stored: StoredStep | undefined): Effect.Effect => + const alignStored = (restore: Restore, stored: StoredStep | undefined): Effect.Effect => Effect.suspend(() => { if (!hostsWork || work.closed || memory === undefined) return Effect.void if (stored !== undefined) recordWakes(stored.woken) @@ -1255,7 +1291,7 @@ export const make = (options: Options): Effect.Effect, const scheduleLoaded = ( restore: Restore, loaded: Memory - ): Effect.Effect> => + ): Effect.Effect, never, R> => Effect.suspend(() => { if ( loaded._tag !== "Active" || work.revision === loaded.revision || @@ -1319,7 +1355,7 @@ export const make = (options: Options): Effect.Effect, amended: Pick, woken: ReadonlyArray = [], outgoing: ReadonlyArray = [] - ): Effect.Effect => + ): Effect.Effect => Effect.suspend(() => { const revision = memory?.revision memory = undefined @@ -1335,6 +1371,10 @@ export const make = (options: Options): Effect.Effect, } yield* saveWakes(woken) yield* saveOutgoing(outgoing) + if (onCommit !== undefined) { + const decodedState: Snapshot = yield* internalMachine.decodeSnapshot(machine, checkpoint.snapshot) + yield* notifyCommit(checkpoint, decodedState) + } return checkpoint.revision }))) }) @@ -1345,7 +1385,7 @@ export const make = (options: Options): Effect.Effect, restore: Restore, cause: Checkpoint.InvocationKey | { readonly requestId: Snowflake }, failure: string - ): Effect.Effect => + ): Effect.Effect => // A machine that fails stops its children, and a child tells its parent. amend( restore, @@ -1582,16 +1622,20 @@ export const make = (options: Options): Effect.Effect, const initial = yield* Effect.option(internalMachine.planInitial(planned, ...options.input)) if (Option.isNone(initial)) return false const snapshot = yield* internalMachine.encodeSnapshot(machine, initial.value.state) - const committed = yield* storage.commit(address, { + const checkpoint: Checkpoint = { definitionId, version, revision: 1, origin: { _tag: "Request", requestId }, snapshot, status: { _tag: "Failed", failure } - }) + } + const committed = yield* storage.commit(address, checkpoint) if (committed._tag === "RevisionConflict") return yield* new Conflicted() yield* saveOutgoing(endedFor(true)) + if (committed._tag === "Committed") { + yield* notifyCommit(checkpoint, initial.value.state) + } return true }))).pipe( Effect.matchCauseEffect({ diff --git a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts index 576309b..8894d13 100644 --- a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts +++ b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts @@ -8,12 +8,13 @@ * * @since 0.4.0 */ -import type { ClusterError, Entity, MessageStorage, Sharding, Snowflake } from "effect/cluster" +import type { ClusterError, Entity, EntityId, MessageStorage, Sharding, Snowflake } from "effect/cluster" import type * as Duration from "effect/Duration" import type * as Effect from "effect/Effect" import type * as Layer from "effect/Layer" import type * as Option from "effect/Option" import type { Rpc } from "effect/rpc" +import type * as Schedule from "effect/Schedule" import type * as Schema from "effect/Schema" import type * as Stream from "effect/Stream" import * as internal from "../../internal/machine/cluster.js" @@ -518,6 +519,77 @@ type MachineEvents = Machine.Machine.InputEvents< type MachineEmits = Machine.Machine.EmittedEvents +/** + * Committed checkpoint passed to {@link LayerOptions.onCommit} inside the same + * `MessageStorage` transaction as the checkpoint write. + * + * @category models + * @since 0.49.0 + */ +export interface CommitEvent { + /** Entity id of the machine whose checkpoint was committed. */ + readonly entityId: string + + /** Stored checkpoint that was just committed. */ + readonly checkpoint: Checkpoint + + /** Decoded snapshot matching the committed checkpoint. */ + readonly snapshot: Snapshot +} + +/** + * Options for {@link ClusterMachine.toLayer}, combining transactional commit + * hooks with standard Effect Cluster `Entity.toLayer` tuning options. + * + * @category models + * @since 0.49.0 + */ +export interface LayerOptions { + /** + * Durably enqueues emitted events inside the checkpoint's `MessageStorage` + * transaction. + */ + readonly enqueue?: ( + event: Machine.Machine.EmittedEventOf> + ) => Effect.Effect + + /** + * Runs inside the checkpoint's `MessageStorage` transaction right after a + * checkpoint is committed, for projections, read models, or audit tables that + * must commit or roll back atomically with the machine state. + */ + readonly onCommit?: ( + event: CommitEvent + ) => Effect.Effect + + /** Overrides `ShardingConfig.entityMaxIdleTime` for this entity (and its children). */ + readonly maxIdleTime?: Duration.Input | undefined + + /** Concurrency forwarded to `Entity.toLayer` for this entity (and its children). */ + readonly concurrency?: number | "unbounded" | undefined + + /** Overrides `ShardingConfig.entityMailboxCapacity` for this entity (and its children). */ + readonly mailboxCapacity?: number | "unbounded" | undefined + + /** Enables Cluster mailbox metrics for this entity (and its children). */ + readonly mailboxMetrics?: boolean | undefined + + /** + * When `true`, a handler defect fails only its request instead of restarting + * the entity and replaying its in-flight requests. + */ + readonly disableFatalDefects?: boolean | undefined + + /** + * Schedule for restarting an entity after a defect and for retrying failed + * handler construction. + */ + readonly defectRetryPolicy?: Schedule.Schedule | undefined + + /** Tracing span attributes attached to entity requests. */ + readonly spanAttributes?: Record | undefined +} + /** * Cluster adapter for one machine definition and entity type. * @@ -645,24 +717,26 @@ export interface ClusterMachine< * * **Gotchas** * - * `enqueue` runs after the checkpoint write in the same `MessageStorage` - * transaction. It must durably enqueue emitted events in that transaction; + * `enqueue` and `onCommit` run after the checkpoint write in the same + * `MessageStorage` transaction. Use them only for work that joins that + * transaction (such as durable outbox writes or SQL read-model projections); * arbitrary external effects are not atomic with the checkpoint. The reply * is persisted after commit and recovered through request-id deduplication if * delivery is interrupted. Machines that never emit may omit `enqueue`. * - * An `enqueue` that fails rejects the request that emitted. An event emitted - * by the outcome of an invoked effect or timer has no request to reject, so - * that step is retried until it is stored. Without `enqueue`, it fails the - * machine. + * An `enqueue` failure rejects the request as `EmissionFailure`; an + * `onCommit` failure rejects it as `PersistenceFailure` and rolls back the + * transaction. For steps triggered by an invoked effect or timer, both are + * retried until stored. Entity tuning options (`maxIdleTime`, `concurrency`, + * `mailboxCapacity`, `mailboxMetrics`, `disableFatalDefects`, + * `defectRetryPolicy`, `spanAttributes`) are forwarded to `Entity.toLayer` + * for this entity and its child entities. * * @since 0.4.0 */ - readonly toLayer: (options?: { - readonly enqueue?: ( - event: Machine.Machine.EmittedEventOf> - ) => Effect.Effect - }) => Layer.Layer + readonly toLayer: ( + options?: LayerOptions + ) => Layer.Layer } /** @@ -1432,6 +1506,11 @@ export const make: < * Defaults to one second. */ readonly readInterval?: Duration.Input | undefined + /** + * Selects the Cluster shard group for each entity id (and for any child + * entities invoked by that parent). Defaults to Cluster's `"default"` group. + */ + readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined }, ...input: readonly [] | [...Machine.Machine.InputArgs] ) => ClusterMachine< diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachineOptions.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachineOptions.test.ts new file mode 100644 index 0000000..8116c34 --- /dev/null +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachineOptions.test.ts @@ -0,0 +1,294 @@ +import { SqliteClient } from "@effect/sql-sqlite-node" +import { assert, describe, it } from "@effect/vitest" +import { Effect, Layer, Option, Schema } from "effect" +import { + EntityId, + MessageStorage, + RunnerHealth, + Runners, + RunnerStorage, + Sharding, + ShardingConfig, + SqlMessageStorage +} from "effect/cluster" +import { Digest } from "effect/crypto" +import { TestClock } from "effect/testing" +import { Machine } from "../../../src/index.js" +import { ClusterMachine, SqlMachineStorage } from "../../../src/unstable/cluster/index.js" +import { config, makeTestStorage } from "./support/harness.js" + +const Events = Machine.events({ + Add: { by: Schema.Number }, + Finish: {}, + RunEffect: {}, + FailWork: {} +}) + +const childMachine = Machine.make({ + id: "ShardChild", + root: Machine.state({ states: { Open: {}, Done: { type: "final", output: Schema.String } } }), + events: Machine.events({ Complete: {} }) +}).handle({ + initial: { target: "Open" }, + states: { + Open: { on: { Complete: { target: "Done" } } }, + Done: { output: () => "child-done" } + } +}) + +const Child = Machine.child("child", childMachine) + +const jobMachine = Machine.make({ + id: "OptionsJob", + root: Machine.state({ + states: { + Open: { fields: { total: Schema.Number } }, + Working: { fields: { total: Schema.Number } }, + Failing: {}, + Done: { type: "final", fields: { total: Schema.Number }, output: Schema.Number } + } + }), + events: Events, + effects: { + compute: Effect.succeed(10), + boom: Effect.die(new Error("work boom")) + }, + children: { child: Child } +}).handle({ + initial: { target: "Open", data: { total: 0 } }, + states: { + Open: { + on: { + Add: { update: { Open: ({ event, state }) => ({ total: state.total + event.by }) } }, + Finish: { target: "Done", data: ({ state }) => ({ total: state.total }) }, + RunEffect: { target: "Working", data: ({ state }) => ({ total: state.total }) }, + FailWork: { target: "Failing" } + } + }, + Working: { + invoke: { + src: "compute", + onDone: { target: "Done", data: ({ output, state }) => ({ total: state.total + output }) } + } + }, + Failing: { + invoke: { src: "boom" } + }, + Done: { + output: ({ state }) => state.total + } + } +}) + +const parentWithChild = Machine.make({ + id: "ShardedParent", + root: Machine.state({ + states: { + Idle: {}, + Running: {}, + Done: { type: "final", output: Schema.String } + } + }), + events: Machine.events({ Begin: {}, CompleteChild: {} }), + children: { child: Child } +}).handle({ + initial: { target: "Idle" }, + states: { + Idle: { on: { Begin: { target: "Running" } } }, + Running: { + invoke: { src: "child", onDone: { target: "Done" } }, + on: { CompleteChild: { stay: true, commands: (_, enqueue) => enqueue.sendTo(Child, { _tag: "Complete" }) } } + }, + Done: { output: () => "parent-done" } + } +}) + +const settle = Effect.forEach(Array.from({ length: 100 }), () => Effect.yieldNow, { discard: true }) + +describe("ClusterMachine options and onCommit", () => { + it.effect("routes entities and child entities using shardGroup", () => + Effect.gen(function*() { + const shardGroup = (entityId: EntityId.EntityId) => entityId.startsWith("eu:") ? "eu" : "us" + const Parent = ClusterMachine.make("ShardedParent", parentWithChild, { + version: "1", + shardGroup + }) + assert.strictEqual(Parent.entity.getShardGroup(EntityId.make("eu:order-1")), "eu") + assert.strictEqual(Parent.entity.getShardGroup(EntityId.make("us:order-2")), "us") + + const storage = makeTestStorage() + const layer = Parent.toLayer().pipe( + Layer.provide(Layer.succeed(ClusterMachine.Storage, storage.service)), + Layer.provideMerge(Sharding.layer), + Layer.provide(Runners.layerNoop), + Layer.provide(MessageStorage.layerMemory), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(ShardingConfig.layer({ + availableShardGroups: ["eu", "us"], + assignedShardGroups: ["eu", "us"], + entityMailboxCapacity: 10, + entityMaxIdleTime: "10 minutes", + entityTerminationTimeout: 0, + entityMessagePollInterval: 5000, + sendRetryInterval: 100, + refreshAssignmentsInterval: 0 + })) + ) + + yield* Effect.gen(function*() { + yield* TestClock.adjust(1) + const makeClient = yield* Parent.client + const eu = makeClient("eu:order-1") + const us = makeClient("us:order-2") + + yield* eu.send({ _tag: "Begin" }) + yield* us.send({ _tag: "Begin" }) + yield* eu.send({ _tag: "CompleteChild" }) + yield* settle + + const euSnap = Option.getOrThrow(yield* eu.snapshot) + assert.strictEqual(euSnap.status, "done") + const usSnap = Option.getOrThrow(yield* us.snapshot) + assert.strictEqual(usSnap.status, "active") + }).pipe( + Effect.provide(layer), + Effect.provideService(ClusterMachine.Storage, storage.service) + ) + }).pipe(Effect.scoped)) + + it.effect("forwards Entity.toLayer options such as maxIdleTime to passivate idle entities", () => + Effect.gen(function*() { + const Job = ClusterMachine.make("IdleJob", jobMachine, { version: "1" }) + const storage = makeTestStorage() + const layer = Job.toLayer({ + maxIdleTime: "5 seconds", + concurrency: 1, + mailboxCapacity: 16, + disableFatalDefects: false, + spanAttributes: { service: "jobs" } + }).pipe( + Layer.provide(Layer.succeed(ClusterMachine.Storage, storage.service)), + Layer.provideMerge(Sharding.layer), + Layer.provide(Runners.layerNoop), + Layer.provide(MessageStorage.layerMemory), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(config("10 minutes")) + ) + + yield* Effect.gen(function*() { + yield* TestClock.adjust(1) + const client = (yield* Job.client)("job-idle") + yield* client.send(Events.Add({ by: 1 })) + // First request loads from storage once (1), second request uses in-memory cache (still 1). + yield* client.send(Events.Add({ by: 2 })) + assert.strictEqual(storage.loads, 1) + + // Advance past entity-level maxIdleTime (5s) and EntityReaper resolution (5s), + // well below ShardingConfig's 10-minute default. + yield* TestClock.adjust("5 seconds") + yield* settle + yield* TestClock.adjust("5 seconds") + yield* settle + + // After passivation, the next request recreates the entity and reloads from storage. + yield* client.send(Events.Add({ by: 3 })) + assert.isAtLeast(storage.loads, 2) + const snap = Option.getOrThrow(yield* client.snapshot) + assert.strictEqual(snap.revision, 3) + }).pipe( + Effect.provide(layer), + Effect.provideService(ClusterMachine.Storage, storage.service) + ) + }).pipe(Effect.scoped)) + + it.effect("invokes onCommit for active, done, and failed checkpoints and retries on background failure", () => + Effect.gen(function*() { + const Job = ClusterMachine.make("CommitJob", jobMachine, { version: "1" }) + const seen: Array< + { readonly entityId: string; readonly revision: number; readonly status: string; readonly output?: number } + > = [] + let failOnceOnDone = true + + // Use transactional SQLite storage so a failed onCommit on a background + // invocation rolls back the checkpoint and retries cleanly. + const layer = Job.toLayer({ + onCommit: ({ checkpoint, entityId, snapshot }) => + Effect.gen(function*() { + if (entityId === "job-effect" && snapshot.status === "done" && failOnceOnDone) { + failOnceOnDone = false + return yield* Effect.fail("transient projection failure") + } + seen.push({ + entityId, + revision: checkpoint.revision, + status: snapshot.status, + ...(snapshot.status === "done" ? { output: snapshot.output } : {}) + }) + }) + }).pipe( + Layer.provideMerge(Sharding.layer), + Layer.provide(Runners.layerNoop), + Layer.provideMerge(SqlMessageStorage.layer), + Layer.provideMerge(SqlMachineStorage.layer), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(config()), + Layer.provide(Digest.layerWebCrypto), + Layer.provide(SqliteClient.layer({ filename: ":memory:" })) + ) + + yield* Effect.gen(function*() { + yield* TestClock.adjust(1) + const makeClient = yield* Job.client + + // Active + done transitions from requests. + const direct = makeClient("job-direct") + yield* direct.send(Events.Add({ by: 5 })) + yield* direct.send(Events.Finish()) + + // Invoked effect completes -> onCommit fails once (rolling back rev 3), + // retries after 1s, and commits rev 3 without failing the machine. + const effectJob = makeClient("job-effect") + yield* effectJob.send(Events.Add({ by: 2 })) + yield* effectJob.send(Events.RunEffect()) + yield* settle + yield* TestClock.adjust("2 seconds") + yield* settle + const effectSnap = Option.getOrThrow(yield* effectJob.snapshot) + assert.strictEqual(effectSnap.status, "done") + if (effectSnap.status === "done") assert.strictEqual(effectSnap.output, 12) + + // Failed machine -> onCommit observes status: "failed". + const failing = makeClient("job-fail") + yield* failing.send(Events.FailWork()) + yield* settle + const failSnap = Option.getOrThrow(yield* failing.snapshot) + assert.strictEqual(failSnap.status, "failed") + + assert.deepStrictEqual( + seen.filter((e) => e.entityId === "job-direct"), + [ + { entityId: "job-direct", revision: 1, status: "active" }, + { entityId: "job-direct", revision: 2, status: "done", output: 5 } + ] + ) + assert.deepStrictEqual( + seen.filter((e) => e.entityId === "job-effect"), + [ + { entityId: "job-effect", revision: 1, status: "active" }, + { entityId: "job-effect", revision: 2, status: "active" }, + { entityId: "job-effect", revision: 3, status: "done", output: 12 } + ] + ) + assert.deepStrictEqual( + seen.filter((e) => e.entityId === "job-fail"), + [ + { entityId: "job-fail", revision: 1, status: "active" }, + { entityId: "job-fail", revision: 2, status: "failed" } + ] + ) + }).pipe(Effect.provide(layer)) + }).pipe(Effect.scoped)) +}) diff --git a/packages/effect-machine/test/unstable/cluster/SqlMachineStorage.test.ts b/packages/effect-machine/test/unstable/cluster/SqlMachineStorage.test.ts index 14214f9..22dc90a 100644 --- a/packages/effect-machine/test/unstable/cluster/SqlMachineStorage.test.ts +++ b/packages/effect-machine/test/unstable/cluster/SqlMachineStorage.test.ts @@ -156,5 +156,79 @@ for (const dialect of dialects) { ), Effect.orDie )) + + it.effect("commits or rolls back onCommit SQL projections atomically with the checkpoint", () => + Effect.gen(function*() { + const failing = { next: false } + const adapter = ClusterMachine.make("SqlCounter", counter, { version: "1" }) + const layer = adapter.toLayer({ + enqueue: () => Effect.void, + onCommit: ({ checkpoint, entityId, snapshot }) => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + const total = snapshot.state.state.value.total + yield* sql` + INSERT INTO projections (entity_id, revision, total) + VALUES (${entityId}, ${checkpoint.revision}, ${total}) + ` + if (failing.next) return yield* Effect.fail("projection failed") + }) + }).pipe( + Layer.provideMerge(Sharding.layer), + Layer.provide(Runners.layerNoop), + Layer.provideMerge(SqlMessageStorage.layer), + Layer.provideMerge(SqlMachineStorage.layer), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(config()), + Layer.provide(Digest.layerWebCrypto) + ) + + yield* Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + yield* TestClock.adjust(1) + const client = (yield* adapter.client)("counter-proj") + const storage = yield* ClusterMachine.Storage + + yield* client.send(Events.Add({ amount: 4 })) + assert.strictEqual(Option.getOrThrow(yield* storage.load(address("counter-proj"))).revision, 1) + const rows1 = yield* sql<{ readonly entity_id: string; readonly revision: number; readonly total: number }>` + SELECT entity_id, revision, total FROM projections ORDER BY revision + ` + assert.deepStrictEqual(rows1, [{ entity_id: "counter-proj", revision: 1, total: 4 }]) + + // Failing onCommit rolls back both the checkpoint write and the projection insert. + failing.next = true + const failed = yield* Effect.flip(client.send(Events.Add({ amount: 10 }))) + assert.strictEqual(failed._tag, "Rejected") + if (failed._tag === "Rejected") assert.strictEqual(failed.reason, "PersistenceFailure") + assert.strictEqual(Option.getOrThrow(yield* storage.load(address("counter-proj"))).revision, 1) + const rowsAfterFail = yield* sql`SELECT entity_id, revision, total FROM projections ORDER BY revision` + assert.strictEqual(rowsAfterFail.length, 1) + + // Next attempt succeeds and commits both together. + failing.next = false + yield* client.send(Events.Add({ amount: 6 })) + assert.strictEqual(Option.getOrThrow(yield* storage.load(address("counter-proj"))).revision, 2) + const rows2 = yield* sql<{ readonly entity_id: string; readonly revision: number; readonly total: number }>` + SELECT entity_id, revision, total FROM projections ORDER BY revision + ` + assert.deepStrictEqual(rows2, [ + { entity_id: "counter-proj", revision: 1, total: 4 }, + { entity_id: "counter-proj", revision: 2, total: 10 } + ]) + }).pipe(Effect.provide(layer)) + }).pipe( + Effect.provide( + Layer.effectDiscard( + Effect.flatMap( + SqlClient.SqlClient, + (sql) => + sql`CREATE TABLE projections (entity_id TEXT NOT NULL, revision INTEGER NOT NULL, total INTEGER NOT NULL)` + ) + ).pipe(Layer.provideMerge(dialect.client())) + ), + Effect.orDie + )) }) } diff --git a/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts b/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts index 291a3ea..bd9fe9c 100644 --- a/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts +++ b/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts @@ -1,5 +1,5 @@ -import { Context, Effect, type Layer, type Option, Schema, SchemaGetter, type Stream } from "effect" -import type { ClusterError, MessageStorage, Sharding, Snowflake } from "effect/cluster" +import { Context, Effect, type Layer, type Option, Schedule, Schema, SchemaGetter, type Stream } from "effect" +import type { ClusterError, EntityId, MessageStorage, Sharding, Snowflake } from "effect/cluster" import type { Rpc, RpcGroup } from "effect/rpc" import { describe, expect, it } from "tstyche" import { Machine } from "../../../src/index.js" @@ -483,4 +483,33 @@ describe("ClusterMachine", () => { expect(order((enqueue) => enqueue.sendTo(target, { _tag: "Add", amount: "1" }))).type.toRaiseError() expect(order((enqueue) => enqueue.stop(target))).type.toRaiseError() }) + + it("supports shardGroup, Entity.toLayer tuning options, and transactional onCommit with typed services", () => { + const sharded = ClusterMachine.make("ShardedCounter", machine, { + version: "1", + shardGroup: (entityId: EntityId.EntityId) => entityId.startsWith("eu:") ? "eu" : "us" + }) + expect(sharded).type.toBeAssignableTo>() + + const layer = sharded.toLayer({ + enqueue: () => Effect.asVoid(PlanningService), + onCommit: (event) => { + expect(event).type.toBe>() + expect(event.entityId).type.toBe() + expect(event.checkpoint).type.toBe() + expect(event.snapshot).type.toBe>() + return Effect.flatMap(ActionService, (service) => service.run) + }, + maxIdleTime: "30 seconds", + concurrency: 1, + mailboxCapacity: 64, + mailboxMetrics: true, + disableFatalDefects: false, + defectRetryPolicy: Schedule.spaced("1 second"), + spanAttributes: { region: "eu" } + }) + expect>().type.toBe< + ClusterMachine.Storage | MessageStorage.MessageStorage | Sharding.Sharding | PlanningService | ActionService + >() + }) })