Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/cluster-stop-and-start.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 19 additions & 8 deletions LLMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
27 changes: 19 additions & 8 deletions ai-docs/src/35_cluster/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
37 changes: 34 additions & 3 deletions packages/effect-machine/src/internal/machine/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,21 @@ const decodeInputEvent = (
)
)

const decodeMachineInput = (
machine: Machine.Machine.Any,
input: unknown
): Effect.Effect<unknown, Rejected> =>
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<Storage["Service"]> = Effect.sync(() => {
Expand Down Expand Up @@ -124,6 +139,7 @@ export interface AdapterMeta {
readonly version: string
readonly readInterval: Duration.Input
readonly decodeEvent: (event: unknown) => Effect.Effect<unknown, Rejected>
readonly decodeInput: (input: unknown) => Effect.Effect<unknown, Rejected>
}

const adapterMeta = new WeakMap<object, AdapterMeta>()
Expand Down Expand Up @@ -174,7 +190,7 @@ export const make = <
readonly version: string
readonly readInterval?: Duration.Input | undefined
},
...input: [...Machine.Machine.InputArgs<Input>]
...input: readonly [] | [...Machine.Machine.InputArgs<Input>]
): ClusterMachine<
Type,
Machine.Machine<
Expand Down Expand Up @@ -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
Expand All @@ -268,6 +284,19 @@ const build = (
Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
)

const startThroughClient = (
rpc: EntityClient,
args: ReadonlyArray<unknown>
): Effect.Effect<void, Rejected | ClientError> =>
decodeMachineInput(machine, args[0]).pipe(
Effect.flatMap((decoded) =>
rpc.start(
(machine.input === undefined ? {} : { input: decoded }) as never
) as Effect.Effect<typeof SendResult.Type, ClientError>
),
Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
)

const protocol: ClusterTarget.Protocol = {
entity,
machine,
Expand Down Expand Up @@ -380,6 +409,7 @@ const build = (
return {
entityId,
...reader,
start: (...args: ReadonlyArray<unknown>) => startThroughClient(rpc, args),
send: (event) => sendThroughClient(rpc, event)
}
}
Expand All @@ -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
}
13 changes: 10 additions & 3 deletions packages/effect-machine/src/internal/machine/clusterChild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`
Expand Down Expand Up @@ -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 extends Schema.Top>(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.
Expand Down
Loading