From 8e03bc40f87a74f8f048dacdbe1fe06f81639559 Mon Sep 17 00:00:00 2001 From: SandroMaglione Date: Wed, 25 Nov 2026 13:14:28 +1300 Subject: [PATCH] Add ClusterMachineProxy to expose Cluster machines over RPC and Web Workers --- .changeset/cluster-machine-proxy.md | 29 + LLMS.md | 37 ++ ai-docs/src/35_cluster/index.md | 37 ++ .../src/internal/machine/cluster.ts | 32 +- .../src/internal/machine/clusterProxy.ts | 211 +++++++ .../src/internal/machine/clusterRead.ts | 127 ++++- .../unstable/cluster/ClusterMachineProxy.ts | 333 +++++++++++ .../src/unstable/cluster/index.ts | 8 + .../cluster/ClusterMachineProxy.test.ts | 528 ++++++++++++++++++ .../cluster/ClusterMachineProxy.tst.ts | 107 ++++ scripts/check-architecture.mjs | 3 + 11 files changed, 1429 insertions(+), 23 deletions(-) create mode 100644 .changeset/cluster-machine-proxy.md create mode 100644 packages/effect-machine/src/internal/machine/clusterProxy.ts create mode 100644 packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts create mode 100644 packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts create mode 100644 packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts diff --git a/.changeset/cluster-machine-proxy.md b/.changeset/cluster-machine-proxy.md new file mode 100644 index 0000000..f4244bd --- /dev/null +++ b/.changeset/cluster-machine-proxy.md @@ -0,0 +1,29 @@ +--- +"@typeonce/effect-machine": minor +--- + +Add `ClusterMachineProxy` to `@typeonce/effect-machine/cluster` to expose `ClusterMachine` adapters over any `effect/rpc` transport, including Web Workers, `SharedWorker`, Node worker threads, WebSockets, and HTTP. + +When a Cluster runner and its SQL database live in another thread or process — such as a browser Web Worker running `SingleRunner` with `SqlMachineStorage` — callers on the main thread have neither `Sharding` nor `ClusterMachine.Storage`. `ClusterMachineProxy` derives prefixed `send`, `snapshot`, and `changes` RPCs and gives callers a typed `ClusterMachineProxy.Client` with `send`, `snapshot`, `changes`, and `join`: + +```ts +import { ClusterMachineProxy } from "@typeonce/effect-machine/cluster" +import { Effect, Layer } from "effect" +import { RpcServer } from "effect/rpc" + +// Inside the worker or RPC server: +const ServerLive = ClusterMachineProxy.toLayer(Order).pipe( + Layer.provide(Order.toLayer()), + Layer.provide(ClusterLive), + Layer.provide(RpcServer.layerProtocolWorkerRunner) +) + +// On the main thread or remote client (requires only RpcClient.Protocol and Scope): +const program = Effect.gen(function*() { + const client = (yield* ClusterMachineProxy.client(Order))("order-1") + yield* client.send(Events.Pay({ amount: 50 })) + const snapshot = yield* client.snapshot +}) +``` + +Compose multiple Cluster machines onto one worker or server with `ClusterMachineProxy.toRpcGroup(A).merge(ClusterMachineProxy.toRpcGroup(B))` and `ClusterMachineProxy.layerHandlers`. diff --git a/LLMS.md b/LLMS.md index 077da81..68d4d28 100644 --- a/LLMS.md +++ b/LLMS.md @@ -1776,6 +1776,43 @@ To write a store of your own, run `ClusterMachine.checkStorage` against it in your tests, with the `withTransaction` of its `MessageStorage`. It fails with the first part of the contract the store breaks. +### Run in a Web Worker or over RPC + +`ClusterMachine` and `SqlMachineStorage` have no Node.js dependencies, so a +single-node Cluster can run inside a Web Worker or `SharedWorker` with +`SingleRunner.layer` and a browser SQL client such as `@effect/sql-sqlite-wasm` +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): + +```ts +// Inside the Web Worker: serve one machine over RpcServer.Protocol +const WorkerLive = ClusterMachineProxy.toLayer(Invoice).pipe( + Layer.provide(Invoice.toLayer()), + Layer.provide(ClusterLive), + Layer.provide(RpcServer.layerProtocolWorkerRunner) +) + +// On the main thread: zero Sharding, zero Storage, zero SQL +const program = Effect.gen(function*() { + const client = (yield* ClusterMachineProxy.client(Invoice))("invoice-1") + yield* client.send(Events.Send({ invoiceId: "inv-1" })) + const latest = yield* client.snapshot + const receipt = yield* client.join +}) +``` + +To host several machines on one worker or server, merge their groups with +`ClusterMachineProxy.toRpcGroup(A).merge(ClusterMachineProxy.toRpcGroup(B))` and +provide each with `ClusterMachineProxy.layerHandlers`. When using +`RpcClient.layerProtocolWorker` with `size: 1`, set `concurrency` above `1` (for +example `{ size: 1, concurrency: 100 }`) so streaming `changes` or `join` calls +do not block concurrent `send` calls. + ## Effect Machine implementation review Use this review after a machine and its UI adapter have been implemented. Look diff --git a/ai-docs/src/35_cluster/index.md b/ai-docs/src/35_cluster/index.md index dad2ea4..8be38cf 100644 --- a/ai-docs/src/35_cluster/index.md +++ b/ai-docs/src/35_cluster/index.md @@ -147,3 +147,40 @@ checkpoint, the events it sends, and the reply commit in one transaction. Its To write a store of your own, run `ClusterMachine.checkStorage` against it in your tests, with the `withTransaction` of its `MessageStorage`. It fails with the first part of the contract the store breaks. + +### Run in a Web Worker or over RPC + +`ClusterMachine` and `SqlMachineStorage` have no Node.js dependencies, so a +single-node Cluster can run inside a Web Worker or `SharedWorker` with +`SingleRunner.layer` and a browser SQL client such as `@effect/sql-sqlite-wasm` +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): + +```ts +// Inside the Web Worker: serve one machine over RpcServer.Protocol +const WorkerLive = ClusterMachineProxy.toLayer(Invoice).pipe( + Layer.provide(Invoice.toLayer()), + Layer.provide(ClusterLive), + Layer.provide(RpcServer.layerProtocolWorkerRunner) +) + +// On the main thread: zero Sharding, zero Storage, zero SQL +const program = Effect.gen(function*() { + const client = (yield* ClusterMachineProxy.client(Invoice))("invoice-1") + yield* client.send(Events.Send({ invoiceId: "inv-1" })) + const latest = yield* client.snapshot + const receipt = yield* client.join +}) +``` + +To host several machines on one worker or server, merge their groups with +`ClusterMachineProxy.toRpcGroup(A).merge(ClusterMachineProxy.toRpcGroup(B))` and +provide each with `ClusterMachineProxy.layerHandlers`. When using +`RpcClient.layerProtocolWorker` with `size: 1`, set `concurrency` above `1` (for +example `{ size: 1, concurrency: 100 }`) so streaming `changes` or `join` calls +do not block concurrent `send` calls. diff --git a/packages/effect-machine/src/internal/machine/cluster.ts b/packages/effect-machine/src/internal/machine/cluster.ts index 1064546..33ff610 100644 --- a/packages/effect-machine/src/internal/machine/cluster.ts +++ b/packages/effect-machine/src/internal/machine/cluster.ts @@ -116,6 +116,27 @@ const makeKeepAlive = Effect.gen(function*() { : Effect.provideContext(Entity.keepAlive(enabled), context) }) +/** Internal metadata captured for a `ClusterMachine` adapter, used by sibling internal bridges. */ +export interface AdapterMeta { + readonly type: string + readonly machine: Machine.Machine.Any + readonly definitionId: string + readonly version: string + readonly readInterval: Duration.Input + readonly decodeEvent: (event: unknown) => Effect.Effect +} + +const adapterMeta = new WeakMap() + +/** Reads the internal metadata of a `ClusterMachine` created by {@link make}. */ +export const getAdapterMeta = (adapter: object): AdapterMeta => { + const meta = adapterMeta.get(adapter) + if (meta === undefined) { + throw new Error("Expected a ClusterMachine created by ClusterMachine.make") + } + return meta +} + export const make = < const Type extends string, States extends Machine.Machine.StateSchemas, @@ -364,5 +385,14 @@ const build = ( } }) - return { machine, entity, protocol, client, target, toLayer } + const built: Built = { machine, entity, protocol, client, target, toLayer } + adapterMeta.set(built, { + type, + machine, + definitionId, + version: options.version, + readInterval: options.readInterval ?? "1 second", + decodeEvent: (event) => decodeInputEvent(machine, publicTags, event) + }) + return built } diff --git a/packages/effect-machine/src/internal/machine/clusterProxy.ts b/packages/effect-machine/src/internal/machine/clusterProxy.ts new file mode 100644 index 0000000..3cf12ee --- /dev/null +++ b/packages/effect-machine/src/internal/machine/clusterProxy.ts @@ -0,0 +1,211 @@ +/** + * Transport-independent RPC proxy for `ClusterMachine`. + * + * Exposes `send`, `snapshot`, and `changes` of a `ClusterMachine` as an + * `effect/rpc` `RpcGroup`, so clients without direct `Sharding` or `Storage` + * access (such as a browser main thread talking to a Web Worker or + * `SharedWorker`, a Node worker thread, or a remote HTTP/WebSocket client) can + * drive and observe Cluster machines with full type safety. + * + * @since 0.48.0 + */ +import { ClusterError, EntityAddress, EntityId, Sharding } from "effect/cluster" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import { Rpc, RpcClient, RpcGroup, RpcServer } from "effect/rpc" +import * as Schema from "effect/Schema" +import type * as Scope from "effect/Scope" +import * as Stream from "effect/Stream" +import type * as Machine from "../../Machine.js" +import type * as ClusterMachine from "../../unstable/cluster/ClusterMachine.js" +import type * as Public from "../../unstable/cluster/ClusterMachineProxy.js" +import * as Cluster from "./cluster.js" +import { ReadError, Rejected } from "./clusterProtocol.js" +import * as ClusterRead from "./clusterRead.js" +import * as Protocol from "./protocol.js" + +/** Wire schema for a validated committed checkpoint returned by proxy reads. */ +export const EncodedSnapshot = Schema.Union([ + Schema.Struct({ + status: Schema.Literal("active"), + revision: Schema.Number, + snapshot: Schema.Unknown + }), + Schema.Struct({ + status: Schema.Literal("done"), + revision: Schema.Number, + snapshot: Schema.Unknown + }), + Schema.Struct({ + status: Schema.Literal("failed"), + revision: Schema.Number, + snapshot: Schema.Unknown, + failure: Schema.String + }), + Schema.Struct({ + status: Schema.Literal("stopped"), + revision: Schema.Number, + snapshot: Schema.Unknown + }) +]) + +export const SendErrorSchema = Schema.Union([ + Rejected, + ClusterError.MailboxFull, + ClusterError.AlreadyProcessingMessage, + ClusterError.PersistenceError, + ClusterError.EntityNotAssignedToRunner +]) + +export const ReadErrorSchema = Schema.Union([ + ReadError, + ClusterError.PersistenceError +]) + +const rpcGroups = new WeakMap>() + +export const toRpcGroup = < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +): RpcGroup.RpcGroup> => { + const cached = rpcGroups.get(adapter) + if (cached !== undefined) return cached + const meta = Cluster.getAdapterMeta(adapter) + const eventSchema = Schema.Union(Protocol.inputEventSchemas(meta.machine)) + const sendRpc = Rpc.make(`${meta.type}.send`, { + payload: Schema.Struct({ + entityId: Schema.String, + event: eventSchema + }), + success: Schema.Void, + error: SendErrorSchema + }) + const snapshotRpc = Rpc.make(`${meta.type}.snapshot`, { + payload: Schema.Struct({ entityId: Schema.String }), + success: Schema.Option(EncodedSnapshot), + error: ReadErrorSchema + }) + const changesRpc = Rpc.make(`${meta.type}.changes`, { + payload: Schema.Struct({ entityId: Schema.String }), + success: EncodedSnapshot, + error: ReadErrorSchema, + stream: true + }) + const group = RpcGroup.make(sendRpc, snapshotRpc, changesRpc) + rpcGroups.set(adapter, group) + return group as never +} + +export const layerHandlers = < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +): Layer.Layer< + Public.RpcHandlers, + never, + Sharding.Sharding | ClusterMachine.ReadServices +> => { + const meta = Cluster.getAdapterMeta(adapter) + const group = toRpcGroup(adapter) + return group.toLayer( + Effect.gen(function*() { + const makeClient = yield* adapter.client + const sharding = yield* Sharding.Sharding + const context = yield* Effect.context>() + + const readerOf = (entityId: string) => { + const id = EntityId.make(entityId) + return ClusterRead.makeEncoded({ + machine: meta.machine, + definitionId: meta.definitionId, + version: meta.version, + address: EntityAddress.make({ + shardId: sharding.getShardId(id, adapter.entity.getShardGroup(id)), + entityType: adapter.entity.type, + entityId: id + }), + interval: meta.readInterval + }) + } + + return { + [`${meta.type}.send`]: ({ entityId, event }: { readonly entityId: string; readonly event: never }) => + makeClient(entityId).send(event), + [`${meta.type}.snapshot`]: ({ entityId }: { readonly entityId: string }) => + readerOf(entityId).snapshot.pipe(Effect.provideContext(context)), + [`${meta.type}.changes`]: ({ entityId }: { readonly entityId: string }) => + readerOf(entityId).changes.pipe(Stream.provideContext(context)) + } as never + }) + ) +} + +export const toLayer = < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine, + options?: Public.ServerOptions +): Layer.Layer< + never, + never, + | RpcServer.Protocol + | Sharding.Sharding + | ClusterMachine.ReadServices + | Public.ServerServices +> => + RpcServer.layer(toRpcGroup(adapter), options).pipe( + Layer.provide(layerHandlers(adapter)) + ) + +export const client = < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +): Effect.Effect< + (entityId: string) => Public.Client, + never, + RpcClient.Protocol | Scope.Scope +> => + Effect.gen(function*() { + const meta = Cluster.getAdapterMeta(adapter) + const group = toRpcGroup(adapter) + const rpc = (yield* RpcClient.make(group)) as Record any> + const sendTag = `${meta.type}.send` + const snapshotTag = `${meta.type}.snapshot` + const changesTag = `${meta.type}.changes` + + return (entityId: string): Public.Client => { + const send = (event: unknown) => + meta.decodeEvent(event).pipe( + Effect.flatMap((decoded) => rpc[sendTag]!({ entityId, event: decoded })) + ) + + const snapshot = (rpc[snapshotTag]!({ entityId }) as Effect.Effect< + Option.Option, + any + >).pipe( + Effect.flatMap(Option.match({ + onNone: () => Effect.succeedNone, + onSome: (wire) => Effect.asSome(ClusterRead.decodeWire(meta.machine as M, wire)) + })) + ) + + const changes = (rpc[changesTag]!({ entityId }) as Stream.Stream).pipe( + Stream.mapEffect((wire) => ClusterRead.decodeWire(meta.machine as M, wire)) + ) + + const join = ClusterRead.joinChanges(changes) + + return { entityId, send, snapshot, changes, join } as Public.Client + } + }) diff --git a/packages/effect-machine/src/internal/machine/clusterRead.ts b/packages/effect-machine/src/internal/machine/clusterRead.ts index cb376f0..008ad7b 100644 --- a/packages/effect-machine/src/internal/machine/clusterRead.ts +++ b/packages/effect-machine/src/internal/machine/clusterRead.ts @@ -35,6 +35,18 @@ export interface Reader { > } +/** Validated wire representation of a committed checkpoint, ready for RPC transport. */ +export type WireSnapshot = + | { readonly status: "active"; readonly revision: number; readonly snapshot: unknown } + | { readonly status: "done"; readonly revision: number; readonly snapshot: unknown } + | { readonly status: "failed"; readonly revision: number; readonly snapshot: unknown; readonly failure: string } + | { readonly status: "stopped"; readonly revision: number; readonly snapshot: unknown } + +export interface EncodedReader { + readonly snapshot: Effect.Effect, ReadError | PersistenceError, Services> + readonly changes: Stream.Stream> +} + export interface Options { readonly machine: Machine.Machine.Any readonly definitionId: string @@ -45,6 +57,68 @@ export interface Options { const invalid = (message: string) => new ReadError({ reason: "InvalidCheckpoint", message }) +const toWire = (snapshot: Snapshot, encoded: unknown): WireSnapshot => { + switch (snapshot.status) { + case "active": + return { status: "active", revision: snapshot.revision, snapshot: encoded } + case "done": + return { status: "done", revision: snapshot.revision, snapshot: encoded } + case "failed": + return { status: "failed", revision: snapshot.revision, snapshot: encoded, failure: snapshot.failure } + case "stopped": + return { status: "stopped", revision: snapshot.revision, snapshot: encoded } + } +} + +/** Decodes a validated wire snapshot back into a typed `ClusterMachine.Snapshot`. */ +export const decodeWire = ( + machine: M, + wire: WireSnapshot +): Effect.Effect< + Snapshot, + ReadError, + Machine.Machine.SnapshotDecodingServices> +> => + Effect.gen(function*() { + const state = yield* internalMachine.decodeSnapshot(machine, wire.snapshot).pipe( + Effect.mapError((error) => invalid(String(error.cause))) + ) + if (wire.status === "failed") { + return { status: "failed", revision: wire.revision, state, failure: wire.failure } + } + if (wire.status === "stopped") { + return { status: "stopped", revision: wire.revision, state } + } + if (wire.status === "active") { + return { status: "active", revision: wire.revision, state } + } + if (!internalMachine.isFinal(machine, state)) { + return yield* invalid("Expected a final state for a done snapshot") + } + const output = yield* Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent).pipe( + Effect.mapError((error) => invalid(String(error.cause))) + ) + return { status: "done", revision: wire.revision, state, output } + }) + +/** Waits for the terminal snapshot of a change stream and returns its output or failure. */ +export const joinChanges = ( + changes: Stream.Stream, E, R> +): Effect.Effect, MachineFailedError | E, R> => + changes.pipe( + Stream.filter((read) => read.status !== "active"), + Stream.runHead, + Effect.flatMap((read) => + Option.isNone(read) + ? Effect.die(new Error("A reader of a Cluster machine ended without a terminal checkpoint")) + : read.value.status === "failed" + ? Effect.fail(new MachineFailedError({ failure: read.value.failure })) + : read.value.status === "stopped" + ? Effect.fail(new MachineFailedError({ failure: "The child machine was stopped by its parent" })) + : Effect.succeed(read.value.output) + ) + ) + // Validates a checkpoint as an entity does when it loads one, so that a reader // refuses what the entity would refuse. const decode = Effect.fnUntraced(function*( @@ -82,6 +156,35 @@ const decode = Effect.fnUntraced(function*( return { status: "done", revision, state, output } }) +const pollChanges = ( + snapshot: Effect.Effect, E, R>, + interval: Duration.Input +): Stream.Stream => + Stream.fromEffectSchedule( + snapshot, + Schedule.spaced(Duration.fromInputUnsafe(interval)) + ).pipe( + Stream.filter(Option.isSome), + Stream.map((read) => read.value), + Stream.changesWith((left, right) => left.revision === right.revision), + Stream.takeUntil((read) => read.status !== "active") + ) + +export const makeEncoded = (options: Options): EncodedReader => { + const snapshot = Effect.gen(function*() { + const storage = yield* Storage + return yield* storage.load(options.address) + }).pipe( + Effect.flatMap(Option.match({ + onNone: () => Effect.succeedNone, + onSome: (checkpoint) => + Effect.map(decode(options, checkpoint), (decoded) => Option.some(toWire(decoded, checkpoint.snapshot))) + })) + ) as EncodedReader["snapshot"] + + return { snapshot, changes: pollChanges(snapshot, options.interval) } +} + export const make = (options: Options): Reader => { const snapshot = Effect.gen(function*() { const storage = yield* Storage @@ -96,29 +199,9 @@ export const make = (options: Options): Reader // Reads again after each interval and emits every revision it has not seen, // ending after a terminal one. Reading again is also how a reader follows an // entity that is passivated or moves: there is no subscription to lose. - const changes: Reader["changes"] = Stream.fromEffectSchedule( - snapshot, - Schedule.spaced(Duration.fromInputUnsafe(options.interval)) - ).pipe( - Stream.filter(Option.isSome), - Stream.map((read) => read.value), - Stream.changesWith((left, right) => left.revision === right.revision), - Stream.takeUntil((read) => read.status !== "active") - ) + const changes: Reader["changes"] = pollChanges(snapshot, options.interval) - const join: Reader["join"] = changes.pipe( - Stream.filter((read) => read.status !== "active"), - Stream.runHead, - Effect.flatMap((read) => - Option.isNone(read) - ? Effect.die(new Error("A reader of a Cluster machine ended without a terminal checkpoint")) - : read.value.status === "failed" - ? Effect.fail(new MachineFailedError({ failure: read.value.failure })) - : read.value.status === "stopped" - ? Effect.fail(new MachineFailedError({ failure: "The child machine was stopped by its parent" })) - : Effect.succeed(read.value.output) - ) - ) + const join: Reader["join"] = joinChanges(changes) return { snapshot, changes, join } } diff --git a/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts b/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts new file mode 100644 index 0000000..569586c --- /dev/null +++ b/packages/effect-machine/src/unstable/cluster/ClusterMachineProxy.ts @@ -0,0 +1,333 @@ +/** + * Exposes `ClusterMachine` adapters over `effect/rpc` transports, including Web + * Workers, `SharedWorker`, Node worker threads, WebSockets, and HTTP. + * + * A `ClusterMachine.Client` sends through `Sharding` and reads `Storage` + * 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`. + * + * **Example** (Serving and calling a Cluster machine over RPC) + * + * ```ts import.meta.vitest + * import { Machine } from "@typeonce/effect-machine" + * import { ClusterMachine, ClusterMachineProxy } from "@typeonce/effect-machine/cluster" + * import { Schema } from "effect" + * + * const Counter = ClusterMachine.make( + * "Counter", + * Machine.make({ + * root: Machine.state({ states: { Open: { fields: { count: Schema.Number } } } }), + * events: Machine.events({ Add: { by: Schema.Number } }) + * }).handle({ + * initial: { target: "Open", data: { count: 0 } }, + * states: { + * Open: { + * on: { Add: { update: { Open: ({ event, state }) => ({ count: state.count + event.by }) } } } + * } + * } + * }), + * { version: "1" } + * ) + * + * const rpcs = ClusterMachineProxy.toRpcGroup(Counter) + * + * rpcs.requests.size // => 3 + * ``` + * + * @since 0.48.0 + */ +import type { ClusterError, Sharding } from "effect/cluster" +import type * as Effect from "effect/Effect" +import type * as Layer from "effect/Layer" +import type * as Option from "effect/Option" +import type { Rpc, RpcClient, RpcClientError, RpcGroup, RpcSchema, RpcServer } from "effect/rpc" +import type * as Schema from "effect/Schema" +import type * as Scope from "effect/Scope" +import type * as Stream from "effect/Stream" +import * as internal from "../../internal/machine/clusterProxy.js" +import type * as Machine from "../../Machine.js" +import type * as ClusterMachine from "./ClusterMachine.js" + +/** + * Schema for the validated checkpoint summary sent over an RPC transport by + * `snapshot` and `changes`. + * + * @category schemas + * @since 0.48.0 + */ +export const EncodedSnapshot: typeof internal.EncodedSnapshot = internal.EncodedSnapshot + +/** + * Type of {@link EncodedSnapshot}. + * + * @category models + * @since 0.48.0 + */ +export type EncodedSnapshot = typeof EncodedSnapshot.Type + +type MachineEvents = Machine.Machine.InputEvents + +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`. + * + * @category models + * @since 0.48.0 + */ +export type Rpcs = + | Rpc.Rpc< + `${Type}.send`, + Schema.Struct<{ + readonly entityId: typeof Schema.String + readonly event: Schema.Union> + }>, + typeof Schema.Void, + SendErrorSchema + > + | Rpc.Rpc< + `${Type}.snapshot`, + Schema.Struct<{ readonly entityId: typeof Schema.String }>, + Schema.Option, + ReadErrorSchema + > + | Rpc.Rpc< + `${Type}.changes`, + Schema.Struct<{ readonly entityId: typeof Schema.String }>, + RpcSchema.Stream, + typeof Schema.Never + > + +/** + * Union of RPC handler services provided by {@link layerHandlers}. + * + * @category services + * @since 0.48.0 + */ +export type RpcHandlers = Rpc.ToHandler> + +/** + * Services required to encode events sent by a remote {@link Client}. + * + * @category models + * @since 0.48.0 + */ +export type SendServices = MachineEvents[number]["EncodingServices"] + +/** + * Services required to decode snapshots read by a remote {@link Client}. + * + * **Details** + * + * Unlike `ClusterMachine.ReadServices`, this does not include + * `ClusterMachine.Storage` because reads travel over the RPC protocol. + * + * @category models + * @since 0.48.0 + */ +export type ReadServices = Machine.Machine.SnapshotDecodingServices< + Machine.Machine.States +> + +/** + * Event decoding services required by an RPC server hosting a proxy for `M`. + * + * @category models + * @since 0.48.0 + */ +export type ServerServices = MachineEvents[number]["DecodingServices"] + +/** + * Options passed through to `RpcServer.layer` by {@link toLayer}. + * + * @category models + * @since 0.48.0 + */ +export interface ServerOptions { + readonly disableTracing?: boolean | undefined + readonly spanPrefix?: string | undefined + readonly spanAttributes?: Record | undefined + readonly concurrency?: number | "unbounded" | undefined + readonly disableFatalDefects?: boolean | undefined +} + +/** + * A client for one `ClusterMachine` entity accessed over an `effect/rpc` + * transport. + * + * **Details** + * + * Mirrors `ClusterMachine.Client` (`send`, `snapshot`, `changes`, `join`) + * without requiring `Sharding` or `ClusterMachine.Storage` in the caller's + * environment. Transport failures from the underlying RPC channel are reported + * as `RpcClientError.RpcClientError`. + * + * **Gotchas** + * + * When running over a single Web Worker with `RpcClient.layerProtocolWorker`, + * pass a `concurrency` greater than `1` (for example + * `{ size: 1, concurrency: 100 }`) so streaming `changes` or `join` calls do + * not occupy the worker pool's only slot and block concurrent `send` calls. + * + * @category models + * @since 0.48.0 + */ +export interface Client { + /** Entity id of the machine this client addresses. */ + readonly entityId: string + + /** Sends one input event and waits until it is committed or rejected. */ + readonly send: ( + event: Machine.Machine.EventInputOf> + ) => Effect.Effect< + void, + ClusterMachine.Rejected | ClusterMachine.ClientError | RpcClientError.RpcClientError, + SendServices + > + + /** + * Reads the latest committed checkpoint, or `None` when the machine has not + * committed one yet. + */ + readonly snapshot: Effect.Effect< + Option.Option>, + ClusterMachine.ReadError | ClusterError.PersistenceError | RpcClientError.RpcClientError, + ReadServices + > + + /** + * Streams the latest committed checkpoint and later committed revisions, once + * each, ending after a terminal checkpoint. + */ + readonly changes: Stream.Stream< + ClusterMachine.Snapshot, + ClusterMachine.ReadError | ClusterError.PersistenceError | RpcClientError.RpcClientError, + ReadServices + > + + /** + * Waits for the output of the machine, or fails with + * `ClusterMachine.MachineFailedError` when it failed or was stopped. + */ + readonly join: Effect.Effect< + Machine.Machine.Output, + | ClusterMachine.MachineFailedError + | ClusterMachine.ReadError + | ClusterError.PersistenceError + | RpcClientError.RpcClientError, + ReadServices + > +} + +/** + * Derives an `RpcGroup` exposing `${Type}.send`, `${Type}.snapshot`, and + * `${Type}.changes` for one `ClusterMachine` adapter. + * + * **When to use** + * + * Use to compose multiple Cluster machines onto one RPC server (such as a + * single Web Worker or `SharedWorker`) via `groupA.merge(groupB)`, or to attach + * RPC middleware before passing the group to `RpcServer.layer`. + * + * @see {@link layerHandlers} to provide the handlers for a merged group. + * @see {@link toLayer} for serving a single machine directly. + * @category constructors + * @since 0.48.0 + */ +export const toRpcGroup: < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +) => RpcGroup.RpcGroup> = internal.toRpcGroup + +/** + * Provides the RPC handlers for the group created by {@link toRpcGroup}. + * + * **When to use** + * + * Use alongside `RpcServer.layer` when serving one or more merged Cluster + * machine groups from a worker or server that hosts `Sharding` and + * `ClusterMachine.Storage`. + * + * @category layers + * @since 0.48.0 + */ +export const layerHandlers: < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +) => Layer.Layer< + RpcHandlers, + never, + Sharding.Sharding | ClusterMachine.ReadServices +> = internal.layerHandlers + +/** + * Serves one `ClusterMachine` adapter over the provided `RpcServer.Protocol`. + * + * **When to use** + * + * Use as a one-step server layer when a worker or endpoint serves a single + * Cluster machine. Combine with `RpcServer.layerProtocolWorkerRunner` for a Web + * Worker or `SharedWorker`, or with an HTTP/WebSocket server protocol. + * + * @category layers + * @since 0.48.0 + */ +export const toLayer: < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine, + options?: ServerOptions +) => Layer.Layer< + never, + never, + | RpcServer.Protocol + | Sharding.Sharding + | ClusterMachine.ReadServices + | ServerServices +> = internal.toLayer + +/** + * Creates a factory of remote {@link Client}s for one `ClusterMachine` adapter + * over the provided `RpcClient.Protocol`. + * + * **When to use** + * + * Use on a browser main thread (with `RpcClient.layerProtocolWorker`) or any + * remote process that talks to a Cluster runner over `effect/rpc` without + * direct access to `Sharding` or `ClusterMachine.Storage`. + * + * **Details** + * + * `send` validates input events locally before sending them over the wire, so + * events constructed by `Machine.events` work as they do locally and invalid + * events fail with `ClusterMachine.Rejected("InvalidEvent")` without reaching + * the server. + * + * @category constructors + * @since 0.48.0 + */ +export const client: < + const Type extends string, + M extends Machine.Machine.Any, + Services +>( + adapter: ClusterMachine.ClusterMachine +) => Effect.Effect< + (entityId: string) => Client, + never, + RpcClient.Protocol | Scope.Scope +> = internal.client diff --git a/packages/effect-machine/src/unstable/cluster/index.ts b/packages/effect-machine/src/unstable/cluster/index.ts index 6de364f..849a698 100644 --- a/packages/effect-machine/src/unstable/cluster/index.ts +++ b/packages/effect-machine/src/unstable/cluster/index.ts @@ -1,5 +1,13 @@ export * as ClusterMachine from "./ClusterMachine.js" +/** + * Exposes `ClusterMachine` adapters over `effect/rpc` transports, including Web + * Workers, `SharedWorker`, WebSockets, and HTTP. + * + * @since 0.48.0 + */ +export * as ClusterMachineProxy from "./ClusterMachineProxy.js" + /** * Stores the checkpoints of Cluster machines in a SQL database. * diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts new file mode 100644 index 0000000..fa8299e --- /dev/null +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachineProxy.test.ts @@ -0,0 +1,528 @@ +import { SqliteClient } from "@effect/sql-sqlite-node" +import { assert, describe, it } from "@effect/vitest" +import { Cause, Deferred, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect" +import { + MessageStorage, + RunnerHealth, + Runners, + RunnerStorage, + Sharding, + ShardingConfig, + SqlMessageStorage +} from "effect/cluster" +import { Digest } from "effect/crypto" +import { RpcClient, RpcServer } from "effect/rpc" +import { Worker, WorkerRunner } from "effect/workers" +import { Machine } from "../../../src/index.js" +import { ClusterMachine, ClusterMachineProxy, SqlMachineStorage } from "../../../src/unstable/cluster/index.js" +import { makeMessages, makeTestStorage, storageKey, type TestStorage } from "./support/harness.js" + +/** + * Pairs a `WorkerPlatform` (main thread) and `WorkerRunnerPlatform` (worker) + * over web-standard `MessageChannel` / `MessagePort` structured-clone + * messaging, exercising the exact protocol used by Web Workers and + * `SharedWorker`s. + */ +const makeMessagePortPair = () => { + const channel = new MessageChannel() + + const clientPlatform = Worker.makePlatform()({ + setup: ({ scope, worker }) => + Effect.as( + Scope.addFinalizer( + scope, + Effect.sync(() => { + worker.postMessage([1]) + worker.close() + }) + ), + worker + ), + listen: ({ emit, port, scope }) => { + const onMessage = (event: MessageEvent) => emit(event.data) + port.addEventListener("message", onMessage) + port.start() + return Scope.addFinalizer( + scope, + Effect.sync(() => { + port.removeEventListener("message", onMessage) + }) + ) + } + }) + + const serverPlatform: WorkerRunner.WorkerRunnerPlatform["Service"] = { + start: () => + Effect.gen(function*() { + const disconnects = yield* Queue.make() + const port = channel.port2 + const sendUnsafe = (_portId: number, message: O, transfers?: ReadonlyArray) => + port.postMessage([1, message], transfers as never) + const send = (portId: number, message: O, transfers?: ReadonlyArray) => + Effect.sync(() => sendUnsafe(portId, message, transfers)) + + const run = ( + handler: (portId: number, message: I) => Effect.Effect | void + ) => + Effect.scopedWith(Effect.fnUntraced(function*(scope) { + const closeLatch = Deferred.makeUnsafe() + const trackFiber = Fiber.runIn(scope) + const services = yield* Effect.context() + const runFork = Effect.runForkWith(services) + const onExit = (exit: Exit.Exit) => { + if (exit._tag === "Failure" && !Cause.hasInterruptsOnly(exit.cause)) { + runFork(Effect.logError("unhandled error in worker", exit.cause)) + } + } + + const onMessage = (event: MessageEvent) => { + const message = event.data as WorkerRunner.PlatformMessage + if (message[0] === 0) { + const result = handler(0, message[1]) + if (Effect.isEffect(result)) { + const fiber = runFork(result) + fiber.addObserver(onExit) + trackFiber(fiber) + } + } else { + Queue.offerUnsafe(disconnects, 0) + Deferred.doneUnsafe(closeLatch, Exit.void) + } + } + + port.addEventListener("message", onMessage) + port.start() + yield* Scope.addFinalizer( + scope, + Effect.sync(() => { + port.removeEventListener("message", onMessage) + port.close() + }) + ) + // Signal worker readiness, matching `BrowserWorkerRunner`. + port.postMessage([0]) + yield* Deferred.await(closeLatch) + })) + + return { run, send, sendUnsafe, disconnects } + }) + } + + const clientLayer = RpcClient.layerProtocolWorker({ size: 1, concurrency: 100 }).pipe( + Layer.provide(Layer.succeed(Worker.WorkerPlatform, clientPlatform)), + Layer.provide(Worker.layerSpawner(() => channel.port1)) + ) + + const serverLayer = RpcServer.layerProtocolWorkerRunner.pipe( + Layer.provide(Layer.succeed(WorkerRunner.WorkerRunnerPlatform, serverPlatform)) + ) + + return { clientLayer, serverLayer } +} + +const shardingConfig = ShardingConfig.layer({ + shardsPerGroup: 10, + entityMessagePollInterval: "50 millis", + entityMailboxCapacity: 100, + entityMaxIdleTime: "5 minutes" +}) + +const Events = Machine.events({ + Rename: { name: Schema.NonEmptyString }, + Add: { amount: Schema.Number }, + Finish: {}, + FailWork: {} +}) +const Internal = Machine.internalEvents({ Touched: {} }) + +class Receipt extends Schema.Class("Receipt")({ + label: Schema.String, + total: Schema.Number, + at: Schema.DateFromString +}) {} + +const counterMachine = Machine.make({ + id: "ProxyCounter", + root: Machine.state({ + states: { + Counting: { fields: { name: Schema.String, total: Schema.Number, updatedAt: Schema.DateFromString } }, + Failing: {}, + Done: { + type: "final", + fields: { name: Schema.String, total: Schema.Number, updatedAt: Schema.DateFromString }, + output: Receipt + } + } + }), + events: Events, + internalEvents: Internal, + effects: { + boom: Effect.die(new Error("work exploded")) + } +}).handle({ + initial: { + target: "Counting", + data: { name: "untitled", total: 0, updatedAt: new Date("2026-01-01T00:00:00.000Z") } + }, + states: { + Counting: { + on: { + Rename: { + target: "Counting", + data: ({ event, state }) => ({ name: event.name, total: state.total, updatedAt: state.updatedAt }) + }, + Add: { + target: "Counting", + data: ({ event, state }) => ({ + name: state.name, + total: state.total + event.amount, + updatedAt: new Date("2026-06-15T12:00:00.000Z") + }) + }, + Finish: { + target: "Done", + data: ({ state }) => ({ name: state.name, total: state.total, updatedAt: state.updatedAt }) + }, + FailWork: { target: "Failing" }, + Touched: { stay: true } + } + }, + Failing: { + invoke: { src: "boom" } + }, + Done: { + output: ({ state }) => new Receipt({ label: state.name, total: state.total, at: state.updatedAt }) + } + } +}) + +const Counter = ClusterMachine.make("ProxyCounter", counterMachine, { + version: "1", + readInterval: "50 millis" +}) + +const LedgerEvents = Machine.events({ Credit: { amount: Schema.Number } }) +const ledgerMachine = Machine.make({ + id: "ProxyLedger", + root: Machine.state({ states: { Open: { fields: { balance: Schema.Number } } } }), + events: LedgerEvents +}).handle({ + initial: { target: "Open", data: { balance: 0 } }, + states: { + Open: { + on: { + Credit: { update: { Open: ({ event, state }) => ({ balance: state.balance + event.amount }) } } + } + } + } +}) +const Ledger = ClusterMachine.make("ProxyLedger", ledgerMachine, { version: "1", readInterval: "50 millis" }) + +const OrderEvents = Machine.events({ Pay: { ledgerId: Schema.String, amount: Schema.Number } }) +const orderMachine = Machine.make({ + id: "ProxyOrder", + root: Machine.state({ states: { Open: {}, Paid: { type: "final", output: Schema.Number } } }), + events: OrderEvents +}).handle({ + initial: { target: "Open" }, + states: { + Open: { + on: { + Pay: { + target: "Paid", + commands: ({ event }, enqueue) => + enqueue.sendTo(Ledger.target(event.ledgerId), { _tag: "Credit", amount: event.amount }) + } + } + }, + Paid: { output: () => 1 } + } +}) +const Order = ClusterMachine.make("ProxyOrder", orderMachine, { version: "1", readInterval: "50 millis" }) + +const startWorkerCluster = (sqlLayer: Layer.Layer) => { + const { clientLayer, serverLayer } = makeMessagePortPair() + 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(Counter).pipe( + Layer.provide(Counter.toLayer()), + Layer.provide(clusterLayer), + Layer.provide(serverLayer) + ) + return { clientLayer, workerLayer } +} + +const runWorkerInFiber = (workerLayer: Layer.Layer) => + Effect.gen(function*() { + const ready = yield* Deferred.make() + const fiber = yield* Layer.build(workerLayer).pipe( + Effect.andThen(Deferred.succeed(ready, undefined)), + Effect.andThen(Effect.never), + Effect.scoped, + Effect.forkScoped + ) + yield* Deferred.await(ready) + return fiber + }) +const overwrite = (storage: TestStorage, entityId: string, change: Partial) => { + const key = storageKey("ProxyCounter", entityId) + const stored = storage.entries.get(key)! + storage.entries.set(key, { ...stored, ...change }) +} + +const TrialEvents = Machine.events({ Start: { ms: Schema.Number } }) +const trialMachine = Machine.make({ + id: "ProxyTrial", + root: Machine.state({ + states: { + Inactive: {}, + Running: { fields: { ms: Schema.Number } }, + Expired: { type: "final", output: Schema.String } + } + }), + events: TrialEvents, + timers: { trial: (ms: number) => `${ms} millis` as const } +}).handle({ + initial: { target: "Inactive" }, + states: { + Inactive: { on: { Start: { target: "Running", data: ({ event }) => ({ ms: event.ms }) } } }, + Running: { invoke: { src: "trial", input: ({ state }) => state.ms, onDone: { target: "Expired" } } }, + Expired: { output: () => "expired" } + } +}) +const Trial = ClusterMachine.make("ProxyTrial", trialMachine, { version: "1", readInterval: "25 millis" }) + +describe("ClusterMachineProxy", () => { + it.live("runs a SQLite ClusterMachine over Web Worker MessagePort RPC with decoded classes, dates, changes, and join", () => + Effect.gen(function*() { + const sqlLayer = SqliteClient.layer({ filename: ":memory:" }) + const { clientLayer, workerLayer } = startWorkerCluster(sqlLayer) + yield* Layer.build(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + + // Client runs with ONLY `RpcClient.Protocol` — zero `Sharding`, zero `Storage`, zero SQL. + const makeCounter = yield* ClusterMachineProxy.client(Counter).pipe(Effect.provide(clientContext)) + const client = makeCounter("c-1") + + assert.strictEqual(client.entityId, "c-1") + assert.isTrue(Option.isNone(yield* client.snapshot)) + + // Start streaming changes concurrently while sending events over the single worker. + const seenFiber = yield* client.changes.pipe( + Stream.map((snap) => `${snap.status}@${snap.revision}`), + Stream.runCollect, + Effect.forkChild + ) + + yield* client.send(Events.Rename({ name: "Q4" })) + yield* client.send({ _tag: "Add", amount: 7 }) + + const active = Option.getOrThrow(yield* client.snapshot) + assert.strictEqual(active.status, "active") + assert.strictEqual(active.revision, 2) + assert.strictEqual(active.state.state.path, "Counting") + if (active.state.state.path === "Counting") { + assert.strictEqual(active.state.state.value.name, "Q4") + assert.strictEqual(active.state.state.value.total, 7) + // DateFromString is properly decoded back into a Date instance on the client! + assert.instanceOf(active.state.state.value.updatedAt, Date) + assert.strictEqual(active.state.state.value.updatedAt.toISOString(), "2026-06-15T12:00:00.000Z") + } + + const joinFiber = yield* Effect.forkChild(client.join) + yield* client.send(Events.Finish()) + + const receipt = yield* Fiber.join(joinFiber) + assert.instanceOf(receipt, Receipt) + assert.strictEqual(receipt.label, "Q4") + assert.strictEqual(receipt.total, 7) + assert.instanceOf(receipt.at, Date) + assert.strictEqual(receipt.at.toISOString(), "2026-06-15T12:00:00.000Z") + + const seen = yield* Fiber.join(seenFiber) + assert.isTrue(seen.length >= 1) + assert.strictEqual(seen.at(-1), "done@3") + }).pipe(Effect.scoped)) + + it.live("rejects invalid and internal events locally before sending over the worker wire", () => + Effect.gen(function*() { + const sqlLayer = SqliteClient.layer({ filename: ":memory:" }) + const { clientLayer, workerLayer } = startWorkerCluster(sqlLayer) + yield* Layer.build(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + + const makeCounter = yield* ClusterMachineProxy.client(Counter).pipe(Effect.provide(clientContext)) + const client = makeCounter("c-invalid") + + const badSchema = yield* Effect.flip(client.send({ _tag: "Rename", name: "" })) + assert.strictEqual(badSchema._tag, "Rejected") + assert.strictEqual(badSchema._tag === "Rejected" && badSchema.reason, "InvalidEvent") + + const internal = yield* Effect.flip(client.send(Internal.Touched() as never)) + assert.strictEqual(internal._tag, "Rejected") + assert.strictEqual(internal._tag === "Rejected" && internal.reason, "InvalidEvent") + + // Nothing was committed on the worker. + assert.isTrue(Option.isNone(yield* client.snapshot)) + }).pipe(Effect.scoped)) + + it.live("propagates MachineFailedError and ReadError across the worker boundary", () => + Effect.gen(function*() { + const storage = makeTestStorage() + const messages = yield* makeMessages + const { clientLayer, serverLayer } = makeMessagePortPair() + const clusterLayer = Sharding.layer.pipe( + Layer.provideMerge(Runners.layerNoop), + Layer.provideMerge(Layer.succeed(MessageStorage.MessageStorage, messages.storage)), + Layer.provideMerge(Layer.succeed(ClusterMachine.Storage, storage.service)), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(shardingConfig) + ) + const workerLayer = ClusterMachineProxy.toLayer(Counter).pipe( + Layer.provide(Counter.toLayer()), + Layer.provide(clusterLayer), + Layer.provide(serverLayer) + ) + yield* Layer.build(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + + const makeCounter = yield* ClusterMachineProxy.client(Counter).pipe(Effect.provide(clientContext)) + const failing = makeCounter("c-fail") + yield* failing.send(Events.FailWork()) + + const failed = yield* Effect.flip(failing.join) + assert.strictEqual(failed._tag, "MachineFailedError") + assert.include(failed._tag === "MachineFailedError" ? failed.failure : "", "work exploded") + + const versioned = makeCounter("c-1") + yield* versioned.send(Events.Add({ amount: 1 })) + overwrite(storage, "c-1", { version: "2" }) + const readError = yield* Effect.flip(versioned.snapshot) + assert.strictEqual(readError._tag, "ReadError") + assert.strictEqual(readError._tag === "ReadError" && readError.reason, "VersionMismatch") + }).pipe(Effect.scoped)) + + it.live("hosts multiple ClusterMachines on one Web Worker with transactional cross-machine sends", () => + Effect.gen(function*() { + const sqlLayer = SqliteClient.layer({ filename: ":memory:" }) + const { clientLayer, serverLayer } = makeMessagePortPair() + 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 group = ClusterMachineProxy.toRpcGroup(Order).merge(ClusterMachineProxy.toRpcGroup(Ledger)) + const workerLayer = RpcServer.layer(group).pipe( + Layer.provide(ClusterMachineProxy.layerHandlers(Order)), + Layer.provide(ClusterMachineProxy.layerHandlers(Ledger)), + Layer.provide(Layer.mergeAll(Order.toLayer(), Ledger.toLayer())), + Layer.provide(clusterLayer), + Layer.provide(serverLayer) + ) + yield* Layer.build(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + + // Both clients share the same single-worker RpcClient.Protocol. + const makeOrder = yield* ClusterMachineProxy.client(Order).pipe(Effect.provide(clientContext)) + const makeLedger = yield* ClusterMachineProxy.client(Ledger).pipe(Effect.provide(clientContext)) + + const order = makeOrder("order-1") + const ledger = makeLedger("ledger-1") + + yield* order.send(OrderEvents.Pay({ ledgerId: "ledger-1", amount: 42 })) + assert.strictEqual(yield* order.join, 1) + + // Wait for the Ledger entity to commit the transactional `Credit` sent by Order. + const ledgerSnap = yield* ledger.changes.pipe( + Stream.take(1), + Stream.runHead, + Effect.map(Option.getOrThrow) + ) + assert.strictEqual(ledgerSnap.status, "active") + assert.strictEqual(ledgerSnap.state.state.path, "Open") + if (ledgerSnap.state.state.path === "Open") { + assert.strictEqual(ledgerSnap.state.state.value.balance, 42) + } + }).pipe(Effect.scoped)) + + it.live("runs timers inside the Cluster worker and delivers the final output to the main thread", () => + Effect.gen(function*() { + const sqlLayer = SqliteClient.layer({ filename: ":memory:" }) + const { clientLayer, serverLayer } = makeMessagePortPair() + 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(Trial).pipe( + Layer.provide(Trial.toLayer()), + Layer.provide(clusterLayer), + Layer.provide(serverLayer) + ) + yield* runWorkerInFiber(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + + const makeTrial = yield* ClusterMachineProxy.client(Trial).pipe(Effect.provide(clientContext)) + const trial = makeTrial("trial-1") + + yield* trial.send(TrialEvents.Start({ ms: 40 })) + assert.strictEqual(yield* trial.join, "expired") + }).pipe(Effect.scoped)) + + it.live("recovers from a persisted SQLite checkpoint when a new worker boots", () => + Effect.gen(function*() { + // One shared SQLite database outlives the first worker, simulating a page/worker reload. + const sqlLayer = Layer.fresh(SqliteClient.layer({ filename: ":memory:" })) + const sqlContext = yield* Layer.build(sqlLayer) + const sharedSql = Layer.succeedContext(sqlContext) + + // Boot worker #1 in its own fiber, commit two events, then shut worker #1 down cleanly. + yield* Effect.scoped(Effect.gen(function*() { + const { clientLayer, workerLayer } = startWorkerCluster(sharedSql) + yield* runWorkerInFiber(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + const makeCounter = yield* ClusterMachineProxy.client(Counter).pipe(Effect.provide(clientContext)) + const client = makeCounter("reload-1") + yield* client.send(Events.Rename({ name: "Saved" })) + yield* client.send(Events.Add({ amount: 10 })) + })) + + // Boot worker #2 against the same SQLite database and continue from revision 2. + yield* Effect.scoped(Effect.gen(function*() { + const { clientLayer, workerLayer } = startWorkerCluster(sharedSql) + yield* runWorkerInFiber(workerLayer) + const clientContext = yield* Layer.build(clientLayer) + const makeCounter = yield* ClusterMachineProxy.client(Counter).pipe(Effect.provide(clientContext)) + const client = makeCounter("reload-1") + + const before = Option.getOrThrow(yield* client.snapshot) + assert.strictEqual(before.revision, 2) + + yield* client.send(Events.Add({ amount: 5 })) + yield* client.send(Events.Finish()) + const receipt = yield* client.join + assert.strictEqual(receipt.label, "Saved") + assert.strictEqual(receipt.total, 15) + })) + }).pipe(Effect.scoped)) +}) diff --git a/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts b/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts new file mode 100644 index 0000000..1491bed --- /dev/null +++ b/packages/effect-machine/typetest/unstable/cluster/ClusterMachineProxy.tst.ts @@ -0,0 +1,107 @@ +import type { Effect, Layer, Option, Scope, Stream } from "effect" +import { Schema } from "effect" +import type { ClusterError, Sharding } from "effect/cluster" +import type { RpcClient, RpcClientError, RpcGroup, RpcServer } from "effect/rpc" +import { describe, expect, it } from "tstyche" +import { Machine } from "../../../src/index.js" +import { ClusterMachine, ClusterMachineProxy } from "../../../src/unstable/cluster/index.js" + +const Events = Machine.events({ + Add: { by: Schema.Number }, + Finish: {} +}) + +const counter = Machine.make({ + id: "Counter", + root: Machine.state({ + states: { + Counting: { fields: { count: Schema.Number } }, + Done: { type: "final", fields: { count: Schema.Number }, output: Schema.Number } + } + }), + events: Events +}).handle({ + initial: { target: "Counting", data: { count: 0 } }, + states: { + Counting: { + on: { + Add: { target: "Counting", data: ({ event, state }) => ({ count: state.count + event.by }) }, + Finish: { target: "Done", data: ({ state }) => ({ count: state.count }) } + } + }, + Done: { output: ({ state }) => state.count } + } +}) + +const Counter = ClusterMachine.make("Counter", counter, { version: "1" }) + +describe("ClusterMachineProxy", () => { + it("derives an RpcGroup, handler layer, and server layer", () => { + const group = ClusterMachineProxy.toRpcGroup(Counter) + expect(group).type.toBe>>() + + const handlers = ClusterMachineProxy.layerHandlers(Counter) + expect(handlers).type.toBe< + Layer.Layer< + ClusterMachineProxy.RpcHandlers<"Counter", typeof counter>, + never, + Sharding.Sharding | ClusterMachine.ReadServices + > + >() + + const server = ClusterMachineProxy.toLayer(Counter) + expect(server).type.toBe< + Layer.Layer< + never, + never, + RpcServer.Protocol | Sharding.Sharding | ClusterMachine.ReadServices + > + >() + }) + + it("exposes a remote client requiring only RpcClient.Protocol and Scope", () => { + const makeClient = ClusterMachineProxy.client(Counter) + expect(makeClient).type.toBe< + Effect.Effect< + (entityId: string) => ClusterMachineProxy.Client, + never, + RpcClient.Protocol | Scope.Scope + > + >() + + const client = null! as ClusterMachineProxy.Client + + expect(client.send(Events.Add({ by: 1 }))).type.toBe< + Effect.Effect< + void, + ClusterMachine.Rejected | ClusterMachine.ClientError | RpcClientError.RpcClientError + > + >() + expect(client.send).type.not.toBeCallableWith({ _tag: "Add", by: "1" }) + expect(client.send).type.not.toBeCallableWith({ _tag: "Unknown" }) + + expect(client.snapshot).type.toBe< + Effect.Effect< + Option.Option>, + ClusterMachine.ReadError | ClusterError.PersistenceError | RpcClientError.RpcClientError + > + >() + + expect(client.changes).type.toBe< + Stream.Stream< + ClusterMachine.Snapshot, + ClusterMachine.ReadError | ClusterError.PersistenceError | RpcClientError.RpcClientError + > + >() + + expect(client.join).type.toBe< + Effect.Effect< + number, + | ClusterMachine.MachineFailedError + | ClusterMachine.ReadError + | ClusterError.PersistenceError + | RpcClientError.RpcClientError + > + >() + }) +}) diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs index 2a867bb..4e1755b 100644 --- a/scripts/check-architecture.mjs +++ b/scripts/check-architecture.mjs @@ -296,6 +296,9 @@ export const checkArchitecture = ({ "src/internal/machine/clusterProtocol.ts", "src/internal/machine/clusterStorageCheck.ts" ])], + ["src/unstable/cluster/ClusterMachineProxy.ts", new Set([ + "src/internal/machine/clusterProxy.ts" + ])], ["src/unstable/cluster/SqlMachineStorage.ts", new Set([ "src/internal/machine/clusterSqlStorage.ts", "src/internal/machine/clusterProtocol.ts"