diff --git a/.changeset/cluster-stop-and-start.md b/.changeset/cluster-stop-and-start.md new file mode 100644 index 0000000..590676c --- /dev/null +++ b/.changeset/cluster-stop-and-start.md @@ -0,0 +1,9 @@ +--- +"@typeonce/effect-machine": minor +--- + +Support `enqueue.stop(Child)` in synchronous transitions and per-entity startup input via `client.start(...input)` on `ClusterMachine` and `ClusterMachineProxy`. + +- `enqueue.stop(Child)` with a `ChildMachine` descriptor now stops the running child entity in the same transaction as the parent checkpoint, settles its invocation progress so it does not restart while its state remains active, and ignores a child that is not running. Passing a local `ChildAddress` still rejects as `UnsupportedProcessLocal`. +- `ClusterMachine.Client` and `ClusterMachineProxy.Client` now expose `start(...input)` (and `ClusterMachineProxy.toRpcGroup` adds `${Type}.start`), allowing each entity instance to be initialized with its own schema-validated input or to commit its initial state before receiving an event. +- `ClusterMachine.make` now accepts omitting the static default `input` for machines that declare `input`, requiring `client.start(input)` before sending events (or continuing to auto-start on `send` when a default input is supplied), and enforces that declared `input` schemas have JSON-compatible encoded representations. diff --git a/LLMS.md b/LLMS.md index 68d4d28..1536609 100644 --- a/LLMS.md +++ b/LLMS.md @@ -1670,9 +1670,9 @@ const InvoiceLive = Invoice.toLayer().pipe( definition id or version is refused, so change it together with a migration of the stored checkpoints. -State values, completion outputs, and public input events must have JSON -encoded forms. A schema that does not is a compile error that names the -offending states and events. +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 +the offending states, events, or input. ### What runs, and how often @@ -1719,8 +1719,10 @@ the failure is stored as text. `adapter.target(id)` names another Cluster machine. `enqueue.sendTo` with a target or with the descriptor of an invoked child saves the event with the checkpoint of the step, so it is sent if and only if the step is stored, and -applied once. Work sends with `Machine.sendTo` and stops a child with -`Machine.stopChild`, given the child's descriptor. +applied once. `enqueue.stop` with the descriptor of an invoked child stops the +running child in the same transaction and settles its progress so it does not +restart while its state stays active. Work sends with `Machine.sendTo` and stops +a child with `Machine.stopChild`, given the child's descriptor. ### What is refused, and why @@ -1750,6 +1752,15 @@ const program = Effect.gen(function*() { }) ``` +`start` initializes an entity with its per-entity startup input (or commits the +initial state of a machine without input without needing an event). It is an +idempotent no-op when the entity is already active, and rejects as +`MachineFailed` if the entity failed or was stopped. A machine that declares +`input` can omit a static default input in `ClusterMachine.make` so each entity +is started with `client.start(input)` (sending an event before start rejects as +`InvalidEvent`), or pass a default input so `send` can auto-start while +`client.start(customInput)` still starts with per-entity input. + `send` decodes the event as a local reference does and waits until the step is committed. An event the machine refuses fails with `Rejected` and its reason. Failures of Cluster itself are `ClientError`s; a request that ended in one may @@ -1785,9 +1796,9 @@ or `@effect/sql-pglite`. When the runner and its database live in another thread or process, callers do not have direct access to `Sharding` or `ClusterMachine.Storage`. -`ClusterMachineProxy` from `@typeonce/effect-machine/cluster` exposes `send`, -`snapshot`, `changes`, and `join` over any `effect/rpc` transport (Web Workers, -`SharedWorker`, Node worker threads, WebSockets, or HTTP): +`ClusterMachineProxy` from `@typeonce/effect-machine/cluster` exposes `start`, +`send`, `snapshot`, `changes`, and `join` over any `effect/rpc` transport (Web +Workers, `SharedWorker`, Node worker threads, WebSockets, or HTTP): ```ts // Inside the Web Worker: serve one machine over RpcServer.Protocol diff --git a/ai-docs/src/35_cluster/index.md b/ai-docs/src/35_cluster/index.md index 8be38cf..e2c7fba 100644 --- a/ai-docs/src/35_cluster/index.md +++ b/ai-docs/src/35_cluster/index.md @@ -42,9 +42,9 @@ const InvoiceLive = Invoice.toLayer().pipe( definition id or version is refused, so change it together with a migration of the stored checkpoints. -State values, completion outputs, and public input events must have JSON -encoded forms. A schema that does not is a compile error that names the -offending states and events. +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 +the offending states, events, or input. ### What runs, and how often @@ -91,8 +91,10 @@ the failure is stored as text. `adapter.target(id)` names another Cluster machine. `enqueue.sendTo` with a target or with the descriptor of an invoked child saves the event with the checkpoint of the step, so it is sent if and only if the step is stored, and -applied once. Work sends with `Machine.sendTo` and stops a child with -`Machine.stopChild`, given the child's descriptor. +applied once. `enqueue.stop` with the descriptor of an invoked child stops the +running child in the same transaction and settles its progress so it does not +restart while its state stays active. Work sends with `Machine.sendTo` and stops +a child with `Machine.stopChild`, given the child's descriptor. ### What is refused, and why @@ -122,6 +124,15 @@ const program = Effect.gen(function*() { }) ``` +`start` initializes an entity with its per-entity startup input (or commits the +initial state of a machine without input without needing an event). It is an +idempotent no-op when the entity is already active, and rejects as +`MachineFailed` if the entity failed or was stopped. A machine that declares +`input` can omit a static default input in `ClusterMachine.make` so each entity +is started with `client.start(input)` (sending an event before start rejects as +`InvalidEvent`), or pass a default input so `send` can auto-start while +`client.start(customInput)` still starts with per-entity input. + `send` decodes the event as a local reference does and waits until the step is committed. An event the machine refuses fails with `Rejected` and its reason. Failures of Cluster itself are `ClientError`s; a request that ended in one may @@ -157,9 +168,9 @@ or `@effect/sql-pglite`. When the runner and its database live in another thread or process, callers do not have direct access to `Sharding` or `ClusterMachine.Storage`. -`ClusterMachineProxy` from `@typeonce/effect-machine/cluster` exposes `send`, -`snapshot`, `changes`, and `join` over any `effect/rpc` transport (Web Workers, -`SharedWorker`, Node worker threads, WebSockets, or HTTP): +`ClusterMachineProxy` from `@typeonce/effect-machine/cluster` exposes `start`, +`send`, `snapshot`, `changes`, and `join` over any `effect/rpc` transport (Web +Workers, `SharedWorker`, Node worker threads, WebSockets, or HTTP): ```ts // Inside the Web Worker: serve one machine over RpcServer.Protocol diff --git a/packages/effect-machine/src/internal/machine/cluster.ts b/packages/effect-machine/src/internal/machine/cluster.ts index 33ff610..ab71b4e 100644 --- a/packages/effect-machine/src/internal/machine/cluster.ts +++ b/packages/effect-machine/src/internal/machine/cluster.ts @@ -59,6 +59,21 @@ const decodeInputEvent = ( ) ) +const decodeMachineInput = ( + machine: Machine.Machine.Any, + input: unknown +): Effect.Effect => + machine.input === undefined + ? Effect.succeed(undefined) + : Protocol.decodeBoundary(machine, machine.input, input, { boundary: "input" }).pipe( + Effect.mapError(() => + new Rejected({ + reason: "InvalidEvent", + message: "The input does not match the schema of the machine" + }) + ) + ) + const addressKey = (address: EntityAddress): string => `${address.entityType}\u0000${address.entityId}` export const makeMemory: Effect.Effect = Effect.sync(() => { @@ -124,6 +139,7 @@ export interface AdapterMeta { readonly version: string readonly readInterval: Duration.Input readonly decodeEvent: (event: unknown) => Effect.Effect + readonly decodeInput: (input: unknown) => Effect.Effect } const adapterMeta = new WeakMap() @@ -174,7 +190,7 @@ export const make = < readonly version: string readonly readInterval?: Duration.Input | undefined }, - ...input: [...Machine.Machine.InputArgs] + ...input: readonly [] | [...Machine.Machine.InputArgs] ): ClusterMachine< Type, Machine.Machine< @@ -250,7 +266,7 @@ const build = ( rpc, deliver, ClusterWake.WakeRpc, - ClusterChild.makeStartRpc(machine.input ?? Schema.Undefined), + ClusterChild.makeStartRpc(machine.input), ClusterChild.StopRpc, ClusterChild.EndedRpc, ClusterChild.SnapshotRpc @@ -268,6 +284,19 @@ const build = ( Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result)) ) + const startThroughClient = ( + rpc: EntityClient, + args: ReadonlyArray + ): Effect.Effect => + decodeMachineInput(machine, args[0]).pipe( + Effect.flatMap((decoded) => + rpc.start( + (machine.input === undefined ? {} : { input: decoded }) as never + ) as Effect.Effect + ), + Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result)) + ) + const protocol: ClusterTarget.Protocol = { entity, machine, @@ -380,6 +409,7 @@ const build = ( return { entityId, ...reader, + start: (...args: ReadonlyArray) => startThroughClient(rpc, args), send: (event) => sendThroughClient(rpc, event) } } @@ -392,7 +422,8 @@ const build = ( definitionId, version: options.version, readInterval: options.readInterval ?? "1 second", - decodeEvent: (event) => decodeInputEvent(machine, publicTags, event) + decodeEvent: (event) => decodeInputEvent(machine, publicTags, event), + decodeInput: (value) => decodeMachineInput(machine, value) }) return built } diff --git a/packages/effect-machine/src/internal/machine/clusterChild.ts b/packages/effect-machine/src/internal/machine/clusterChild.ts index 9672973..dca0543 100644 --- a/packages/effect-machine/src/internal/machine/clusterChild.ts +++ b/packages/effect-machine/src/internal/machine/clusterChild.ts @@ -19,6 +19,7 @@ import { Rpc } from "effect/rpc" import * as Schema from "effect/Schema" import type { ChildMachine } from "../../Machine.js" import * as CapturedInvocation from "./capturedInvocation.js" +import { SendResult } from "./clusterProtocol.js" /** @internal */ export const entityTypeOf = (parentType: string, childId: string): string => `${parentType}/${childId}` @@ -77,12 +78,18 @@ export const snapshotsOf = ( } /** - * Starts a child with its input. A child that has started already ignores it. + * Starts a machine entity with its input. An entity that is already active + * accepts it as a no-op; a failed or stopped entity rejects it. * * @internal */ -export const makeStartRpc = (input: Input) => - Rpc.make("start", { payload: { input } }).annotate(ClusterSchema.Persisted, true) +export const makeStartRpc = (input: Schema.Top | undefined) => + Rpc.make("start", { + payload: input === undefined + ? { input: Schema.optionalKey(Schema.Undefined) } + : { input }, + success: SendResult + }).annotate(ClusterSchema.Persisted, true) /** * Stops a child, which then rejects every later request. diff --git a/packages/effect-machine/src/internal/machine/clusterInstance.ts b/packages/effect-machine/src/internal/machine/clusterInstance.ts index 0edfebe..d4372be 100644 --- a/packages/effect-machine/src/internal/machine/clusterInstance.ts +++ b/packages/effect-machine/src/internal/machine/clusterInstance.ts @@ -135,8 +135,13 @@ export interface ClusterInstance { */ readonly deliver: (input: Input) => Effect.Effect - /** Starts a child machine with its input. A child that started ignores it. */ - readonly start: (input: { readonly requestId: Snowflake; readonly input: unknown }) => Effect.Effect + /** + * Starts the machine with its input, committing its initial state if absent. + * An active machine accepts it as a no-op; a failed or stopped one rejects it. + */ + readonly start: ( + input: { readonly requestId: Snowflake; readonly input: unknown } + ) => Effect.Effect /** Stops a child machine, which then rejects every later request. */ readonly stop: (requestId: Snowflake) => Effect.Effect @@ -600,16 +605,22 @@ export const make = (options: Options): Effect.Effect, const wasFinal = (base: Base): boolean => base._tag === "Active" && internalMachine.isFinal(machine, base.state) - // The child that runs for a child descriptor in a progress. - const childTarget = ( + // The running entry and target for a child descriptor in a progress. + const runningChildEntry = ( progress: ClusterProgress.Progress, child: Machine.ChildMachine.Any - ): ClusterTarget.Target | undefined => { + ): readonly [key: Checkpoint.InvocationKey, target: ClusterTarget.Target] | undefined => { const protocol = options.children?.protocols.get(child.id) const running = ClusterProgress.children(progress).find(([key]) => key.id === child.id) - return protocol && running && new ClusterTarget.Target(protocol, running[1]) + return protocol && running && [running[0], new ClusterTarget.Target(protocol, running[1])] } + // The child that runs for a child descriptor in a progress. + const childTarget = ( + progress: ClusterProgress.Progress, + child: Machine.ChildMachine.Any + ): ClusterTarget.Target | undefined => runningChildEntry(progress, child)?.[1] + const runningChild = (child: Machine.ChildMachine.Any): Effect.Effect => Effect.suspend(() => { const known = memory @@ -636,16 +647,41 @@ export const make = (options: Options): Effect.Effect, Effect.orDie ) - // The events that commands send to Cluster machines, in order, decoded by + // The sends and child stops that commands enqueue, in order, decoded by // the protocols of their targets. A child is the one that runs once the step - // is stored, and an event sent to a child that does not run is dropped, as a - // local runtime drops it. - const sendsOf = Effect.fnUntraced(function*( + // is stored, and a send or stop for a child that does not run is dropped, as + // a local runtime drops it. Stopping a child settles its progress entry so + // it does not restart while its state stays active. + const commandsOf = Effect.fnUntraced(function*( commands: ReadonlyArray, - progress: ClusterProgress.Progress - ): Effect.fn.Return, Rejected> { - const sent: Array = [] + initialProgress: ClusterProgress.Progress + ): Effect.fn.Return< + { + readonly outgoing: Array + readonly progress: ClusterProgress.Progress + readonly stoppedIds: ReadonlySet + }, + Rejected + > { + const outgoing: Array = [] + const stoppedIds = new Set() + let progress = initialProgress for (const command of commands) { + if (command._tag === "Stop") { + if (!isChildMachine(command.child)) { + return yield* fail( + "UnsupportedProcessLocal", + "Machine commands on Cluster stop only an invoked child machine" + ) + } + const running = runningChildEntry(progress, command.child) + if (running === undefined) continue + const [key, target] = running + progress = ClusterProgress.settle(progress, key) + stoppedIds.add(target.entityId) + outgoing.push({ target, tag: "stop", payload: undefined }) + continue + } const child = command._tag === "SendTo" && isChildMachine(command.target) ? command.target : undefined if ( command._tag !== "SendTo" || options.sends === undefined || @@ -665,9 +701,9 @@ export const make = (options: Options): Effect.Effect, reject("TransitionFailure", `The step sends ${target.sessionId} an event it refuses: ${rejected.message}`) ) ) - sent.push({ target, tag: "send", payload: event }) + outgoing.push({ target, tag: "send", payload: event }) } - return sent + return { outgoing, progress, stoppedIds } }) // Starts the child machines of the states of a step that run no child yet. @@ -709,18 +745,19 @@ export const make = (options: Options): Effect.Effect, } // Stops the children that ran before a step and do not after it, except the - // one whose end the step applies. + // one whose end the step applies or ones already stopped by commands. const stopsOf = ( before: ClusterProgress.Progress, after: ClusterProgress.Progress, - ended: Checkpoint.InvocationKey | undefined + ended: Checkpoint.InvocationKey | undefined, + alreadyStopped?: ReadonlySet ): ReadonlyArray => { const children = options.children if (children === undefined) return [] const kept = new Set(ClusterProgress.children(after).map(([, entityId]) => entityId)) return ClusterProgress.children(before).flatMap(([key, entityId]): Array => { const protocol = children.protocols.get(key.id) - return protocol === undefined || kept.has(entityId) || + return protocol === undefined || kept.has(entityId) || alreadyStopped?.has(entityId) === true || (ended !== undefined && key.path === ended.path && key.id === ended.id) ? [] : [{ target: new ClusterTarget.Target(protocol, entityId), tag: "stop", payload: undefined }] @@ -768,6 +805,9 @@ export const make = (options: Options): Effect.Effect, if (options.children?.parent !== undefined && initialArgs === undefined) { return yield* fail("InvalidEvent", "A child machine takes events once its parent has started it") } + if (machine.input !== undefined && initialArgs === undefined && options.input.length === 0) { + return yield* fail("InvalidEvent", "A machine with input must be started before it takes events") + } const initial = yield* internalMachine.planInitial(planned, ...initialArgs ?? options.input) commands.push(...initial.commands) state = initial.state @@ -855,17 +895,17 @@ export const make = (options: Options): Effect.Effect, const revision = base.revision + 1 // Last, so a step that is refused evaluates no duration. const scheduled = yield* Effect.sync(() => progressAfter(base, input, planned)) - const { starts, progress } = yield* Effect.try({ + const { starts, progress: startedProgress } = yield* Effect.try({ try: () => startChildren(planned.state, scheduled.progress, planned.changes, revision), catch: (error) => reject("TransitionFailure", `The input of a child machine cannot be built: ${String(error)}`) }) const unscheduled = scheduled.unscheduled - const sent = yield* sendsOf(planned.commands, progress) + const { outgoing: commandOutgoing, progress, stoppedIds } = yield* commandsOf(planned.commands, startedProgress) const before = base._tag === "Active" ? base.progress : ClusterProgress.empty const outgoing = [ - ...stopsOf(before, progress, input._tag === "Invocation" ? input.key : undefined), + ...stopsOf(before, progress, input._tag === "Invocation" ? input.key : undefined, stoppedIds), ...starts, - ...sent, + ...commandOutgoing, ...snapshotFor(planned, snapshot), ...endedFor(internalMachine.isFinal(machine, planned.state) && !wasFinal(base)) ] @@ -997,9 +1037,9 @@ export const make = (options: Options): Effect.Effect, } const confirm = known !== undefined - // A start of a child that started, and a stop of one that does not run, - // change nothing. - if (input.lifecycle === "Start" && base._tag !== "Absent") return { memory: base, stored: undefined } + // A start of an active machine, and a stop of one that does not run, + // change nothing. A start of a failed or stopped machine is rejected below. + if (input.lifecycle === "Start" && base._tag === "Active") return { memory: base, stored: undefined } if (input.lifecycle === "Stop") { return base._tag === "Active" ? yield* stopStep(input.requestId, base) : { memory: base, stored: undefined } } @@ -1580,6 +1620,20 @@ export const make = (options: Options): Effect.Effect, ) ) + const applyRequest = (input: RequestInput): Effect.Effect => + turn((restore) => + attempt(restore, input).pipe( + // A conflict leaves memory unknown, so the retry loads. + Effect.catchTag("Conflicted", () => attempt(restore, input)), + Effect.catchTag("Conflicted", () => + Effect.succeed(reject( + "RevisionConflict", + "Another instance advanced the checkpoint while this request was applied" + ))), + Effect.tap(() => align(restore, undefined)) + ) + ) + return { wake, childEnded, @@ -1587,25 +1641,13 @@ export const make = (options: Options): Effect.Effect, childSnapshot: ({ entityId, requestId, snapshot }) => untilDone(deliverOnce({ requestId, event: undefined, child: { entityId, snapshot } })), start: ({ input, requestId }) => - lifecycle({ + applyRequest({ requestId, event: undefined, lifecycle: "Start", initial: machine.input === undefined ? [] : [input] }), stop: (requestId) => lifecycle({ requestId, event: undefined, lifecycle: "Stop" }), - apply: (input) => - turn((restore) => - attempt(restore, input).pipe( - // A conflict leaves memory unknown, so the retry loads. - Effect.catchTag("Conflicted", () => attempt(restore, input)), - Effect.catchTag("Conflicted", () => - Effect.succeed(reject( - "RevisionConflict", - "Another instance advanced the checkpoint while this request was applied" - ))), - Effect.tap(() => align(restore, undefined)) - ) - ) + apply: (input) => applyRequest(input) } }) diff --git a/packages/effect-machine/src/internal/machine/clusterProxy.ts b/packages/effect-machine/src/internal/machine/clusterProxy.ts index 3cf12ee..c53ab81 100644 --- a/packages/effect-machine/src/internal/machine/clusterProxy.ts +++ b/packages/effect-machine/src/internal/machine/clusterProxy.ts @@ -76,6 +76,16 @@ export const toRpcGroup = < if (cached !== undefined) return cached const meta = Cluster.getAdapterMeta(adapter) const eventSchema = Schema.Union(Protocol.inputEventSchemas(meta.machine)) + const startRpc = Rpc.make(`${meta.type}.start`, { + payload: meta.machine.input === undefined + ? Schema.Struct({ entityId: Schema.String }) + : Schema.Struct({ + entityId: Schema.String, + input: meta.machine.input + }), + success: Schema.Void, + error: SendErrorSchema + }) const sendRpc = Rpc.make(`${meta.type}.send`, { payload: Schema.Struct({ entityId: Schema.String, @@ -95,7 +105,7 @@ export const toRpcGroup = < error: ReadErrorSchema, stream: true }) - const group = RpcGroup.make(sendRpc, snapshotRpc, changesRpc) + const group = RpcGroup.make(startRpc, sendRpc, snapshotRpc, changesRpc) rpcGroups.set(adapter, group) return group as never } @@ -135,6 +145,10 @@ export const layerHandlers = < } return { + [`${meta.type}.start`]: (payload: { readonly entityId: string; readonly input?: unknown }) => + meta.machine.input === undefined + ? (makeClient(payload.entityId).start as () => Effect.Effect)() + : (makeClient(payload.entityId).start as (input: unknown) => Effect.Effect)(payload.input), [`${meta.type}.send`]: ({ entityId, event }: { readonly entityId: string; readonly event: never }) => makeClient(entityId).send(event), [`${meta.type}.snapshot`]: ({ entityId }: { readonly entityId: string }) => @@ -180,11 +194,19 @@ export const client = < const meta = Cluster.getAdapterMeta(adapter) const group = toRpcGroup(adapter) const rpc = (yield* RpcClient.make(group)) as Record any> + const startTag = `${meta.type}.start` const sendTag = `${meta.type}.send` const snapshotTag = `${meta.type}.snapshot` const changesTag = `${meta.type}.changes` return (entityId: string): Public.Client => { + const start = (...args: ReadonlyArray) => + meta.decodeInput(args[0]).pipe( + Effect.flatMap((decoded) => + rpc[startTag]!(meta.machine.input === undefined ? { entityId } : { entityId, input: decoded }) + ) + ) + const send = (event: unknown) => meta.decodeEvent(event).pipe( Effect.flatMap((decoded) => rpc[sendTag]!({ entityId, event: decoded })) @@ -206,6 +228,6 @@ export const client = < const join = ClusterRead.joinChanges(changes) - return { entityId, send, snapshot, changes, join } as Public.Client + return { entityId, start, send, snapshot, changes, join } as Public.Client } }) diff --git a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts index 9c5be37..576309b 100644 --- a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts +++ b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts @@ -706,8 +706,9 @@ export type ClientError = * The types check the event against the input events of the target, but not * that the target was made by this module: a step on Cluster that sends to a * local reference is rejected as `UnsupportedProcessLocal`, and so is - * `enqueue.stop`. A target made here is not a local reference either, so a local - * machine cannot send to it. + * `enqueue.stop` with a local child address (whereas `enqueue.stop` with the + * descriptor of an invoked child stops that child). A target made here is not a + * local reference either, so a local machine cannot send to it. * * The runner that stores the step reads the request at once. A target owned by * another runner reads it at its next poll of `MessageStorage`, after up to @@ -772,6 +773,15 @@ export interface Client { /** Entity id of the machine this client addresses. */ readonly entityId: string + /** + * Starts the entity with its initial input, committing its initial state when + * it has no checkpoint yet. Succeeds as a no-op if the entity is already + * active, and rejects with `MachineFailed` if it failed or was stopped. + */ + readonly start: ( + ...input: [...Machine.Machine.InputArgs>] + ) => Effect.Effect + /** Sends one input event and waits until it is committed or rejected. */ readonly send: ( event: Machine.Machine.EventInputOf> @@ -928,15 +938,22 @@ type NonJsonInputEvent = Input extends typeof Schema.Void ? never + : IsJsonEncoded extends true ? never + : Input["Encoded"] + type EnsureJsonEncoded< States extends Machine.Machine.StateSchemas, - InputEvents extends ReadonlyArray -> = [NonJsonState | NonJsonOutput | NonJsonInputEvent] extends [never] ? unknown + InputEvents extends ReadonlyArray, + Input extends Schema.Top +> = [NonJsonState | NonJsonOutput | NonJsonInputEvent | NonJsonInput] extends + [never] ? unknown : { readonly "~effect/cluster/ClusterMachine/NonJsonEncoded": { readonly states: NonJsonState readonly outputs: NonJsonOutput readonly inputEvents: NonJsonInputEvent + readonly input: NonJsonInput } } @@ -1051,7 +1068,13 @@ export { StorageCheckFailure } * * **Details** * - * A missing checkpoint runs initial planning before the first event. Existing + * A missing checkpoint runs initial planning before the first event. An entity + * may also be started explicitly via `client.start(...input)`. For a machine + * that declares `input`, you may either omit the default input from + * `ClusterMachine.make` and pass per-entity input to `client.start(input)` + * (sending an event before start rejects as `InvalidEvent`), or pass a default + * input to `ClusterMachine.make` so `client.send` can auto-start while + * `client.start(input)` still starts an entity with a custom input. Existing * checkpoints are checked for their definition id and version, decoded, and * resumed without rerunning initial entry behavior. Final checkpoints accept * later requests as no-ops. The definition id is `machine.id` when present, @@ -1176,7 +1199,10 @@ export { StorageCheckFailure } * its checkpoint, and the step that exits it saves its stop, so a child runs * exactly while its state is stored. `enqueue.sendTo` with the descriptor of a * child sends to the child that runs once the step is stored, and drops the - * event when none does. The child's `parent` is the target of its parent. A + * event when none does. `enqueue.stop` with the descriptor of a child stops the + * running child in the same transaction, settles its invocation progress so it + * does not restart while the state stays active, and ignores a child that does + * not run. The child's `parent` is the target of its parent. A * child that ends tells its parent, which reads its output or its failure from * `Storage` and applies it as the end of the invocation. A failure of a child * fails its parent, also when the parent declares `onFailure`, because the @@ -1195,10 +1221,11 @@ export { StorageCheckFailure } * process compile and fail at run time: * * - A step whose plan sends to a target that is neither a {@link Target} nor - * the descriptor of an invoked child, or stops a child with `enqueue.stop`. It - * rejects the request as `UnsupportedProcessLocal`, or fails the machine when - * the step applies an outcome. Planning-time raised events remain part of the - * current macrostep. + * the descriptor of an invoked child, or stops a child address rather than + * the descriptor of an invoked child with `enqueue.stop`. It rejects the + * request as `UnsupportedProcessLocal`, or fails the machine when the step + * applies an outcome. Planning-time raised events remain part of the current + * macrostep. * - Work that uses an operation of `children` from the context of its input * mapper. It fails the machine. * - A machine whose requirements are `any`, such as an erased one. When any of its @@ -1396,7 +1423,7 @@ export const make: < > & EnsureExecutable & Machine.Machine.RootCompatible - & EnsureJsonEncoded + & EnsureJsonEncoded & EnsureSupported, options: { readonly version: string @@ -1406,7 +1433,7 @@ export const make: < */ readonly readInterval?: Duration.Input | undefined }, - ...input: [...Machine.Machine.InputArgs] + ...input: readonly [] | [...Machine.Machine.InputArgs] ) => ClusterMachine< Type, Machine.Machine< diff --git a/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts b/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts index 569586c..889f8b9 100644 --- a/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts +++ b/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts @@ -6,8 +6,8 @@ * directly. When the Cluster runner and its SQL database live in another thread * or process — such as a browser Web Worker running `SingleRunner` over * SQLite-WASM — callers on the main thread have neither `Sharding` nor - * `Storage`. `ClusterMachineProxy` bridges `send`, `snapshot`, `changes`, and - * `join` over any `RpcServer.Protocol` / `RpcClient.Protocol`. + * `Storage`. `ClusterMachineProxy` bridges `start`, `send`, `snapshot`, + * `changes`, and `join` over any `RpcServer.Protocol` / `RpcClient.Protocol`. * * **Example** (Serving and calling a Cluster machine over RPC) * @@ -34,7 +34,7 @@ * * const rpcs = ClusterMachineProxy.toRpcGroup(Counter) * - * rpcs.requests.size // => 3 + * rpcs.requests.size // => 4 * ``` * * @since 0.48.0 @@ -70,18 +70,31 @@ export type EncodedSnapshot = typeof EncodedSnapshot.Type type MachineEvents = Machine.Machine.InputEvents +type StartPayload = Machine.Machine.InputSchema extends typeof Schema.Void + ? Schema.Struct<{ readonly entityId: typeof Schema.String }> + : Schema.Struct<{ + readonly entityId: typeof Schema.String + readonly input: Machine.Machine.InputSchema + }> + type SendErrorSchema = typeof internal.SendErrorSchema type ReadErrorSchema = typeof internal.ReadErrorSchema /** * Union of prefixed RPC definitions derived for one `ClusterMachine` adapter: - * `${Type}.send`, `${Type}.snapshot`, and `${Type}.changes`. + * `${Type}.start`, `${Type}.send`, `${Type}.snapshot`, and `${Type}.changes`. * * @category models * @since 0.48.0 */ export type Rpcs = + | Rpc.Rpc< + `${Type}.start`, + StartPayload, + typeof Schema.Void, + SendErrorSchema + > | Rpc.Rpc< `${Type}.send`, Schema.Struct<{ @@ -112,6 +125,16 @@ export type Rpcs = */ export type RpcHandlers = Rpc.ToHandler> +/** + * Services required to encode startup input sent by a remote {@link Client}. + * + * @category models + * @since 0.49.0 + */ +export type StartServices = Machine.Machine.InputSchema extends typeof Schema.Void + ? never + : Machine.Machine.InputSchema["EncodingServices"] + /** * Services required to encode events sent by a remote {@link Client}. * @@ -136,12 +159,16 @@ export type ReadServices = Machine.Machine.Snapsh > /** - * Event decoding services required by an RPC server hosting a proxy for `M`. + * Event and startup input decoding services required by an RPC server hosting + * a proxy for `M`. * * @category models * @since 0.48.0 */ -export type ServerServices = MachineEvents[number]["DecodingServices"] +export type ServerServices = + | MachineEvents[number]["DecodingServices"] + | (Machine.Machine.InputSchema extends typeof Schema.Void ? never + : Machine.Machine.InputSchema["DecodingServices"]) /** * Options passed through to `RpcServer.layer` by {@link toLayer}. @@ -182,6 +209,18 @@ export interface Client { /** Entity id of the machine this client addresses. */ readonly entityId: string + /** + * Starts the entity with its initial input, committing its initial state when + * it has no checkpoint yet. + */ + readonly start: ( + ...input: [...Machine.Machine.InputArgs>] + ) => Effect.Effect< + void, + ClusterMachine.Rejected | ClusterMachine.ClientError | RpcClientError.RpcClientError, + StartServices + > + /** Sends one input event and waits until it is committed or rejected. */ readonly send: ( event: Machine.Machine.EventInputOf> @@ -226,8 +265,8 @@ export interface Client { } /** - * Derives an `RpcGroup` exposing `${Type}.send`, `${Type}.snapshot`, and - * `${Type}.changes` for one `ClusterMachine` adapter. + * Derives an `RpcGroup` exposing `${Type}.start`, `${Type}.send`, + * `${Type}.snapshot`, and `${Type}.changes` for one `ClusterMachine` adapter. * * **When to use** * diff --git a/packages/effect-machine/test/unstable/cluster/Children.test.ts b/packages/effect-machine/test/unstable/cluster/Children.test.ts index 056870c..86ede7e 100644 --- a/packages/effect-machine/test/unstable/cluster/Children.test.ts +++ b/packages/effect-machine/test/unstable/cluster/Children.test.ts @@ -47,6 +47,8 @@ const Counter = Machine.child("counter", counter) // The same machine, invoked by a state that takes its snapshots. const Watched = Machine.child("watched", counter) +const LocalAddress = Machine.childAddress("local-child") + const host = Machine.make({ id: "Host", root: Machine.state({ @@ -67,6 +69,8 @@ const host = Machine.make({ Finish: {}, Break: {}, Cancel: {}, + StopChild: {}, + StopAddress: {}, Doom: {}, Watch: {}, Glance: {}, @@ -102,11 +106,18 @@ const host = Machine.make({ Add: { stay: true, commands: ({ event }, enqueue) => enqueue.sendTo(Counter, { _tag: "Add", by: event.by }) }, Finish: { stay: true, commands: (_, enqueue) => enqueue.sendTo(Counter, { _tag: "Finish" }) }, Break: { stay: true, commands: (_, enqueue) => enqueue.sendTo(Counter, { _tag: "Break" }) }, + StopChild: { stay: true, commands: (_, enqueue) => enqueue.stop(Counter) }, + StopAddress: { stay: true, commands: (_, enqueue) => enqueue.stop(LocalAddress) }, Counted: { update: { Hosting: ({ event }) => ({ counted: event.count }) } }, Cancel: { target: "Idle" } } }, - Ready: { on: { Add: { stay: true, commands: ({ event }, enqueue) => enqueue.sendTo(Counter, event) } } }, + Ready: { + on: { + Add: { stay: true, commands: ({ event }, enqueue) => enqueue.sendTo(Counter, event) }, + StopChild: { stay: true, commands: (_, enqueue) => enqueue.stop(Counter) } + } + }, Watching: { invoke: { src: "watched", @@ -332,4 +343,53 @@ describe("ClusterMachine child machines", () => { // The parent stays, as a local one does when its work stops its child. assert.deepStrictEqual(leafOf(storage), { path: "Driving" }) }).pipe(Effect.scoped)) + + it.effect("stop an invoked child with enqueue.stop, settle its progress, and ignore when not running", () => + Effect.gen(function*() { + const { messages, runner, storage } = yield* start + yield* runner.send({ _tag: "Host", name: "ada" }) + yield* runner.send({ _tag: "Add", by: 3 }) + yield* settle + assert.deepStrictEqual(leafOf(storage, childType, "worker-1/counter/1")?.value, { _tag: "Counting", count: 3 }) + + // Stopping the child via enqueue.stop stays in Hosting, stops the child + // once, and marks its invocation progress as Settled so it will not restart. + const stopResult = yield* runner.send({ _tag: "StopChild" }) + assert.strictEqual(stopResult._tag, "Accepted") + yield* settle + assert.deepStrictEqual(leafOf(storage)?.value, { _tag: "Hosting", counted: 3 }) + assert.deepStrictEqual(progressOf(storage), { Hosting: { counter: { _tag: "Settled" } } }) + assert.deepStrictEqual(checkpointOf(storage, childType, "worker-1/counter/1")?.status, { _tag: "Stopped" }) + const stopEnvelopes = messages.driver.journal.filter((envelope) => + envelope._tag === "Request" && envelope.tag === "stop" + ) + assert.strictEqual(stopEnvelopes.length, 1) + + // Subsequent sends and stops for the settled child are dropped without restarting it. + assert.strictEqual((yield* runner.send({ _tag: "Add", by: 4 }))._tag, "Accepted") + assert.strictEqual((yield* runner.send({ _tag: "StopChild" }))._tag, "Accepted") + yield* settle + assert.deepStrictEqual(childrenOf(storage), ["worker-1/counter/1"]) + assert.deepStrictEqual(leafOf(storage, childType, "worker-1/counter/1")?.value, { _tag: "Counting", count: 3 }) + + // Exiting and re-entering Hosting starts a fresh child entity. + yield* runner.send({ _tag: "Cancel" }) + yield* runner.send({ _tag: "Host", name: "grace" }) + yield* settle + assert.strictEqual(childrenOf(storage).length, 2) + }).pipe(Effect.scoped)) + + it.effect("reject enqueue.stop with a local child address as UnsupportedProcessLocal", () => + Effect.gen(function*() { + const { runner, storage } = yield* start + yield* runner.send({ _tag: "Host", name: "ada" }) + yield* settle + const commitsBefore = storage.commits + const rejected = yield* runner.send({ _tag: "StopAddress" }) + assert.strictEqual(rejected._tag, "Rejected") + if (rejected._tag === "Rejected") { + assert.strictEqual(rejected.reason, "UnsupportedProcessLocal") + } + assert.strictEqual(storage.commits, commitsBefore) + }).pipe(Effect.scoped)) }) diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts index 4885dca..dc07407 100644 --- a/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts @@ -69,6 +69,7 @@ const UnsupportedChildMachine = Machine.make({ } }) const UnsupportedChild = Machine.child("unsupported", UnsupportedChildMachine) +const UnsupportedChildAddress = Machine.childAddress("unsupported") const makeCounter = (state: { readonly gate: Latch.Latch initialEntries: number @@ -127,7 +128,7 @@ const makeCounter = (state: { SpawnFromAction: { branches: [{ target: "Count" }], resolve: ({ state: current, select }, enqueue) => { - enqueue.stop(UnsupportedChild) + enqueue.stop(UnsupportedChildAddress) return select.target("Count", { data: current, decoded: true }) } } @@ -1129,7 +1130,7 @@ describe("ClusterMachine", () => { Work: { branches: [{ target: "Fresh" }], resolve: ({ select }, enqueue) => { - enqueue.stop(UnsupportedChild) + enqueue.stop(UnsupportedChildAddress) return select.target("Fresh") } } @@ -1818,7 +1819,7 @@ describe("ClusterMachine", () => { throw: /^Error: cannot leave$/, schema: /MachineSchemaDecodeError/, encode: /^SnapshotEncodeFailure: /, - command: /^UnsupportedProcessLocal: Machine commands require a managed local process$/, + command: /^UnsupportedProcessLocal: Machine commands on Cluster stop only an invoked child machine$/, emission: /^EmissionFailure: No durable enqueue handler was configured$/ } for (const [to, failure] of Object.entries(outcomes)) { @@ -1852,7 +1853,7 @@ describe("ClusterMachine", () => { case "encode": return select.target("Sealed", { data: new Sealed({ value: "sealed" }), decoded: true }) case "command": - enqueue.stop(UnsupportedChild) + enqueue.stop(UnsupportedChildAddress) return select.target("Idle") default: enqueue.emit(new Changed({ value: 1 })) diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachineClient.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachineClient.test.ts index 7ad084e..6fbd62f 100644 --- a/packages/effect-machine/test/unstable/cluster/ClusterMachineClient.test.ts +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachineClient.test.ts @@ -1,7 +1,9 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Schema } from "effect" +import { Effect, Option, Schema } from "effect" +import { TestClock } from "effect/testing" import { Machine } from "../../../src/index.js" -import { makeMessages, makeTestStorage, startRunner } from "./support/harness.js" +import { ClusterMachine } from "../../../src/unstable/cluster/index.js" +import { makeLayer, makeMessages, makeTestStorage, startRunner } from "./support/harness.js" const Events = Machine.events({ Rename: { name: Schema.NonEmptyString }, Archive: {} }) const Internal = Machine.internalEvents({ Touched: {} }) @@ -84,4 +86,156 @@ describe("ClusterMachine.Client", () => { assert.strictEqual(rejected.reason, "PersistenceFailure") yield* runner.client.send(Events.Archive()) }).pipe(Effect.scoped)) + + it.effect("starts a machine without input explicitly and treats duplicate starts as no-ops", () => + Effect.gen(function*() { + const { runner, storage } = yield* start + assert.isTrue( + Option.isNone( + yield* runner.client.snapshot.pipe(Effect.provideService(ClusterMachine.Storage, storage.service)) + ) + ) + yield* runner.client.start() + assert.strictEqual(storage.commits, 1) + const snap = Option.getOrThrow( + yield* runner.client.snapshot.pipe(Effect.provideService(ClusterMachine.Storage, storage.service)) + ) + assert.strictEqual(snap.status, "active") + assert.strictEqual(snap.revision, 1) + assert.deepStrictEqual(snap.state, { + path: "", + value: undefined, + state: { path: "Draft", value: { _tag: "Draft", name: "untitled" } } + }) + + // Duplicate start on an active entity is an idempotent no-op. + yield* runner.client.start() + assert.strictEqual(storage.commits, 1) + }).pipe(Effect.scoped)) + + it.effect("starts entities with distinct per-entity input and rejects send before start when no default input is set", () => + Effect.gen(function*() { + class OrderInput extends Schema.Class("OrderInput")({ + customer: Schema.NonEmptyString, + total: Schema.Number + }) {} + const OrderEvents = Machine.events({ Add: { amount: Schema.Number } }) + const orderMachine = Machine.make({ + id: "OrderWithInput", + root: Machine.state({ + fields: { customer: Schema.String }, + states: { Open: { fields: { total: Schema.Number } } } + }), + input: OrderInput, + events: OrderEvents + }).handle({ + root: ({ input }) => ({ customer: input.customer }), + initial: { target: "Open", data: ({ input }) => ({ total: input.total }) }, + states: { + Open: { + on: { + Add: { update: { Open: ({ event, state }) => ({ total: state.total + event.amount }) } } + } + } + } + }) + + const Order = ClusterMachine.make("OrderWithInput", orderMachine, { version: "1" }) + const storage = makeTestStorage() + yield* Effect.gen(function*() { + yield* TestClock.adjust(1) + const makeClient = yield* Order.client + const alice = makeClient("order-alice") + const bob = makeClient("order-bob") + + // Sending before start rejects when no default input was provided to make. + const beforeStart = yield* rejection(alice.send(OrderEvents.Add({ amount: 5 }))) + assert.strictEqual(beforeStart.reason, "InvalidEvent") + assert.strictEqual(storage.commitAttempts, 0) + + // Invalid input is rejected locally before hitting storage. + const badInput = yield* rejection(alice.start({ customer: "", total: 10 })) + assert.strictEqual(badInput.reason, "InvalidEvent") + assert.strictEqual(storage.commitAttempts, 0) + + // Start two entities with distinct inputs. + yield* alice.start(new OrderInput({ customer: "alice", total: 10 })) + yield* bob.start(new OrderInput({ customer: "bob", total: 50 })) + yield* alice.send(OrderEvents.Add({ amount: 5 })) + + const aliceSnap = Option.getOrThrow(yield* alice.snapshot) + const bobSnap = Option.getOrThrow(yield* bob.snapshot) + assert.deepStrictEqual(aliceSnap.state.value, { _tag: "", customer: "alice" }) + assert.deepStrictEqual(aliceSnap.state.state, { path: "Open", value: { _tag: "Open", total: 15 } }) + assert.deepStrictEqual(bobSnap.state.value, { _tag: "", customer: "bob" }) + assert.deepStrictEqual(bobSnap.state.state, { path: "Open", value: { _tag: "Open", total: 50 } }) + + // Calling start again on an active entity is a no-op and preserves its state. + yield* bob.start(new OrderInput({ customer: "other", total: 999 })) + const bobAfter = Option.getOrThrow(yield* bob.snapshot) + assert.deepStrictEqual(bobAfter.state.value, { _tag: "", customer: "bob" }) + assert.strictEqual(bobAfter.revision, 1) + }).pipe( + Effect.provide(makeLayer(Order, storage.service)), + Effect.provideService(ClusterMachine.Storage, storage.service) + ) + }).pipe(Effect.scoped)) + + it.effect("allows start(customInput) to override a static default input and rejects start on a failed entity", () => + Effect.gen(function*() { + const InputEvents = Machine.events({ Bump: {} }) + const machineWithDefault = Machine.make({ + id: "DefaultInputMachine", + root: Machine.state({ + states: { + Counting: { fields: { count: Schema.Number } }, + Failing: {} + } + }), + input: Schema.Number, + events: InputEvents, + effects: { fail: Effect.die(new Error("boom")) } + }).handle({ + initial: { target: "Counting", data: ({ input }) => ({ count: input }) }, + states: { + Counting: { + on: { + Bump: { + target: "Failing" + } + } + }, + Failing: { + invoke: { src: "fail" } + } + } + }) + + const Defaulted = ClusterMachine.make("DefaultInputMachine", machineWithDefault, { version: "1" }, 100) + const storage = makeTestStorage() + yield* Effect.gen(function*() { + yield* TestClock.adjust(1) + const makeClient = yield* Defaulted.client + const custom = makeClient("custom-1") + const auto = makeClient("auto-1") + + // Explicit start uses per-entity input instead of the static default (100). + yield* custom.start(42) + const customSnap = Option.getOrThrow(yield* custom.snapshot) + assert.deepStrictEqual(customSnap.state.state, { path: "Counting", value: { _tag: "Counting", count: 42 } }) + + // Auto-start via send uses the static default (100), then enters Failing and fails. + yield* auto.send(InputEvents.Bump()) + yield* Effect.forEach(Array.from({ length: 50 }), () => Effect.yieldNow, { discard: true }) + const failedSnap = Option.getOrThrow(yield* auto.snapshot) + assert.strictEqual(failedSnap.status, "failed") + + // Starting a failed entity rejects with MachineFailed. + const rejected = yield* rejection(auto.start(7)) + assert.strictEqual(rejected.reason, "MachineFailed") + }).pipe( + Effect.provide(makeLayer(Defaulted, storage.service)), + Effect.provideService(ClusterMachine.Storage, storage.service) + ) + }).pipe(Effect.scoped)) }) diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts index fa8299e..c3b1b92 100644 --- a/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts @@ -525,4 +525,78 @@ describe("ClusterMachineProxy", () => { assert.strictEqual(receipt.total, 15) })) }).pipe(Effect.scoped)) + + it.live("starts per-entity input machines over Web Worker MessagePort RPC and validates input locally", () => + Effect.gen(function*() { + class AccountInput extends Schema.Class("AccountInput")({ + owner: Schema.NonEmptyString, + opening: Schema.Number + }) {} + const AccountEvents = Machine.events({ Deposit: { amount: Schema.Number } }) + const accountMachine = Machine.make({ + id: "ProxyAccount", + root: Machine.state({ + fields: { owner: Schema.String }, + states: { Open: { fields: { balance: Schema.Number } } } + }), + input: AccountInput, + events: AccountEvents + }).handle({ + root: ({ input }) => ({ owner: input.owner }), + initial: { target: "Open", data: ({ input }) => ({ balance: input.opening }) }, + states: { + Open: { + on: { Deposit: { update: { Open: ({ event, state }) => ({ balance: state.balance + event.amount }) } } } + } + } + }) + const Account = ClusterMachine.make("ProxyAccount", accountMachine, { version: "1", readInterval: "50 millis" }) + + const { clientLayer, serverLayer } = makeMessagePortPair() + const sqlLayer = SqliteClient.layer({ filename: ":memory:" }) + const clusterLayer = Sharding.layer.pipe( + Layer.provideMerge(Runners.layerNoop), + Layer.provideMerge(SqlMessageStorage.layer), + Layer.provideMerge(SqlMachineStorage.layer), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(shardingConfig), + Layer.provide(Digest.layerWebCrypto), + Layer.provide(sqlLayer) + ) + const workerLayer = ClusterMachineProxy.toLayer(Account).pipe( + Layer.provide(Account.toLayer()), + Layer.provide(clusterLayer), + Layer.provide(serverLayer) + ) + yield* runWorkerInFiber(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + const makeAccount = yield* ClusterMachineProxy.client(Account).pipe(Effect.provide(clientContext)) + + const a = makeAccount("acct-1") + const b = makeAccount("acct-2") + + // Send before start is rejected. + const before = yield* Effect.flip(a.send(AccountEvents.Deposit({ amount: 5 }))) + assert.strictEqual(before._tag, "Rejected") + if (before._tag === "Rejected") assert.strictEqual(before.reason, "InvalidEvent") + + // Invalid input is rejected locally before crossing the worker boundary. + const bad = yield* Effect.flip(a.start({ owner: "", opening: 0 })) + assert.strictEqual(bad._tag, "Rejected") + if (bad._tag === "Rejected") assert.strictEqual(bad.reason, "InvalidEvent") + + yield* a.start(new AccountInput({ owner: "ada", opening: 100 })) + yield* b.start(new AccountInput({ owner: "grace", opening: 250 })) + yield* a.send(AccountEvents.Deposit({ amount: 25 })) + // Duplicate start is a no-op. + yield* b.start(new AccountInput({ owner: "ignored", opening: 0 })) + + const snapA = Option.getOrThrow(yield* a.snapshot) + const snapB = Option.getOrThrow(yield* b.snapshot) + assert.deepStrictEqual(snapA.state.value, { _tag: "", owner: "ada" }) + assert.deepStrictEqual(snapA.state.state, { path: "Open", value: { _tag: "Open", balance: 125 } }) + assert.deepStrictEqual(snapB.state.value, { _tag: "", owner: "grace" }) + assert.deepStrictEqual(snapB.state.state, { path: "Open", value: { _tag: "Open", balance: 250 } }) + }).pipe(Effect.scoped)) }) diff --git a/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts b/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts index 659e9a9..291a3ea 100644 --- a/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts +++ b/packages/effect-machine/typetest/unstable/cluster/ClusterMachine.tst.ts @@ -184,7 +184,7 @@ describe("ClusterMachine", () => { ClusterMachine.Storage | MessageStorage.MessageStorage | Sharding.Sharding | PlanningService >() }) - it("captures non-void machine input", () => { + it("supports per-entity and default non-void machine input, and checks JSON-encoded input schemas", () => { const inputStates = Machine.state({ fields: { input: Input }, states: { Count } }) const inputMachine = Machine.make({ id: "InputCounter", @@ -200,13 +200,43 @@ describe("ClusterMachine", () => { root: ({ input }) => ({ input }), states: { Count: {} } }) - expect(ClusterMachine.make).type.not.toBeCallableWith("InputCounterEntity", inputMachine, { version: "1" }) + expect(ClusterMachine.make).type.toBeCallableWith("InputCounterEntity", inputMachine, { version: "1" }) expect(ClusterMachine.make).type.toBeCallableWith( "InputCounterEntity", inputMachine, { version: "1" }, new Input({ value: 1 }) ) + expect(ClusterMachine.make).type.not.toBeCallableWith( + "InputCounterEntity", + inputMachine, + { version: "1" }, + "not-an-input" + ) + const inputAdapter = ClusterMachine.make("InputCounterEntity", inputMachine, { version: "1" }) + const inputClient = null! as Effect.Success extends (id: string) => infer C ? C : never + expect(inputClient.start).type.toBeCallableWith(new Input({ value: 1 })) + expect(inputClient.start).type.not.toBeCallableWith() + expect(inputClient.start).type.not.toBeCallableWith("not-an-input") + + const noInputClient = null! as Effect.Success extends (id: string) => infer C ? C : never + expect(noInputClient.start).type.toBeCallableWith() + expect(noInputClient.start).type.not.toBeCallableWith(1) + + const resourceInputMachine = Machine.make({ + id: "ResourceInputCounter", + root: states, + events: Machine.eventsFromSchemas(Reset), + input: LocalResource + }).handle({ + initial: { target: "Count", decoded: true, data: new Count({ value: 0 }) }, + states: { Count: {} } + }) + expect(ClusterMachine.make).type.not.toBeCallableWith( + "ResourceInputEntity", + resourceInputMachine, + { version: "1" } + ) }) it("uses encoded Machine snapshots in checkpoints", () => { expect().type.toBe() diff --git a/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts b/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts index 1491bed..2893859 100644 --- a/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts +++ b/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts @@ -71,6 +71,14 @@ describe("ClusterMachineProxy", () => { const client = null! as ClusterMachineProxy.Client + expect(client.start()).type.toBe< + Effect.Effect< + void, + ClusterMachine.Rejected | ClusterMachine.ClientError | RpcClientError.RpcClientError + > + >() + expect(client.start).type.not.toBeCallableWith(1) + expect(client.send(Events.Add({ by: 1 }))).type.toBe< Effect.Effect< void, @@ -104,4 +112,27 @@ describe("ClusterMachineProxy", () => { > >() }) + + it("types per-entity start input on proxy clients", () => { + const inputMachine = Machine.make({ + id: "ProxyInput", + root: Machine.state({ states: { Open: { fields: { count: Schema.Number } } } }), + input: Schema.Number, + events: Events + }).handle({ + initial: { target: "Open", data: ({ input }) => ({ count: input }) }, + states: { Open: {} } + }) + const InputAdapter = ClusterMachine.make("ProxyInput", inputMachine, { version: "1" }) + const makeClient = ClusterMachineProxy.client(InputAdapter) + const client = null! as Effect.Success extends (id: string) => infer C ? C : never + expect(client.start(42)).type.toBe< + Effect.Effect< + void, + ClusterMachine.Rejected | ClusterMachine.ClientError | RpcClientError.RpcClientError + > + >() + expect(client.start).type.not.toBeCallableWith() + expect(client.start).type.not.toBeCallableWith("42") + }) })