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
23 changes: 23 additions & 0 deletions .changeset/align-send-error-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
"@typeonce/effect-machine": minor
---

Align every caller-awaited `send` and `sendTo` operation with `MachineRef.send` so its error channel matches its runtime behavior.

When a waiting caller sends an event that the receiving machine's event schema refuses, the call now fails with `MachineSchemaDecodeError` and leaves the receiving machine running across `LocalMachine`, `AtomMachine`, and `ClusterMachine`. This applies to:

- `Machine.sendTo` (for both `ChildMachine` descriptors and `ChildAddress` values)
- `ChildOwner.sendTo`, `MachineRuntime.sendTo`, `ChildMachineRuntime.sendTo`, and `MachineStep.Children.sendTo`
- `Logic.Endpoint.send` and `Logic.InitialContext.sendTo`
- `MachineTarget.send` on `self`, `parent`, and `ClusterMachine.target`

Transition commands (`enqueue.sendTo`) have no waiting caller and keep their existing behavior: a refused event fails the receiving machine on `LocalMachine` and refuses the sending step on `ClusterMachine`.

Callers that previously handled only `StoppedError` on `sendTo` or `Logic.Endpoint.send` (for example in infallible finalizers or typed `Machine.logic` handlers) must now also handle or defect on `MachineSchemaDecodeError`:

```ts
yield * Machine.sendTo(child, event).pipe(
Effect.catchTag("StoppedError", () => Effect.void),
Effect.catchTag("MachineSchemaDecodeError", (error) => Effect.logWarning(error))
)
```
2 changes: 1 addition & 1 deletion .changeset/local-rejects-refused-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"@typeonce/effect-machine": minor
---

`send` of a `LocalMachine` reference now rejects an event that the schema of the machine refuses with `MachineSchemaDecodeError`, and the machine keeps running, as `Machine.toStep` and `ClusterMachine` already do. `MachineTarget.send` and `MachineRef.send` add `MachineSchemaDecodeError` to their error channel, and so do the `send` atoms of `AtomMachine` and a rejected `MachineTest` send. An event that another machine, a child, or work delivers is not checked at its `send`: a refused one still fails the machine that plans it.
`send` of a `LocalMachine` reference now rejects an event that the schema of the machine refuses with `MachineSchemaDecodeError`, and the machine keeps running, as `Machine.toStep` and `ClusterMachine` already do. `MachineTarget.send` and `MachineRef.send` add `MachineSchemaDecodeError` to their error channel, and so do the `send` atoms of `AtomMachine` and a rejected `MachineTest` send. An event that a transition command (`enqueue.sendTo`) delivers is not checked at its send: a refused one still fails the machine that plans it.

A timer that cannot start now has one failure mode: `Machine.MachineStep.Work.Timer.duration()` returns an `Exit`, which fails when the input mapper or the source throws and when the input names no duration. Every host settles the timer with that failure where it would have started.

Expand Down
25 changes: 15 additions & 10 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,22 @@ layers use `toImpl` to read them instead of treating the erased public machine a

Runtime responsibilities are separated as follows:

- `process.ts` compiles machine definitions into process logic, for roots and for
child machines, and implements `LocalMachine`.
- `runtime.ts` allocates a root runtime and selects an execution strategy. It is
bound to a function that builds the logic of a child machine, because child
descriptors hold no process logic.
- `step.ts` owns the pure machine protocol shared by every host (`LocalMachine`,
`ClusterMachine`, `Machine.toStep`, and `MachineTest`), parameterized by an
execution plan (`executionPlan.ts`) and state ownership (`"Owned"` or
`"Persistent"`).
- `stepHost.ts` carries out an owned step inside a local process: commands,
stopping and starting invoked work, emissions, and synchronous draining.
- `process.ts` wires machine definitions onto `stepHost.ts` and `runtime.ts`,
for roots and for child machines, and implements `LocalMachine`.
- `runtime.ts` allocates a root runtime and binds scope ownership and prepared
startup. It receives a function that builds the logic of a child machine,
because child descriptors hold no process logic.
- `runtimeProtocol.ts` owns shared process contracts, child ownership, mailboxes,
and observation. It receives startup functions from the coordinator so child
startup does not create a dependency back to either execution strategy.
- `runtimeGeneric.ts` runs the general Effect worker and supervisor.
- `runtimeCompiled.ts` runs compiled statecharts, including synchronous owned
child startup. It preserves the same lifecycle contract as the generic runtime.
and observation.
- `runtimeCompiled.ts` is the single local process driver for both machines
(draining compiled executions, including synchronous owned child startup) and
general `Machine.logic` processes.

Consumers import directly from the module that owns a contract. Runtime modules
must remain independent of planning and statechart semantics. The Cluster adapter
Expand Down
46 changes: 32 additions & 14 deletions packages/effect-machine/src/Machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1405,8 +1405,12 @@ export declare namespace Logic {
/** Stops the addressed child process. */
readonly stop: Effect.Effect<void>

/** Sends an event to the addressed child process. */
readonly send: (event: Event) => Effect.Effect<void, StoppedError>
/**
* Sends an event to the addressed process. When the endpoint belongs to a
* machine whose event schema refuses the event, fails with
* {@link MachineSchemaDecodeError} and leaves the machine running.
*/
readonly send: (event: Event) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
}

/**
Expand Down Expand Up @@ -1466,20 +1470,24 @@ export declare namespace Logic {
readonly spawn: Spawn<Event>

/**
* Sends an event to a machine target or typed parent-local child address.
* An endpoint, such as `parent`, takes every event, and a machine target
* can reject one that its schema refuses.
* Sends an event to a process endpoint, machine target, or typed
* parent-local child address. When the addressed receiver is a machine
* whose event schema refuses the event, fails with
* {@link MachineSchemaDecodeError} and leaves the receiver running.
*/
readonly sendTo: {
<TargetEvent>(target: Endpoint<TargetEvent>, event: TargetEvent): Effect.Effect<void, StoppedError>
<TargetEvent>(
target: Endpoint<TargetEvent>,
event: TargetEvent
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
<TargetEvent>(
target: MachineTarget<TargetEvent>,
event: TargetEvent
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
<Address extends ChildAddress<never>>(
id: Address,
event: ChildAddress.Event<Address>
): Effect.Effect<void, StoppedError>
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
}

/** Stops a child process selected by its parent-local address. */
Expand Down Expand Up @@ -1693,11 +1701,15 @@ export interface ChildOwner<OwnerEvent> {
ChildMachine.StartRequirements<Child>
>

/** Sends an event to one active child. Missing children are ignored. */
/**
* Sends an event to one active child. Missing children are ignored. An event
* that the child's event schema refuses fails with
* {@link MachineSchemaDecodeError} and leaves the child running.
*/
readonly sendTo: <Child extends ChildMachine.Any>(
child: Child,
event: ChildMachine.Event<Child>
) => Effect.Effect<void, StoppedError>
) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>

/** Stops one active child. Missing children are ignored. */
readonly stop: <Child extends ChildMachine.Any>(child: Child) => Effect.Effect<void>
Expand Down Expand Up @@ -8174,11 +8186,15 @@ export declare namespace MachineStep {
options: SpawnOptions | undefined
) => StepEffect<MachineRef<unknown, never, unknown, unknown, unknown>, unknown>

/** Sends an event to a child. A child that does not run is ignored. */
/**
* Sends an event to a child. A child that does not run is ignored. When the
* child is a machine whose event schema refuses the event, fails with
* {@link MachineSchemaDecodeError} and leaves the child running.
*/
readonly sendTo: (
child: ChildMachine.Any | ChildAddress<never>,
event: unknown
) => Effect.Effect<void, StoppedError>
) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>

/** Stops a child. A child that does not run is ignored. */
readonly stop: (child: ChildMachine.Any | ChildAddress<never>) => Effect.Effect<void>
Expand Down Expand Up @@ -8643,7 +8659,9 @@ export const spawn: {
*
* With the descriptor of an invoked child machine, it requires only
* {@link ChildMachineRuntime}, which `ClusterMachine` provides too. With a
* child address, it requires {@link MachineRuntime}.
* child address, it requires {@link MachineRuntime}. When the addressed child
* is a machine whose event schema refuses the event, fails with
* {@link MachineSchemaDecodeError} and leaves the child running.
*
* @category runtime
* @since 0.4.0
Expand All @@ -8652,11 +8670,11 @@ export const sendTo: {
<Child extends ChildMachine.Any>(
child: Child,
event: ChildMachine.Event<Child>
): Effect.Effect<void, StoppedError, ChildMachineRuntime>
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError, ChildMachineRuntime>
<Address extends ChildAddress<never>>(
id: Address,
event: ChildAddress.Event<Address>
): Effect.Effect<void, StoppedError, MachineRuntime>
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError, MachineRuntime>
} = internal.sendTo as never

/**
Expand Down
15 changes: 11 additions & 4 deletions packages/effect-machine/src/internal/machine/capability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
ChildMachine,
Logic,
MachineRef,
MachineSchemaDecodeError,
SpawnOptions,
StoppedError
} from "../../Machine.js"
Expand Down Expand Up @@ -62,12 +63,14 @@ export class MachineRuntime extends Context.Service<MachineRuntime, {

/**
* Sends an event to an active child of the running machine. A missing child is
* ignored.
* ignored. When the addressed child is a machine whose event schema refuses
* the event, fails with `MachineSchemaDecodeError` and leaves the child
* running.
*/
readonly sendTo: (
child: ChildMachine.Any | ChildAddress<never>,
event: unknown
) => Effect.Effect<void, StoppedError>
) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>

/**
* Stops an active child of the running machine. A missing child is ignored.
Expand Down Expand Up @@ -107,9 +110,13 @@ export class MachineRuntime extends Context.Service<MachineRuntime, {
export class ChildMachineRuntime extends Context.Service<ChildMachineRuntime, {
/**
* Sends an event to the child that runs for a descriptor. A child that does
* not run is ignored.
* not run is ignored. An event that the child's event schema refuses fails
* with `MachineSchemaDecodeError` and leaves the child running.
*/
readonly sendTo: (child: ChildMachine.Any, event: unknown) => Effect.Effect<void, StoppedError>
readonly sendTo: (
child: ChildMachine.Any,
event: unknown
) => Effect.Effect<void, StoppedError | MachineSchemaDecodeError>

/** Stops the child that runs for a descriptor. A child that does not run is ignored. */
readonly stopChild: (child: ChildMachine.Any) => Effect.Effect<void>
Expand Down
45 changes: 39 additions & 6 deletions packages/effect-machine/src/internal/machine/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* @since 0.4.0
*/
import * as Cause from "effect/Cause"
import { ClusterSchema, Entity, EntityAddress, EntityId, MessageStorage, Sharding } from "effect/cluster"
import type { Snowflake } from "effect/cluster"
import type * as Duration from "effect/Duration"
Expand All @@ -26,7 +27,7 @@ import { CommitResult, Rejected, SendResult, Storage } from "./clusterProtocol.j
import * as ClusterRead from "./clusterRead.js"
import * as ClusterTarget from "./clusterTarget.js"
import * as ClusterWake from "./clusterWake.js"
import type { MachineSchemaDecodeError } from "./errors.js"
import { MachineSchemaDecodeError } from "./errors.js"
import { toImpl } from "./implementation.js"
import * as Protocol from "./protocol.js"
import type { EnsureExecutable } from "./readiness.js"
Expand All @@ -42,6 +43,30 @@ const invalidEvent = (error: MachineSchemaDecodeError): Rejected =>
: `The event ${error.event} does not match its schema`
})

/**
* Decodes an input event for a waiting caller (`MachineTarget.send` or
* `sendTo`), failing with `MachineSchemaDecodeError` when refused.
*/
const decodeInputEventError = (
machine: Machine.Machine.Any,
publicTags: ReadonlySet<PropertyKey>,
event: unknown
): Effect.Effect<unknown, MachineSchemaDecodeError> =>
Protocol.decodeEvent(machine, event).pipe(
Effect.flatMap((decoded) =>
publicTags.has(decoded._tag)
? Effect.succeed(decoded)
: Effect.fail(
new MachineSchemaDecodeError({
machineId: machine.id,
boundary: "event",
event: String(decoded._tag),
cause: Cause.die(new Error(`The event ${String(decoded._tag)} is not an input event`))
})
)
)
)

/**
* Decodes an event as `LocalMachine` does before it sends it, so that a client
* takes what a local reference takes, and refuses only public input events.
Expand Down Expand Up @@ -341,12 +366,19 @@ const build = (

type EntityClient = ReturnType<Effect.Success<typeof entity.client>>

const sendDecodedThroughClient = (
rpc: EntityClient,
decoded: unknown
): Effect.Effect<void, Rejected | ClientError> =>
// The cast drops the encoding services of the event schemas, as the
// layer drops their decoding services.
(rpc.send(decoded as never) as Effect.Effect<typeof SendResult.Type, ClientError>).pipe(
Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
)

const sendThroughClient = (rpc: EntityClient, event: unknown): Effect.Effect<void, Rejected | ClientError> =>
decodeInputEvent(machine, publicTags, event).pipe(
// The cast drops the encoding services of the event schemas, as the
// layer drops their decoding services.
Effect.flatMap((decoded) => rpc.send(decoded as never) as Effect.Effect<typeof SendResult.Type, ClientError>),
Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result))
Effect.flatMap((decoded) => sendDecodedThroughClient(rpc, decoded))
)

const startThroughClient = (
Expand All @@ -368,8 +400,9 @@ const build = (
definitionId,
version: options.version,
decode: (event) => decodeInputEvent(machine, publicTags, event),
decodeEvent: (event) => decodeInputEventError(machine, publicTags, event),
send: (entityId, event) =>
Effect.flatMap(entity.client, (makeEntityClient) => sendThroughClient(makeEntityClient(entityId), event))
Effect.flatMap(entity.client, (makeEntityClient) => sendDecodedThroughClient(makeEntityClient(entityId), event))
}
const target = (entityId: string): ClusterTarget.Target => new ClusterTarget.Target(protocol, entityId)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ export const make = <R>(options: Options<R>): Effect.Effect<ClusterInstance<R>,
refuseLocal("sendTo") :
Effect.flatMap(runningChild(child), (target) =>
target === undefined ? Effect.void : Effect.flatMap(
Effect.orDie(target.protocol.decode(event)),
target.protocol.decodeEvent(event),
(decoded) => dispatchToChild(target, "deliver", decoded)
)),
stop: (child) =>
Expand Down Expand Up @@ -761,9 +761,7 @@ export const make = <R>(options: Options<R>): Effect.Effect<ClusterInstance<R>,
const parent = options.children?.parent
const last = planned.steps.at(-1)
if (parent === undefined || options.children?.snapshots !== true || last === undefined) return []
// Only microsteps tell whether a step changed anything, so only a parent
// that takes the snapshots reads them.
const moved = base._tag === "Absent" || last.microsteps.length > 0
const moved = base._tag === "Absent" || last.planned
return !moved || last.exit !== undefined
? []
: [{ target: parent, tag: "snapshot", payload: { entityId: address.entityId, snapshot } }]
Expand Down
30 changes: 17 additions & 13 deletions packages/effect-machine/src/internal/machine/clusterTarget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type { Rpc } from "effect/rpc"
import * as Schedule from "effect/Schedule"
import type { Machine, MachineTarget } from "../../Machine.js"
import type { Rejected } from "./clusterProtocol.js"
import { StoppedError } from "./errors.js"
import { type MachineSchemaDecodeError, StoppedError } from "./errors.js"

/** @internal */
export const TypeId = "~effect/cluster/ClusterMachine/Target"
Expand All @@ -40,7 +40,10 @@ export interface Protocol {
/** Decodes an event as the client of the target does before it sends it. */
readonly decode: (event: unknown) => Effect.Effect<unknown, Rejected>

/** Sends through the client of the target, from wherever `Sharding` is. */
/** Decodes an event for a waiting caller, failing with `MachineSchemaDecodeError` when refused. */
readonly decodeEvent: (event: unknown) => Effect.Effect<unknown, MachineSchemaDecodeError>

/** Sends a decoded event through the client of the target, from wherever `Sharding` is. */
readonly send: (entityId: string, event: unknown) => Effect.Effect<void, Rejected | unknown, Sharding.Sharding>
}

Expand All @@ -63,7 +66,7 @@ export class Target implements MachineTarget<any> {
return `${this.entityType}/${this.entityId}`
}

readonly send = (event: unknown): Effect.Effect<void, StoppedError> =>
readonly send = (event: unknown): Effect.Effect<void, StoppedError | MachineSchemaDecodeError> =>
Effect.flatMap(
Effect.serviceOption(Sharding.Sharding),
Option.match({
Expand All @@ -74,16 +77,17 @@ export class Target implements MachineTarget<any> {
)
),
onSome: (sharding) =>
this.protocol.send(this.entityId, event).pipe(
Effect.provideService(Sharding.Sharding, sharding),
// A runner that cannot take the request now takes it later.
Effect.retry({ while: (error) => !isRejected(error), schedule: Schedule.spaced("1 second") }),
Effect.catch((error) =>
isRejected(error) && error.reason === "MachineFailed"
? Effect.fail(new StoppedError())
: Effect.die(error)
)
)
Effect.flatMap(this.protocol.decodeEvent(event), (decoded) =>
this.protocol.send(this.entityId, decoded).pipe(
Effect.provideService(Sharding.Sharding, sharding),
// A runner that cannot take the request now takes it later.
Effect.retry({ while: (error) => !isRejected(error), schedule: Schedule.spaced("1 second") }),
Effect.catch((error) =>
isRejected(error) && error.reason === "MachineFailed"
? Effect.fail(new StoppedError())
: Effect.die(error)
)
))
})
)
}
Expand Down
10 changes: 0 additions & 10 deletions packages/effect-machine/src/internal/machine/commandRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import * as Effect from "effect/Effect"
import type { Machine, MachineSchemaDecodeError, StoppedError } from "../../Machine.js"
import type { RuntimeCommand } from "./command.js"
import { decodeEmit } from "./protocol.js"
import type { ProcessInitialContext } from "./runtimeProtocol.js"

Expand All @@ -22,15 +21,6 @@ export const makeLiveRuntime = <Events>(machine: Machine.Any, scope: ProcessInit
)
})

export const runCommands = <Event>(
commands: Iterable<RuntimeCommand>,
scope: ProcessInitialContext<Event>
) =>
Effect.forEach(commands, (command) =>
command._tag === "SendTo"
? scope.sendTo(command.target as never, command.event)
: scope.stopChild(command.child as never), { discard: true })

export const runEmittedEvents = (
events: Iterable<unknown>,
runtime: LiveRuntime
Expand Down
Loading