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-entity-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@typeonce/effect-machine": minor
---

Expose Cluster `Entity` tuning options, `shardGroup` routing, and a transactional `onCommit` hook on `ClusterMachine`.

- `ClusterMachine.make` now accepts an optional `shardGroup?: (entityId: EntityId) => string` option, annotating both the entity and any invoked child entities with `ClusterSchema.ShardGroup`.
- `ClusterMachine.toLayer` now accepts `LayerOptions<M, RE, RC>`, forwarding Effect Cluster's `Entity.toLayer` options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`, `disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and its children.
- Added `LayerOptions.onCommit` and `CommitEvent<M>`, which run inside the same `MessageStorage` transaction immediately after each checkpoint commit (active, done, or failed) so SQL read-model projections and audit tables commit or roll back atomically with the checkpoint.
14 changes: 13 additions & 1 deletion LLMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1668,7 +1668,19 @@ const InvoiceLive = Invoice.toLayer().pipe(

`version` is stored with every checkpoint. A checkpoint written by another
definition id or version is refused, so change it together with a migration of
the stored checkpoints.
the stored checkpoints. Pass `shardGroup` to `ClusterMachine.make` to route
entities (and their invoked child entities) to named Cluster shard groups.

`adapter.toLayer(options)` forwards standard Effect Cluster `Entity.toLayer`
options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`,
`disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and
its children. It also accepts transactional hooks that run inside the same
`MessageStorage` transaction as the checkpoint write:

- `enqueue(event)` durably writes emitted events to an outbox table.
- `onCommit({ entityId, checkpoint, snapshot })` runs after every committed
checkpoint (active, done, failed), so SQL read-model projections or audit
tables commit or roll back atomically with the machine state.

State values, completion outputs, startup input, and public input events must
have JSON encoded forms. A schema that does not is a compile error that names
Expand Down
14 changes: 13 additions & 1 deletion ai-docs/src/35_cluster/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,19 @@ const InvoiceLive = Invoice.toLayer().pipe(

`version` is stored with every checkpoint. A checkpoint written by another
definition id or version is refused, so change it together with a migration of
the stored checkpoints.
the stored checkpoints. Pass `shardGroup` to `ClusterMachine.make` to route
entities (and their invoked child entities) to named Cluster shard groups.

`adapter.toLayer(options)` forwards standard Effect Cluster `Entity.toLayer`
options (`maxIdleTime`, `concurrency`, `mailboxCapacity`, `mailboxMetrics`,
`disableFatalDefects`, `defectRetryPolicy`, `spanAttributes`) to the entity and
its children. It also accepts transactional hooks that run inside the same
`MessageStorage` transaction as the checkpoint write:

- `enqueue(event)` durably writes emitted events to an outbox table.
- `onCommit({ entityId, checkpoint, snapshot })` runs after every committed
checkpoint (active, done, failed), so SQL read-model projections or audit
tables commit or roll back atomically with the machine state.

State values, completion outputs, startup input, and public input events must
have JSON encoded forms. A schema that does not is a compile error that names
Expand Down
113 changes: 97 additions & 16 deletions packages/effect-machine/src/internal/machine/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import { Rpc } from "effect/rpc"
import type * as Schedule from "effect/Schedule"
import * as Schema from "effect/Schema"
import type * as Machine from "../../Machine.js"
import type { Checkpoint } from "../../unstable/cluster/ClusterMachine.js"
import type { Client, ClientError, ClusterMachine } from "../../unstable/cluster/ClusterMachine.js"
import type {
Checkpoint,
Client,
ClientError,
ClusterMachine,
LayerOptions
} from "../../unstable/cluster/ClusterMachine.js"
import * as ClusterChild from "./clusterChild.js"
import * as ClusterInstance from "./clusterInstance.js"
import { CommitResult, Rejected, SendResult, Storage } from "./clusterProtocol.js"
Expand Down Expand Up @@ -189,6 +195,7 @@ export const make = <
options: {
readonly version: string
readonly readInterval?: Duration.Input | undefined
readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined
},
...input: readonly [] | [...Machine.Machine.InputArgs<Input>]
): ClusterMachine<
Expand Down Expand Up @@ -229,16 +236,70 @@ interface Parent {
readonly snapshots: boolean
}

/** Entity layer tuning options forwarded to `Entity.toLayer`. */
interface EntityLayerOptions {
readonly maxIdleTime?: Duration.Input | undefined
readonly concurrency?: number | "unbounded" | undefined
readonly mailboxCapacity?: number | "unbounded" | undefined
readonly mailboxMetrics?: boolean | undefined
readonly disableFatalDefects?: boolean | undefined
readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined
readonly spanAttributes?: Record<string, string> | undefined
}

const pickEntityLayerOptions = (
options: LayerOptions<any, any, any> | undefined
): EntityLayerOptions | undefined => {
if (options === undefined) return undefined
const out: {
maxIdleTime?: Duration.Input
concurrency?: number | "unbounded"
mailboxCapacity?: number | "unbounded"
mailboxMetrics?: boolean
disableFatalDefects?: boolean
defectRetryPolicy?: Schedule.Schedule<any, unknown>
spanAttributes?: Record<string, string>
} = {}
let hasAny = false
if (options.maxIdleTime !== undefined) {
out.maxIdleTime = options.maxIdleTime
hasAny = true
}
if (options.concurrency !== undefined) {
out.concurrency = options.concurrency
hasAny = true
}
if (options.mailboxCapacity !== undefined) {
out.mailboxCapacity = options.mailboxCapacity
hasAny = true
}
if (options.mailboxMetrics !== undefined) {
out.mailboxMetrics = options.mailboxMetrics
hasAny = true
}
if (options.disableFatalDefects !== undefined) {
out.disableFatalDefects = options.disableFatalDefects
hasAny = true
}
if (options.defectRetryPolicy !== undefined) {
out.defectRetryPolicy = options.defectRetryPolicy
hasAny = true
}
if (options.spanAttributes !== undefined) {
out.spanAttributes = options.spanAttributes
hasAny = true
}
return hasAny ? out : undefined
}

/** An adapter, and the adapters of the child machines that its states invoke. */
interface Built {
readonly machine: Machine.Machine.Any
readonly entity: Entity.Entity<string, any>
readonly protocol: ClusterTarget.Protocol
readonly client: Effect.Effect<(entityId: string) => Client<any>, never, Sharding.Sharding>
readonly target: (entityId: string) => ClusterTarget.Target
readonly toLayer: (layerOptions?: {
readonly enqueue?: (event: any) => Effect.Effect<void, unknown, any>
}) => Layer.Layer<never, never, any>
readonly toLayer: (layerOptions?: LayerOptions<any, any, any>) => Layer.Layer<never, never, any>
}

const build = (
Expand All @@ -247,6 +308,7 @@ const build = (
options: {
readonly version: string
readonly readInterval?: Duration.Input | undefined
readonly shardGroup?: ((entityId: EntityId.EntityId) => string) | undefined
},
input: ReadonlyArray<unknown>,
parent: Parent | undefined
Expand All @@ -262,7 +324,7 @@ const build = (
// `deliver` carries an event another machine sends, `wake` is the delayed
// message of a long timer, `start` and `stop` come from the parent of a
// child, and `ended` and `snapshot` from a child. Only machines send them.
const entity = Entity.make(type, [
const rawEntity = Entity.make(type, [
rpc,
deliver,
ClusterWake.WakeRpc,
Expand All @@ -271,6 +333,9 @@ const build = (
ClusterChild.EndedRpc,
ClusterChild.SnapshotRpc
])
const entity = options.shardGroup === undefined
? rawEntity
: rawEntity.annotate(ClusterSchema.ShardGroup, options.shardGroup)
const definitionId = machine.id ?? type
const publicTags: ReadonlySet<PropertyKey> = new Set(Reflect.ownKeys(machine.events))

Expand Down Expand Up @@ -308,25 +373,39 @@ const build = (
}
const target = (entityId: string): ClusterTarget.Target => new ClusterTarget.Target(protocol, entityId)

// Each child runs as an entity of its own, with the version of its parent.
// Each child runs as an entity of its own, with the version and shard group of its parent.
const snapshots = ClusterChild.snapshotsOf(toImpl(machine).handlers)
const children = Array.from(
ClusterChild.childrenOf(toImpl(machine).handlers),
([childId, child]) =>
[
([childId, child]) => {
const childShardGroup = options.shardGroup === undefined
? undefined
: (childEntityId: EntityId.EntityId) => {
const parentId = ClusterChild.parentEntityIdOf(childEntityId, childId)
return options.shardGroup!(parentId === undefined ? childEntityId : EntityId.make(parentId))
}
return [
childId,
build(ClusterChild.entityTypeOf(type, childId), child.machine, { version: options.version }, [], {
protocol,
childId,
snapshots: snapshots.has(childId)
})
build(
ClusterChild.entityTypeOf(type, childId),
child.machine,
{ version: options.version, shardGroup: childShardGroup },
[],
{
protocol,
childId,
snapshots: snapshots.has(childId)
}
)
] as const
}
)
const childProtocols: ReadonlyMap<string, ClusterTarget.Protocol> = new Map(
children.map(([childId, child]) => [childId, child.protocol])
)

const toLayer: Built["toLayer"] = (layerOptions) => {
const entityLayerOptions = pickEntityLayerOptions(layerOptions)
// Each live entity builds its own handlers, and so owns its own instance.
const layer = entity.toLayer(
Effect.gen(function*() {
Expand All @@ -345,6 +424,7 @@ const build = (
messageStorage,
// A child has no observers, so what it emits reaches nobody.
enqueue: parent === undefined ? layerOptions?.enqueue : () => Effect.void,
onCommit: parent === undefined ? layerOptions?.onCommit : undefined,
keepAlive: yield* makeKeepAlive,
wake: {
threshold: yield* ClusterWake.threshold,
Expand Down Expand Up @@ -382,11 +462,12 @@ const build = (
})
}
return entity.of(handlers as never)
})
}),
entityLayerOptions
)
return children.length === 0
? layer
: Layer.mergeAll(layer, ...children.map(([, child]) => child.toLayer()))
: Layer.mergeAll(layer, ...children.map(([, child]) => child.toLayer(entityLayerOptions)))
}

const client = Effect.gen(function*() {
Expand Down
Loading