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
29 changes: 29 additions & 0 deletions .changeset/cluster-machine-proxy.md
Original file line number Diff line number Diff line change
@@ -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`.
37 changes: 37 additions & 0 deletions LLMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions ai-docs/src/35_cluster/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
32 changes: 31 additions & 1 deletion packages/effect-machine/src/internal/machine/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown, Rejected>
}

const adapterMeta = new WeakMap<object, AdapterMeta>()

/** 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,
Expand Down Expand Up @@ -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
}
211 changes: 211 additions & 0 deletions packages/effect-machine/src/internal/machine/clusterProxy.ts
Original file line number Diff line number Diff line change
@@ -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<object, RpcGroup.RpcGroup<any>>()

export const toRpcGroup = <
const Type extends string,
M extends Machine.Machine.Any,
Services
>(
adapter: ClusterMachine.ClusterMachine<Type, M, Services>
): RpcGroup.RpcGroup<Public.Rpcs<Type, M>> => {
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<Type, M, Services>
): Layer.Layer<
Public.RpcHandlers<Type, M>,
never,
Sharding.Sharding | ClusterMachine.ReadServices<M>
> => {
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<ClusterMachine.ReadServices<M>>()

const readerOf = (entityId: string) => {
const id = EntityId.make(entityId)
return ClusterRead.makeEncoded<M>({
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<Type, M, Services>,
options?: Public.ServerOptions
): Layer.Layer<
never,
never,
| RpcServer.Protocol
| Sharding.Sharding
| ClusterMachine.ReadServices<M>
| Public.ServerServices<M>
> =>
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<Type, M, Services>
): Effect.Effect<
(entityId: string) => Public.Client<M>,
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<string, (payload: any) => any>
const sendTag = `${meta.type}.send`
const snapshotTag = `${meta.type}.snapshot`
const changesTag = `${meta.type}.changes`

return (entityId: string): Public.Client<M> => {
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<ClusterRead.WireSnapshot>,
any
>).pipe(
Effect.flatMap(Option.match({
onNone: () => Effect.succeedNone,
onSome: (wire) => Effect.asSome(ClusterRead.decodeWire<M>(meta.machine as M, wire))
}))
)

const changes = (rpc[changesTag]!({ entityId }) as Stream.Stream<ClusterRead.WireSnapshot, any>).pipe(
Stream.mapEffect((wire) => ClusterRead.decodeWire<M>(meta.machine as M, wire))
)

const join = ClusterRead.joinChanges<M, any, any>(changes)

return { entityId, send, snapshot, changes, join } as Public.Client<M>
}
})
Loading