From 275578573f42d613a8f1e062712f13d14d625823 Mon Sep 17 00:00:00 2001 From: SandroMaglione Date: Sun, 29 Nov 2026 09:50:48 +1300 Subject: [PATCH 1/2] Align send/sendTo error types and clean up step and host internals --- .changeset/align-send-error-types.md | 23 ++ .changeset/local-rejects-refused-events.md | 2 +- CONTRIBUTING.md | 25 +- packages/effect-machine/src/Machine.ts | 46 ++- .../src/internal/machine/capability.ts | 15 +- .../src/internal/machine/cluster.ts | 45 ++- .../src/internal/machine/clusterInstance.ts | 6 +- .../src/internal/machine/clusterTarget.ts | 30 +- .../src/internal/machine/commandRuntime.ts | 10 - .../src/internal/machine/executionPlan.ts | 50 ++- .../src/internal/machine/machine.ts | 2 +- .../src/internal/machine/process.ts | 47 +-- .../src/internal/machine/runtime.ts | 2 +- .../src/internal/machine/runtimeCompiled.ts | 89 +++-- .../src/internal/machine/runtimeProtocol.ts | 105 ++++-- .../src/internal/machine/step.ts | 144 ++++---- .../src/internal/machine/stepHost.ts | 51 ++- .../src/internal/testing/machine/trace.ts | 13 +- .../test/conformance/HostConformance.test.ts | 12 +- .../test/conformance/matrix.txt | 200 +++++----- .../test/conformance/support/hosts/step.ts | 4 +- .../internal/ObservationDifferential.test.ts | 2 +- .../internal/machine/ScopedLifetime.test.ts | 3 +- .../test/internal/machine/capability.test.ts | 8 +- .../internal/machine/invocationStart.test.ts | 4 +- .../internal/machine/planningFailures.test.ts | 2 +- .../internal/machine/stepDifferential.test.ts | 58 +++ .../machine/strategyDifferential.test.ts | 26 +- .../machine/support/conformanceHosts.ts | 9 +- .../machine/support/strategyDifferential.ts | 8 +- .../test/machine/ChildStoppedByParent.test.ts | 2 +- .../test/machine/InvocationGeneration.test.ts | 4 +- .../test/machine/InvocationTurn.test.ts | 2 +- .../test/machine/SendRejection.test.ts | 344 ++++++++++++++++++ .../support/invocationLifecycleModel.ts | 3 +- .../test/unstable/cluster/Sends.test.ts | 105 ++++++ .../typetest/machine/InvocationSupport.tst.ts | 2 +- .../typetest/machine/LocalMachine.tst.ts | 4 +- scripts/fixtures/consumer/declarations.ts | 3 +- 39 files changed, 1084 insertions(+), 426 deletions(-) create mode 100644 .changeset/align-send-error-types.md create mode 100644 packages/effect-machine/test/machine/SendRejection.test.ts diff --git a/.changeset/align-send-error-types.md b/.changeset/align-send-error-types.md new file mode 100644 index 00000000..98546910 --- /dev/null +++ b/.changeset/align-send-error-types.md @@ -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)) +) +``` diff --git a/.changeset/local-rejects-refused-events.md b/.changeset/local-rejects-refused-events.md index 4385144d..21a0daef 100644 --- a/.changeset/local-rejects-refused-events.md +++ b/.changeset/local-rejects-refused-events.md @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 95d07cd7..6648ed98 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 diff --git a/packages/effect-machine/src/Machine.ts b/packages/effect-machine/src/Machine.ts index 586e6cc3..307d85aa 100644 --- a/packages/effect-machine/src/Machine.ts +++ b/packages/effect-machine/src/Machine.ts @@ -1405,8 +1405,12 @@ export declare namespace Logic { /** Stops the addressed child process. */ readonly stop: Effect.Effect - /** Sends an event to the addressed child process. */ - readonly send: (event: Event) => Effect.Effect + /** + * 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 } /** @@ -1466,12 +1470,16 @@ export declare namespace Logic { readonly spawn: Spawn /** - * 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: { - (target: Endpoint, event: TargetEvent): Effect.Effect + ( + target: Endpoint, + event: TargetEvent + ): Effect.Effect ( target: MachineTarget, event: TargetEvent @@ -1479,7 +1487,7 @@ export declare namespace Logic {
>( id: Address, event: ChildAddress.Event
- ): Effect.Effect + ): Effect.Effect } /** Stops a child process selected by its parent-local address. */ @@ -1693,11 +1701,15 @@ export interface ChildOwner { ChildMachine.StartRequirements > - /** 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: Child, event: ChildMachine.Event - ) => Effect.Effect + ) => Effect.Effect /** Stops one active child. Missing children are ignored. */ readonly stop: (child: Child) => Effect.Effect @@ -8174,11 +8186,15 @@ export declare namespace MachineStep { options: SpawnOptions | undefined ) => StepEffect, 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, event: unknown - ) => Effect.Effect + ) => Effect.Effect /** Stops a child. A child that does not run is ignored. */ readonly stop: (child: ChildMachine.Any | ChildAddress) => Effect.Effect @@ -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 @@ -8652,11 +8670,11 @@ export const sendTo: { ( child: Child, event: ChildMachine.Event - ): Effect.Effect + ): Effect.Effect
>( id: Address, event: ChildAddress.Event
- ): Effect.Effect + ): Effect.Effect } = internal.sendTo as never /** diff --git a/packages/effect-machine/src/internal/machine/capability.ts b/packages/effect-machine/src/internal/machine/capability.ts index 136fa9b2..45045beb 100644 --- a/packages/effect-machine/src/internal/machine/capability.ts +++ b/packages/effect-machine/src/internal/machine/capability.ts @@ -13,6 +13,7 @@ import type { ChildMachine, Logic, MachineRef, + MachineSchemaDecodeError, SpawnOptions, StoppedError } from "../../Machine.js" @@ -62,12 +63,14 @@ export class MachineRuntime extends Context.Service, event: unknown - ) => Effect.Effect + ) => Effect.Effect /** * Stops an active child of the running machine. A missing child is ignored. @@ -107,9 +110,13 @@ export class MachineRuntime extends Context.Service Effect.Effect + readonly sendTo: ( + child: ChildMachine.Any, + event: unknown + ) => Effect.Effect /** Stops the child that runs for a descriptor. A child that does not run is ignored. */ readonly stopChild: (child: ChildMachine.Any) => Effect.Effect diff --git a/packages/effect-machine/src/internal/machine/cluster.ts b/packages/effect-machine/src/internal/machine/cluster.ts index cc6f0b72..4c41472a 100644 --- a/packages/effect-machine/src/internal/machine/cluster.ts +++ b/packages/effect-machine/src/internal/machine/cluster.ts @@ -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" @@ -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" @@ -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, + event: unknown +): Effect.Effect => + 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. @@ -341,12 +366,19 @@ const build = ( type EntityClient = ReturnType> + const sendDecodedThroughClient = ( + rpc: EntityClient, + decoded: unknown + ): Effect.Effect => + // 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).pipe( + Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result)) + ) + const sendThroughClient = (rpc: EntityClient, event: unknown): Effect.Effect => 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), - Effect.flatMap((result) => result._tag === "Accepted" ? Effect.void : Effect.fail(result)) + Effect.flatMap((decoded) => sendDecodedThroughClient(rpc, decoded)) ) const startThroughClient = ( @@ -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) diff --git a/packages/effect-machine/src/internal/machine/clusterInstance.ts b/packages/effect-machine/src/internal/machine/clusterInstance.ts index e39db84c..ad2ed0e9 100644 --- a/packages/effect-machine/src/internal/machine/clusterInstance.ts +++ b/packages/effect-machine/src/internal/machine/clusterInstance.ts @@ -467,7 +467,7 @@ export const make = (options: Options): Effect.Effect, 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) => @@ -761,9 +761,7 @@ export const make = (options: Options): Effect.Effect, 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 } }] diff --git a/packages/effect-machine/src/internal/machine/clusterTarget.ts b/packages/effect-machine/src/internal/machine/clusterTarget.ts index 31932fc7..cca1b942 100644 --- a/packages/effect-machine/src/internal/machine/clusterTarget.ts +++ b/packages/effect-machine/src/internal/machine/clusterTarget.ts @@ -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" @@ -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 - /** 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 + + /** Sends a decoded event through the client of the target, from wherever `Sharding` is. */ readonly send: (entityId: string, event: unknown) => Effect.Effect } @@ -63,7 +66,7 @@ export class Target implements MachineTarget { return `${this.entityType}/${this.entityId}` } - readonly send = (event: unknown): Effect.Effect => + readonly send = (event: unknown): Effect.Effect => Effect.flatMap( Effect.serviceOption(Sharding.Sharding), Option.match({ @@ -74,16 +77,17 @@ export class Target implements MachineTarget { ) ), 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) + ) + )) }) ) } diff --git a/packages/effect-machine/src/internal/machine/commandRuntime.ts b/packages/effect-machine/src/internal/machine/commandRuntime.ts index 39531911..7cf41cbd 100644 --- a/packages/effect-machine/src/internal/machine/commandRuntime.ts +++ b/packages/effect-machine/src/internal/machine/commandRuntime.ts @@ -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" @@ -22,15 +21,6 @@ export const makeLiveRuntime = (machine: Machine.Any, scope: ProcessInit ) }) -export const runCommands = ( - commands: Iterable, - scope: ProcessInitialContext -) => - 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, runtime: LiveRuntime diff --git a/packages/effect-machine/src/internal/machine/executionPlan.ts b/packages/effect-machine/src/internal/machine/executionPlan.ts index e460dfca..d9b58ac6 100644 --- a/packages/effect-machine/src/internal/machine/executionPlan.ts +++ b/packages/effect-machine/src/internal/machine/executionPlan.ts @@ -1454,32 +1454,7 @@ export interface SelectedExecutionPlan { readonly plan: CompiledExecutionPlan } -const selectExecutionPlan = ( - machine: Machine.Any, - strategy: ExecutionPlanStrategy -): SelectedExecutionPlan => { - if (strategy === "generic") { - return { strategy, plan: makeActiveExecutionPlan(machine) } - } - const indexed = compileIndexedExecutionDescriptor(machine) - if (indexed === undefined) { - if (strategy === "auto") { - return { strategy: "generic", plan: makeActiveExecutionPlan(machine) } - } - throw new Error(`Machine cannot compile the requested ${strategy} execution plan`) - } - const selected = indexed.flat ? "indexed-flat" : "indexed-hierarchical" - if (strategy !== "auto" && strategy !== selected) { - throw new Error(`Machine compiled ${selected}, not the requested ${strategy} execution plan`) - } - return { strategy: selected, plan: makeIndexedExecutionPlan(machine, indexed) } -} - -/** @internal Test-only uncached strategy selection. */ -export const selectExecutionPlanForTesting = ( - machine: Machine.Any, - strategy: ExecutionPlanStrategy -): SelectedExecutionPlan => selectExecutionPlan(machine, strategy) +const executionPlanStrategyCache = new WeakMap>() /** * The reference execution plan of `machine`, which always plans on the generic @@ -1494,6 +1469,7 @@ export const referenceExecutionPlan = (machine: Machine.Any): CompiledExecutionP } const reference = makeActiveExecutionPlan(machine) referenceExecutionPlanCache.set(machine, reference) + executionPlanStrategyCache.set(reference, "generic") return reference } @@ -1506,6 +1482,28 @@ export const compileExecutionPlan = (machine: Machine.Any): CompiledExecutionPla const compiled = indexed === undefined ? referenceExecutionPlan(machine) : makeIndexedExecutionPlan(machine, indexed) + if (indexed !== undefined) { + executionPlanStrategyCache.set(compiled, indexed.flat ? "indexed-flat" : "indexed-hierarchical") + } executionPlanCache.set(machine, compiled) return compiled } + +/** @internal Test-only planner selection, delegating to the cached reference and compiled plans. */ +export const selectExecutionPlanForTesting = ( + machine: Machine.Any, + strategy: ExecutionPlanStrategy +): SelectedExecutionPlan => { + if (strategy === "generic") { + return { strategy, plan: referenceExecutionPlan(machine) } + } + const plan = compileExecutionPlan(machine) + const selected = executionPlanStrategyCache.get(plan) ?? "generic" + if (strategy !== "auto" && strategy !== selected) { + if (selected === "generic") { + throw new Error(`Machine cannot compile the requested ${strategy} execution plan`) + } + throw new Error(`Machine compiled ${selected}, not the requested ${strategy} execution plan`) + } + return { strategy: selected, plan } +} diff --git a/packages/effect-machine/src/internal/machine/machine.ts b/packages/effect-machine/src/internal/machine/machine.ts index bd7a70f9..94ed647f 100644 --- a/packages/effect-machine/src/internal/machine/machine.ts +++ b/packages/effect-machine/src/internal/machine/machine.ts @@ -1104,7 +1104,7 @@ export const spawn = (logic: Logic, options?: Spaw export const sendTo = ( child: ChildAddress | ChildMachine.Any, event: unknown -): Effect.Effect => +): Effect.Effect => Child.isChildMachine(child) ? Effect.flatMap(ChildMachineRuntime, (runtime) => runtime.sendTo(child, event)) : Effect.flatMap(MachineRuntime, (runtime) => runtime.sendTo(child, event)) diff --git a/packages/effect-machine/src/internal/machine/process.ts b/packages/effect-machine/src/internal/machine/process.ts index 73b6218a..6cd5f2e0 100644 --- a/packages/effect-machine/src/internal/machine/process.ts +++ b/packages/effect-machine/src/internal/machine/process.ts @@ -100,67 +100,68 @@ const toChildProcessLogic: internalRuntimeProtocol.MakeChildLogic = (machine, in const runtime = ProcessRuntime.make(toChildProcessLogic) -// The reference strategy runs a machine on the same driver as every other, -// with a step that always plans with the reference planner. +/** + * Which execution plan a local machine test runs with, on the one local + * process driver: `"reference"` forces the reference planner, and `"indexed"` + * uses the default compiled plan (indexed kernel when supported, otherwise + * reference). + * + * @internal + */ +export type LocalPlannerStrategy = "reference" | "indexed" + const strategyLogic = ( machine: Machine.Any, - strategy: ProcessRuntime.ProcessRuntimeStrategy, + strategy: LocalPlannerStrategy, entry: StepHost.Entry ): internalRuntimeProtocol.ProcessLogic => - strategy === "generic" + strategy === "reference" ? makeProcessLogic(machine, entry, ExecutionPlan.referenceExecutionPlan(machine)) : entry._tag === "Initial" ? toProcessLogic(machine, ...entry.args) : toResumedProcessLogic(machine, entry.snapshot) -const runtimeStrategy = (strategy: ProcessRuntime.ProcessRuntimeStrategy): ProcessRuntime.ProcessRuntimeStrategy => - strategy === "generic" ? "compiled" : strategy - -/** @internal Test-only runtime strategy selection for a fresh machine. */ +/** @internal Test-only planner selection for a fresh local machine. */ export const startWithRuntimeStrategyForTesting = ( machine: Machine.Any, - strategy: ProcessRuntime.ProcessRuntimeStrategy, + strategy: LocalPlannerStrategy, ...args: ReadonlyArray ): Effect.Effect, any, any> => - runtime.startProcessWithStrategyForTesting( + runtime.startProcess( strategyLogic(machine, strategy, { _tag: "Initial", args }), - runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) -/** @internal Test-only prepared startup strategy selection for a fresh machine. */ +/** @internal Test-only prepared startup planner selection for a fresh local machine. */ export const prepareWithRuntimeStrategyForTesting = ( machine: Machine.Any, - strategy: ProcessRuntime.ProcessRuntimeStrategy, + strategy: LocalPlannerStrategy, ...args: ReadonlyArray ): Effect.Effect, any, any> => - runtime.prepareProcessWithStrategyForTesting( + runtime.prepareProcess( strategyLogic(machine, strategy, { _tag: "Initial", args }), - runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) -/** @internal Test-only runtime strategy selection for a resumed machine. */ +/** @internal Test-only planner selection for a resumed local machine. */ export const resumeWithRuntimeStrategyForTesting = ( machine: Machine.Any, snapshot: Machine.Snapshot, - strategy: ProcessRuntime.ProcessRuntimeStrategy + strategy: LocalPlannerStrategy ): Effect.Effect, any, any> => - runtime.startProcessWithStrategyForTesting( + runtime.startProcess( strategyLogic(machine, strategy, { _tag: "Resume", snapshot }), - runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) -/** @internal Test-only runtime strategy selection for a prepared resumed machine. */ +/** @internal Test-only planner selection for a prepared resumed local machine. */ export const prepareResumedWithRuntimeStrategyForTesting = ( machine: Machine.Any, snapshot: Machine.Snapshot, - strategy: ProcessRuntime.ProcessRuntimeStrategy + strategy: LocalPlannerStrategy ): Effect.Effect, any, any> => - runtime.prepareProcessWithStrategyForTesting( + runtime.prepareProcess( strategyLogic(machine, strategy, { _tag: "Resume", snapshot }), - runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) diff --git a/packages/effect-machine/src/internal/machine/runtime.ts b/packages/effect-machine/src/internal/machine/runtime.ts index 37b2835e..51fcbda0 100644 --- a/packages/effect-machine/src/internal/machine/runtime.ts +++ b/packages/effect-machine/src/internal/machine/runtime.ts @@ -1,4 +1,4 @@ -/** Local process startup and execution strategy selection. */ +/** Local process startup, scope ownership, and prepared process lifecycle. */ import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 46e8ca20..0db06fc4 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -35,7 +35,9 @@ import { type CompiledProcessInitial, decodeDelivered, decodeSent, + type Deliverable, deliverEvent, + deliverMachineTarget, type EmissionRuntime, EmissionsClosed, type EventDecoder, @@ -52,7 +54,6 @@ import { messageCausation, messageEvent, noInspectInitial, - noParentSend, notifyActiveSnapshot, offerCompactMailbox, offerProcessMailbox, @@ -69,7 +70,6 @@ import { receiveProcessMailbox, RefusedEvent, type RuntimeSnapshot, - sendEndpoint, sendMachineTarget, sentOf, snapshotObserver, @@ -91,12 +91,14 @@ type CompiledLifecycle = "Active" | "TerminationRequested" | "Completed" type CompiledRunState = "Initializing" | "Idle" | "Draining" /** - * The endpoint of a compiled process: what its work, its children and its - * parent send to. It delivers, so a refused event fails the machine when it is - * planned. Prototype getters and methods keep an endpoint to one reference - * slot with no eager `stop` Effect or closure. + * The endpoint of a local process: what its work, its children, and its parent + * see as `self` or `parent`. Caller-awaited `send` and `sendInspected` reject + * events refused by the machine's schema and keep the machine running, while + * `[deliverEvent]` delivers transition commands and internal work reports. + * Prototype getters and methods keep an endpoint to one reference slot with no + * eager `stop` Effect or closure. */ -class CompiledAddress implements ProcessEndpoint { +class CompiledAddress implements ProcessEndpoint, Deliverable { constructor(private readonly process: LocalProcess) {} get id(): string { return this.process.id @@ -110,13 +112,20 @@ class CompiledAddress implements ProcessEndpoint { get stop(): Effect.Effect { return Effect.suspend(() => this.process.stopFromProcess()) } - send(event: unknown): Effect.Effect { - return this.process.deliver(event, undefined, undefined) + send(event: unknown): Effect.Effect { + return this.process.send(event) } sendInspected( event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined + ): Effect.Effect { + return this.process.sendPublic(event, source, causedBy) + } + [deliverEvent]( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined ): Effect.Effect { return this.process.deliver(event, source, causedBy) } @@ -139,8 +148,8 @@ abstract class LocalProcess implements MachineRef { event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined - ): Effect.Effect { - return this.deliver(event, source, causedBy) + ): Effect.Effect { + return this.sendPublic(event, source, causedBy) } [deliverEvent]( event: unknown, @@ -209,7 +218,7 @@ abstract class LocalProcess implements MachineRef { this.externalEmissions = options.emissions this.send = inspector === undefined ? (event) => this.offerMessage(event, "Sent") - : (event) => this.sendPublic(event) + : (event) => this.sendPublic(event, undefined, undefined) this.address = new CompiledAddress(this) } @@ -321,18 +330,12 @@ abstract class LocalProcess implements MachineRef { const childless = this.childless if (!childless) this.childRuntime = this.makeChildRuntime() const parent = this.options.parent - const sendParent = this.options.sendParent ?? (parent === undefined - ? noParentSend - : this.inspector === undefined - ? (event: unknown) => parent.send(event) - : (event: unknown) => sendEndpoint(parent, event, this.inspectionSubject, this.causation())) this.processScope = { self: this.address, parent, spawn: this.childRuntime.spawn, - sendParent, emit: (event) => this.emitEvent(event), - sendTo: ((target: unknown, event: unknown) => + sendTo: (target: unknown, event: unknown) => isMachineTarget(target) ? this.inspector === undefined ? sendMachineTarget(target, event, undefined, undefined) @@ -342,7 +345,18 @@ abstract class LocalProcess implements MachineRef { event, this.inspectionSubject, this.causation() - )) as ProcessInitialContext["sendTo"], + ), + deliverTo: (target, event) => + isMachineTarget(target) + ? this.inspector === undefined + ? deliverMachineTarget(target, event, undefined, undefined) + : deliverMachineTarget(target, event, this.inspectionSubject, this.causation()) + : this.childRuntime.deliverTo( + target, + event, + this.inspectionSubject, + this.causation() + ), stopChild: this.childRuntime.stop, failCause: (cause: Cause.Cause) => this.failCause(cause), inspectInitial: this.inspector === undefined @@ -393,18 +407,12 @@ abstract class LocalProcess implements MachineRef { self.publishCreated() if (!self.childless) self.childRuntime = self.makeChildRuntime() const parent = self.options.parent - const sendParent = self.options.sendParent ?? (parent === undefined - ? noParentSend - : self.inspector === undefined - ? (event: unknown) => parent.send(event) - : (event: unknown) => sendEndpoint(parent, event, self.inspectionSubject, self.causation())) self.processScope = { self: self.address, parent, spawn: self.childRuntime.spawn, - sendParent, emit: (event) => self.emitEvent(event), - sendTo: ((target: unknown, event: unknown) => + sendTo: (target: unknown, event: unknown) => isMachineTarget(target) ? self.inspector === undefined ? sendMachineTarget(target, event, undefined, undefined) @@ -414,7 +422,18 @@ abstract class LocalProcess implements MachineRef { event, self.inspectionSubject, self.causation() - )) as ProcessInitialContext["sendTo"], + ), + deliverTo: (target, event) => + isMachineTarget(target) + ? self.inspector === undefined + ? deliverMachineTarget(target, event, undefined, undefined) + : deliverMachineTarget(target, event, self.inspectionSubject, self.causation()) + : self.childRuntime.deliverTo( + target, + event, + self.inspectionSubject, + self.causation() + ), stopChild: self.childRuntime.stop, failCause: (cause: Cause.Cause) => self.failCause(cause), inspectInitial: self.inspector === undefined @@ -578,21 +597,25 @@ abstract class LocalProcess implements MachineRef { } /** - * A public `send`: an event that the schema refuses is rejected, and the - * machine keeps running. A machine that has ended rejects first. + * A caller-awaited `send`: an event that the schema refuses is rejected, and + * the machine keeps running. A machine that has ended rejects first. */ - private sendPublic(event: unknown): Effect.Effect { + sendPublic( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { if (this.inspector === undefined) return this.offerMessage(event, "Sent") return Effect.suspend((): Effect.Effect => { if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) const decoded = decodeSent(this.decodeEvent, event) return decoded._tag === "Rejected" ? Effect.fail(decoded.error) - : this.offerEvent(decoded.event, undefined, undefined, undefined, event) + : this.offerEvent(decoded.event, source, causedBy, undefined, event) }) } - /** A delivery from work, a child, a parent or a command of another machine. */ + /** A transition-command or internal-work delivery. */ deliver( event: unknown, source: Inspection.Subject | undefined, diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index c7e40dea..f2be62b6 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -64,10 +64,10 @@ export const isSnapshotObservable = (value: unknown): value is SnapshotObservabl typeof value === "object" && value !== null && snapshotObserver in value /** - * Delivery between the machines of one runtime. A public `send` rejects an - * event that the schema of the machine refuses; a delivery takes it, and the - * machine fails with that error when the event is planned, as a public event - * that a command, a parent or a child sends always has. + * Delivery for transition commands and internal work reports inside one + * runtime. A caller-awaited `send` or `sendTo` rejects an event that the + * schema of the machine refuses; a delivery has no waiting caller, so the + * receiving machine fails with that error when the event is planned. * * @internal */ @@ -287,12 +287,13 @@ export interface ProcessEndpoint { readonly sessionId: string readonly inspectionSubject?: Inspection.Subject | undefined readonly stop: Effect.Effect - readonly send: (event: Event) => Effect.Effect + readonly send: (event: Event) => Effect.Effect readonly sendInspected?: ( event: Event, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined - ) => Effect.Effect + ) => Effect.Effect + readonly [deliverEvent]?: Deliverable[typeof deliverEvent] readonly [acknowledgedSend]?: | ((event: Event) => Effect.Effect, unknown | StoppedError>) | undefined @@ -301,30 +302,52 @@ export interface ProcessEndpoint { export const isMachineTarget = (value: unknown): value is MachineTarget => typeof value === "object" && value !== null && "send" in value && typeof value.send === "function" +/** Sends to a target for a waiting caller: a refused event is rejected and the target keeps running. */ export const sendMachineTarget = ( target: MachineTarget, event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined ): Effect.Effect => - deliverEvent in target - ? (target as unknown as Deliverable)[deliverEvent](event, source, causedBy) - : "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function" + "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function" ? target.sendInspected(event, source, causedBy) : target.send(event) -/** Sends to an endpoint of this runtime, which delivers. */ +/** Delivers a transition command to a target without caller-side schema rejection. */ +export const deliverMachineTarget = ( + target: MachineTarget, + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined +): Effect.Effect => + deliverEvent in target + ? (target as unknown as Deliverable)[deliverEvent](event, source, causedBy) + : sendMachineTarget(target, event, source, causedBy) + +/** Sends to an endpoint for a waiting caller. */ export const sendEndpoint = ( endpoint: ProcessEndpoint, event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined -): Effect.Effect => +): Effect.Effect => endpoint.sendInspected === undefined ? endpoint.send(event) : endpoint.sendInspected(event, source, causedBy) +/** Delivers an internal message or transition command to an endpoint of this runtime. */ +export const deliverToEndpoint = ( + endpoint: ProcessEndpoint, + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined +): Effect.Effect => + endpoint[deliverEvent] !== undefined + ? endpoint[deliverEvent](event, source, causedBy) + : sendEndpoint(endpoint, event, source, causedBy) as Effect.Effect + /** - * Delivers to a child, which this runtime started: a machine takes the - * delivery, and other logic decodes nothing, so its `send` rejects nothing. + * Delivers a transition command to a child started by this runtime: a machine + * takes the delivery and fails when planning a refused event, and other logic + * decodes nothing. */ const deliverToChild = ( ref: MachineRef, @@ -340,16 +363,23 @@ export interface ProcessInitialContext { readonly self: ProcessEndpoint readonly parent: ProcessEndpoint | undefined readonly spawn: ProcessSpawn - readonly sendParent: (event: unknown) => Effect.Effect readonly emit: (event: unknown) => Effect.Effect readonly sendTo: { - (target: ProcessEndpoint, event: TargetEvent): Effect.Effect + ( + target: ProcessEndpoint, + event: TargetEvent + ): Effect.Effect ( target: MachineTarget, event: TargetEvent ): Effect.Effect - (child: ChildSelector, event: unknown): Effect.Effect + (child: ChildSelector, event: unknown): Effect.Effect } + /** Delivers a transition command to a target or child without caller-side schema rejection. */ + readonly deliverTo: ( + target: MachineTarget | ChildSelector, + event: unknown + ) => Effect.Effect readonly stopChild: (child: ChildSelector) => Effect.Effect /** @internal */ readonly failCause: (cause: Cause.Cause) => Effect.Effect @@ -826,7 +856,6 @@ export interface StartInternalOptions { readonly skipStoppedOutcome?: boolean readonly parent?: ProcessEndpoint readonly runtime: ProcessRuntime - readonly sendParent?: (event: unknown) => Effect.Effect readonly origin?: Inspection.Origin readonly programInvocation?: { readonly id: string @@ -892,6 +921,12 @@ export interface ChildRuntime { event: unknown, source?: Inspection.Subject, causedBy?: Inspection.Causation + ) => Effect.Effect + readonly deliverTo: ( + child: ChildSelector, + event: unknown, + source?: Inspection.Subject, + causedBy?: Inspection.Causation ) => Effect.Effect readonly stop: (child: ChildSelector) => Effect.Effect readonly owned: OwnedChildRuntime @@ -901,7 +936,7 @@ export interface ChildRuntime { * Parent endpoint exposed to an owned invocation. Prototype getters and methods * keep each running child free of per-child parent endpoint closures. */ -class OwnedChildParent implements ProcessEndpoint { +class OwnedChildParent implements ProcessEndpoint, Deliverable { startedChild: MachineRef | undefined = undefined constructor( @@ -936,7 +971,7 @@ class OwnedChildParent implements ProcessEndpoint { unregisterChild(this.owner.registry, this.childId, this.token) } - send(event: unknown): Effect.Effect { + send(event: unknown): Effect.Effect { return this.isCurrent() ? this.owner.self.send(event) : Effect.void } @@ -944,10 +979,18 @@ class OwnedChildParent implements ProcessEndpoint { event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined - ): Effect.Effect { + ): Effect.Effect { return this.isCurrent() ? sendEndpoint(this.owner.self, event, source, causedBy) : Effect.void } + [deliverEvent]( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { + return this.isCurrent() ? deliverToEndpoint(this.owner.self, event, source, causedBy) : Effect.void + } + get [acknowledgedSend](): | ((event: unknown) => Effect.Effect, unknown | StoppedError>) | undefined @@ -1013,7 +1056,6 @@ class OwnedChildRuntimeImpl implements OwnedChildRuntime { const startOptions: { -readonly [K in keyof StartInternalOptions]: StartInternalOptions[K] } = { detached: true, id, - sendParent: (event) => parent.send(event), onOutcome: (outcome) => onOutcome(isCurrent, outcome, parent.startedChild?.sessionId), ...(onSnapshot === undefined ? undefined @@ -1077,7 +1119,6 @@ class OwnedChildRuntimeImpl implements OwnedChildRuntime { } const noChildChanges = Stream.succeed(Option.none()).pipe(Stream.concat(Stream.never)) -export const noParentSend = (_event: unknown): Effect.Effect => Effect.void export const noInspectInitial = (_paths: ReadonlyArray, _microsteps?: ReadonlyArray): void => {} export const noCausation = (): Inspection.Causation | undefined => undefined export const EmissionsClosed: unique symbol = Symbol("effect/Machine/EmissionsClosed") @@ -1138,6 +1179,7 @@ export const childlessRuntime: ChildRuntime = { get: () => Effect.succeed(Option.none()), changes: () => noChildChanges, sendTo: () => Effect.void, + deliverTo: () => Effect.void, stop: () => Effect.void, owned: { spawn: () => Effect.die(new Error("Childless machine logic cannot spawn an owned process")), @@ -1267,6 +1309,24 @@ export const makeChildRuntimeSync = ( event: unknown, source?: Inspection.Subject, causedBy?: Inspection.Causation + ): Effect.Effect => { + const id = typeof child === "string" ? child : child.id + return Effect.suspend(() => { + if (registry.closed) { + return Effect.void + } + const entry = registry.children.get(id) + return entry !== undefined && matchesChild(entry, child) + ? sendMachineTarget(entry.ref, event, source, causedBy) + : Effect.void + }) + } + + const deliverTo = ( + child: ChildSelector, + event: unknown, + source?: Inspection.Subject, + causedBy?: Inspection.Causation ): Effect.Effect => { const id = typeof child === "string" ? child : child.id return Effect.suspend(() => { @@ -1404,6 +1464,7 @@ export const makeChildRuntimeSync = ( get, changes, sendTo, + deliverTo, stop, owned: new OwnedChildRuntimeImpl(registry, self, runtime, services, sendAcknowledged) } diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index c59a006f..d322cd65 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -1,6 +1,6 @@ /** * The pure form of a machine: what its next state is, and which work a host - * starts and stops, for hosts written outside the local runtime. + * starts and stops, shared by every host that runs a machine. * * Every function is synchronous and returns a value. The host state holds the * execution state of the plan, the work that runs, and how many entries of @@ -165,7 +165,10 @@ export interface Children { logic: AnyLogic, options: { readonly id?: string | undefined } | undefined ) => Effect.Effect - readonly sendTo: (child: ChildSelector, event: unknown) => Effect.Effect + readonly sendTo: ( + child: ChildSelector, + event: unknown + ) => Effect.Effect readonly stop: (child: ChildSelector) => Effect.Effect } @@ -255,8 +258,8 @@ export class Planning extends PlanningBase { plan: ExecutionPlan.CompiledExecutionPlan, readonly self: MachineTarget, readonly parent: MachineTarget | undefined, - /** The children of the machine, or `undefined` for a host that owns them itself. */ - children: Children | undefined, + /** The children of the machine, or `undefined` when the host supplies none. */ + children: Children = refusedChildren, /** * Whether the host runs work inside the services of this machine already, * as the local runtime runs work in processes of the machine, so work is @@ -265,7 +268,7 @@ export class Planning extends PlanningBase { readonly ambient = false ) { super(machine, plan) - this.children = children ?? (this as unknown as Children) + this.children = children } /** The services through which work acts on the children of this machine. */ @@ -628,6 +631,20 @@ export interface Kernel input: ReadonlyArray, retain?: boolean ) => Exit.Exit, unknown> + /** + * Starts a childless machine directly from `plan.initial`, returning its + * initial snapshot and completion without allocating a `Step` or `State`. + * Throws the same startup failure that `start` fails with. Present only when + * the machine invokes no work and `plan.initial` covers it. + */ + readonly startSnapshot: + | (( + references: Configuration.PlanningMachineReferences, + input: ReadonlyArray + ) => + | { readonly state: Machine.Snapshot; readonly done: false; readonly output: undefined } + | { readonly state: Machine.Snapshot; readonly done: true; readonly output: unknown }) + | undefined readonly resume: ( planning: PlanningBase, snapshot: Machine.Snapshot, @@ -1063,6 +1080,29 @@ const build = ( ) } + /** Builds the step of a childless machine for a planned macrostep. */ + const childlessStep = ( + state: State, + planned: ExecutionPlan.ExecutionMacrostep, + commands: ReadonlyArray + ): Step => + planned.done + ? ended( + reached(state.planning, planned.next, undefined, undefined, state.runs), + empty, + Exit.succeed(planned.output), + { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } + ) + : new Step( + new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), + planned.event, + planned.microsteps, + planned.emittedEvents, + commands, + empty, + empty + ) + /** * Plans one event on a state that runs `running`: a public event that `send` * decoded, or the invocation event of a result. @@ -1095,24 +1135,7 @@ const build = ( } const commanded = planned.commands.length === 0 ? undefined : commandsOf(planned.commands, running) const commands = commanded === undefined ? empty : commanded.commands - if (invoking.size === 0) { - return planned.done - ? ended( - reached(state.planning, planned.next, undefined, undefined, state.runs), - empty, - Exit.succeed(planned.output), - { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } - ) - : new Step( - new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), - planned.event, - planned.microsteps, - planned.emittedEvents, - commands, - empty, - empty - ) - } + if (invoking.size === 0) return childlessStep(state, planned, commands) const changes = InvocationChanges.fromMicrosteps(planned.microsteps) const published: Published = { event: planned.event, @@ -1217,6 +1240,20 @@ const build = ( ) } + const startSnapshot: Kernel["startSnapshot"] = invoking.size === 0 && plan.initial !== undefined + ? (references, input) => { + let planned: ReturnType> + try { + planned = plan.initial!(input, references) + } catch (error) { + throw toStartupFailure(error) + } + return planned.done + ? { state: planned.state, done: true, output: planned.output } + : { state: planned.state, done: false, output: undefined } + } + : undefined + const fromSnapshot: Kernel["fromSnapshot"] = (planning, snapshot) => { if (invoking.size > 0) throw new Error("A machine that invokes work runs its work in its state") return new State(planning, undefined, undefined, snapshot, empty, 0, undefined) @@ -1261,22 +1298,7 @@ const build = ( } state.handOverNeverReuse() const commands = planned.commands.length === 0 ? empty : commandsOf(planned.commands, empty).commands - return planned.done - ? ended( - reached(state.planning, planned.next, undefined, undefined, state.runs), - empty, - Exit.succeed(planned.output), - { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } - ) - : new Step( - new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), - planned.event, - planned.microsteps, - planned.emittedEvents, - commands, - empty, - empty - ) + return childlessStep(state, planned, commands) } const move = ( @@ -1284,46 +1306,8 @@ const build = ( event: Machine.EventOf ): Machine.Snapshot | Step | undefined => { if (state.exit !== undefined) return undefined - if (invoking.size > 0) { - const step = advance(state, state.running, event, false) - return step.state === state && !step.planned && step.exit === undefined ? undefined : step - } - let planned: ExecutionPlan.ExecutionMacrostep - try { - planned = plan.planDecoded(state.execution, event, ownership, false, state.planning) - } catch (error) { - return ended(endedFrom(state), empty, exitOfThrow(error), { ...nothing, event }) - } - if (planned.microsteps.length === 0) return undefined - if (!planned.done && planned.commands.length === 0 && planned.emittedEvents.length === 0) { - const snapshot = plan.snapshot(planned.next) - return new Step( - new State(state.planning, planned.next, undefined, snapshot, empty, state.runs, undefined), - planned.event, - planned.microsteps, - empty, - empty, - empty, - empty - ) - } - const commands = planned.commands.length === 0 ? empty : commandsOf(planned.commands, empty).commands - return planned.done - ? ended( - reached(state.planning, planned.next, undefined, undefined, state.runs), - empty, - Exit.succeed(planned.output), - { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } - ) - : new Step( - new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), - planned.event, - planned.microsteps, - planned.emittedEvents, - commands, - empty, - empty - ) + const step = advance(state, state.running, event, false) + return step.state === state && !step.planned && step.exit === undefined ? undefined : step } const settle = (state: State, work: Work, exit: Exit.Exit, retain = true): Step => { @@ -1392,6 +1376,7 @@ const build = ( return { plan, start, + startSnapshot, fromSnapshot, rest: (state) => state.resting(), send, @@ -1413,6 +1398,7 @@ const build = ( return { plan, start, + startSnapshot, fromSnapshot, rest: (state) => state.restInPlace(), send: (state, event) => { diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index d9eef206..7cd2bf4d 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -21,7 +21,7 @@ import type { Inspection } from "../../LocalMachine.js" import type { ChildMachine, Machine } from "../../Machine.js" import * as ChildRegistry from "./childRegistry.js" import * as CommandRuntime from "./commandRuntime.js" -import { ChildAlreadyExistsError, failPlanning, toStartupFailure } from "./errors.js" +import { ChildAlreadyExistsError, failPlanning } from "./errors.js" import type * as ExecutionPlan from "./executionPlan.js" import type * as InvocationResolution from "./invocationResolution.js" import * as Runtime from "./runtimeProtocol.js" @@ -101,9 +101,9 @@ const runCommands = (commands: ReadonlyArray, scope: Scope): Effec Effect.forEach(commands, (command) => { switch (command._tag) { case "Send": - return scope.sendTo(command.target, command.event) + return scope.deliverTo(command.target, command.event) case "SendToChild": - return scope.sendTo(command.child, command.event) + return scope.deliverTo(command.child, command.event) case "StopChild": return scope.stopChild(command.child) } @@ -238,13 +238,14 @@ const report = ( message: Runtime.WorkMessage, invocationSessionId: string | undefined ): Effect.Effect => - (invocationSessionId === undefined || scope.self.sendInspected === undefined - ? scope.self.send(message) - : scope.self.sendInspected( - message, - scope.self.inspectionSubject, - { _tag: "ProgramInvocation", invocationSessionId } satisfies Inspection.Causation - )).pipe(Effect.catchTag("StoppedError", () => Effect.void)) + Runtime.deliverToEndpoint( + scope.self, + message, + invocationSessionId === undefined ? undefined : scope.self.inspectionSubject, + invocationSessionId === undefined + ? undefined + : ({ _tag: "ProgramInvocation", invocationSessionId } satisfies Inspection.Causation) + ).pipe(Effect.catchTag("StoppedError", () => Effect.void)) /** Starts one piece of work that a step listed, as an owned process of the machine. */ const startWork = (context: Context, kernel: Kernel, work: Step.Work): Effect.Effect => { @@ -394,7 +395,6 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => ): Drain => { const scope = context.scope const exit = step.exit - const done = exit !== undefined // Work that ended in a state the step exits is awaited with `step.stop`, so // its process has stopped before the state is entered again. Remaining work // of non-exited states on a final step is in `step.stopAfter`. @@ -425,7 +425,7 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => const continueAfterCommit = (): Drain => { const continued = Effect.suspend((): Drain => { if (acknowledged) context.completeMessage({ before, plan: planOf(step), after }) - return done ? Effect.succeed(Option.some((exit as Exit.Success).value)) : loop(context) + return exit !== undefined && Exit.isSuccess(exit) ? Effect.succeed(Option.some(exit.value)) : loop(context) }) return afterCommit.length === 0 ? continued : runSequentialDiscard(afterCommit).pipe(Effect.andThen(continued)) } @@ -543,14 +543,13 @@ const initialOf = ( host: Host | undefined ): Runtime.CompiledProcessInitial, unknown> => { const exit = step.exit - const done = exit !== undefined && Exit.isSuccess(exit) - if (host === undefined) { - return done - ? { state: step.snapshot, done: true, output: (exit as Exit.Success).value } - : { state: step.snapshot, done: false, output: undefined } + if (exit !== undefined && Exit.isSuccess(exit)) { + return host === undefined + ? { state: step.snapshot, done: true, output: exit.value } + : { state: step.snapshot, done: true, output: exit.value, executionState: host } } - return done - ? { state: step.snapshot, done: true, output: (exit as Exit.Success).value, executionState: host } + return host === undefined + ? { state: step.snapshot, done: false, output: undefined } : { state: step.snapshot, done: false, output: undefined, executionState: host } } @@ -587,16 +586,8 @@ export const makeExecution = ( // when it starts, so it starts without an Effect. const initialSync = entry._tag === "Initial" && kernel.plan.initial !== undefined ? (scope: Scope): Runtime.CompiledProcessInitial, unknown> => { - if (childless && !isInspected(scope)) { - let planned: ReturnType> - try { - planned = kernel.plan.initial!(entry.args, scope) - } catch (error) { - throw toStartupFailure(error) - } - return planned.done - ? { state: planned.state, done: true, output: planned.output } - : { state: planned.state, done: false, output: undefined } + if (kernel.startSnapshot !== undefined && !isInspected(scope)) { + return kernel.startSnapshot(scope, entry.args) } const started = first(scope) if (Exit.isFailure(started)) throw Cause.squash(started.cause) @@ -604,7 +595,7 @@ export const makeExecution = ( if (step.commands.length > 0 || step.emitted.length > 0) { throw new Error("Machine started by its execution plan planned startup commands or emissions") } - if (entry._tag === "Initial" && isInspected(scope)) scope.inspectInitial(step.entered, step.microsteps) + if (isInspected(scope)) scope.inspectInitial(step.entered, step.microsteps) return initialOf(step, host(step)) } : undefined diff --git a/packages/effect-machine/src/internal/testing/machine/trace.ts b/packages/effect-machine/src/internal/testing/machine/trace.ts index 8362ea99..92f7c5b0 100644 --- a/packages/effect-machine/src/internal/testing/machine/trace.ts +++ b/packages/effect-machine/src/internal/testing/machine/trace.ts @@ -167,8 +167,11 @@ export const planEntry = ( const step = stepOf(machine) const state = stateOf(trace) if (state.exit !== undefined) { - // A completed machine takes no further step. Planning an entry after it - // reports the completion again, as `Machine.plan` does for a final state. + // A completed machine takes no further step, and `MachineStep.send` rejects + // events after completion with `StoppedError`. `MachineTest` preserves + // `Machine.plan`'s idempotent final-state contract (validating schemas with + // `RunServices` and returning `{ done: true, output, next: trace.final }`), + // so post-completion entries delegate to `Machine.plan`. return Effect.map( (Machine.plan as any)( machine, @@ -315,6 +318,12 @@ export const run: ( machine: ReadyMachine, scenario: Scenario ) { + // Startup uses `Machine.planInitial` instead of `step.start` because + // `InitialTrace` exposes `startingState` (the pre-settling snapshot, which + // `MachineStep.Step` does not retain), `Machine.planInitial` supports + // effectful schema services (`RunServices`) whereas `step.start` is + // synchronous, and `MachineTest.run` reports raw `RunError` rather than + // `step.start`'s `StartupError` wrapper. const initialEffect = (machine.input === undefined || machine.input === Schema.Void ? (Machine.planInitial as any)(machine) : (Machine.planInitial as any)(machine, (scenario as { readonly input: InputValue }).input)) as Effect.Effect< diff --git a/packages/effect-machine/test/conformance/HostConformance.test.ts b/packages/effect-machine/test/conformance/HostConformance.test.ts index 74116bc8..8f76111a 100644 --- a/packages/effect-machine/test/conformance/HostConformance.test.ts +++ b/packages/effect-machine/test/conformance/HostConformance.test.ts @@ -1,6 +1,6 @@ import { assert, describe, expect, it } from "@effect/vitest" import { Effect } from "effect" -import { compiledHost, genericHost } from "../internal/machine/support/conformanceHosts.js" +import { indexedPlannerHost, referencePlannerHost } from "../internal/machine/support/conformanceHosts.js" import { differences } from "./differences.js" import { children } from "./scenarios/children.js" import { invocations } from "./scenarios/invocations.js" @@ -13,7 +13,7 @@ import { clusterHost } from "./support/hosts/cluster.js" import { stepHost } from "./support/hosts/step.js" import { cellOf, check, checkEntry, renderMatrix } from "./support/suite.js" -const hosts = [genericHost, compiledHost, atomHost, clusterHost, stepHost] +const hosts = [referencePlannerHost, indexedPlannerHost, atomHost, clusterHost, stepHost] const scenarios = [...transitions, ...invocations, ...timers, ...restarts, ...children] describe("conformance of hosts", () => { @@ -37,7 +37,7 @@ describe("conformance of hosts", () => { for (const difference of differences) { it(`registers what exists for ${difference.hosts.join(", ")}: ${difference.scenario}`, () => - checkEntry(difference, hosts, scenarios, genericHost)) + checkEntry(difference, hosts, scenarios, referencePlannerHost)) } it.effect("refuses an entry for a host that does not differ, and an entry that says something else", () => @@ -45,16 +45,16 @@ describe("conformance of hosts", () => { const scenario = transitions.find(({ name }) => name === "moves between states and carries their data")! const entry: Difference = { kind: "Open", - hosts: [genericHost.name], + hosts: [referencePlannerHost.name], scenario: scenario.name, differs: "Nothing.", evidence: "None.", steps: { "send Close": { happens: [] } } } - const agrees = yield* Effect.exit(check(genericHost, scenario, { _tag: "Differs", difference: entry })) + const agrees = yield* Effect.exit(check(referencePlannerHost, scenario, { _tag: "Differs", difference: entry })) assert.match(String(agrees), /no longer differs/) const changed = { ...scenario, steps: scenario.steps.slice(1) } - const other = yield* Effect.exit(check(genericHost, changed, { _tag: "Differs", difference: entry })) + const other = yield* Effect.exit(check(referencePlannerHost, changed, { _tag: "Differs", difference: entry })) assert.match(String(other), /to deeply equal/) })) diff --git a/packages/effect-machine/test/conformance/matrix.txt b/packages/effect-machine/test/conformance/matrix.txt index 396ac17a..4f2e5455 100644 --- a/packages/effect-machine/test/conformance/matrix.txt +++ b/packages/effect-machine/test/conformance/matrix.txt @@ -1,100 +1,100 @@ -scenario | LocalMachine (generic) | LocalMachine (compiled) | AtomMachine | ClusterMachine | Machine.toStep -settles in its initial state before any event | runs | runs | runs | differs | runs -starts from its input | runs | runs | runs | runs | runs -moves between states and carries their data | runs | runs | runs | runs | runs -takes an event that a constructor of its protocol built | runs | runs | runs | runs | runs -takes an event that no active state handles, and does nothing | runs | runs | runs | runs | runs -offers an event that a guard or a branch declines to the ancestor | runs | runs | runs | runs | runs -updates retained state, and exits and enters only what it is told to | runs | runs | runs | runs | runs -enters a compound state from its root and leaves it from its leaf | runs | runs | runs | runs | runs -handles an event in two regions as one step, unless a child stays | runs | runs | runs | runs | runs -lets the first of two regions win what both change | runs | runs | runs | runs | runs -returns to what shallow and deep history remember | runs | runs | runs | runs | runs -routes through choices without settling in one | runs | runs | runs | runs | runs -settles after the eventless and completion transitions of a step | runs | runs | runs | runs | runs -plans raised events in the step that raises them, in order | runs | runs | runs | runs | runs -emits the events of every kind of transition, in order | runs | runs | runs | runs | runs -ends in a final state with its output, and takes no event after it | runs | runs | runs | differs | runs -ends at once when its initial state is final | runs | runs | runs | differs | runs -refuses the payload of an event that its schema refuses | runs | runs | runs | runs | runs -a transition throws | runs | runs | runs | differs | runs -a step never settles | runs | runs | runs | differs | runs -a transition leads to a state that its schema refuses | runs | runs | runs | differs | runs -a transition emits an event that its schema refuses | runs | runs | runs | differs | runs -cannot settle in its initial state | runs | runs | runs | differs | runs -handles the events of one sender in the order they were sent | runs | runs | runs | runs | runs -carries class instances and transformed fields in events and states | runs | runs | runs | runs | runs -names itself to its transitions and to its work | runs | runs | runs | runs | runs -takes the event that its own command sends to it, in a later step | runs | runs | runs | runs | runs -routes the output of an effect through onDone | runs | runs | runs | runs | runs -routes the typed failure of an effect through onFailure | runs | runs | runs | runs | runs -does not restart the work of a state that stays active | runs | runs | runs | runs | runs -stops the work of a state it leaves, and starts it anew when it returns | runs | runs | runs | runs | runs -ignores a result that ends the work of a state while it is left | runs | runs | runs | runs | runs -ignores a typed failure that ends the work of a state while it is left | runs | runs | runs | runs | runs -ignores a defect that ends the work of a state while it is left | runs | runs | runs | runs | runs -fails after a typed failure without onFailure | runs | runs | runs | runs | runs -fails after a defect of its work | runs | runs | runs | runs | runs -fails after an interruption of its work | runs | runs | runs | runs | runs -fails after an output without onDone | runs | runs | runs | runs | runs -fails when the result of work cannot be applied | runs | runs | runs | runs | runs -fails when work cannot start, in the state that owns it | runs | runs | runs | runs | runs -starts the invocations of a state in their order, and ends them on their own | runs | runs | runs | runs | runs -runs the work of parallel regions on their own, from the outside in | runs | runs | runs | runs | runs -handles the end of work that does not suspend in a later step | runs | runs | runs | runs | runs -starts no work for a state it only passes through | runs | runs | runs | runs | runs -maps the input of work from the state and the event that entered it | runs | runs | runs | runs | runs -stops and starts the work of every level that a step exits and enters | runs | runs | runs | runs | runs -stops all work when it ends, also that of states that stay active | runs | runs | runs | differs | runs -stops work of states that stay active after publishing the final state and emissions | runs | runs | runs | runs | runs -retries work through a choice, and finishes with its output | runs | runs | runs | runs | runs -emits and raises events from the outcome of work | runs | runs | runs | runs | runs -starts the work of its initial state before any event | runs | runs | runs | differs | runs -takes the events that its own work sends to it | runs | runs | runs | runs | runs -lets the first of two ends that come together win | runs | runs | runs | runs | runs -prefers the typed failure of work that also dies | runs | runs | runs | runs | runs -closes the scope of work with its end, and with its stop | runs | runs | runs | runs | runs -maps the input of work that the outcome of other work starts | runs | runs | runs | runs | runs -starts work in the order in which one step enters states | runs | runs | runs | runs | runs -has released the work of the states it leaves before it starts that of the states it enters | runs | runs | runs | runs | runs -fires a timer at its duration, which its state parameterizes | runs | runs | runs | runs | runs -cancels a timer when its state is left | runs | runs | runs | runs | runs -starts a timer over when its state is entered again | runs | runs | runs | runs | runs -fires a timer without a duration, after the state that owns it | runs | runs | runs | runs | runs -stops the effect next to a timer that fires first | runs | runs | runs | runs | runs -cancels the timer next to an effect that ends first | runs | runs | runs | runs | runs -keeps a timer that waits when the effect next to it ends and stays | runs | runs | runs | runs | runs -fires the timers of two regions at their own times, and in order when they are due together | runs | runs | runs | runs | runs -fires a timer that stays once, until its state is entered again | runs | runs | runs | runs | runs -fires again and again in a state that its completion enters again | runs | runs | runs | runs | runs -fails when the completion of a timer cannot be applied | runs | runs | runs | runs | runs -fails when the duration of a timer throws, in the state that owns it | runs | runs | runs | runs | runs -fails when the input of a timer names no duration, in the state that owns it | runs | runs | runs | runs | runs -evaluates a duration in order with the other invocations of its state | runs | runs | runs | differs | runs -never fires a timer of infinite duration | runs | runs | runs | runs | runs -counts the timer of its initial state from its start | runs | runs | runs | differs | runs -restarts while work runs | runs | runs | runs | runs | runs -restarts while a timer waits | runs | runs | runs | differs | runs -restarts after a timer fell due | runs | runs | runs | differs | runs -restarts in a state whose work has ended | runs | runs | runs | differs | runs -restarts while the work of regions runs | runs | runs | runs | runs | runs -restarts with a history to return to | runs | runs | runs | runs | runs -restarts after it ended | runs | runs | runs | differs | runs -restarts after it failed | runs | runs | runs | differs | runs -restarts with decoded values | runs | runs | runs | runs | runs -restarts after one of two regions completed | runs | runs | runs | runs | runs -restarts in a state whose work ends at once | runs | runs | runs | runs | runs -handles the elements of a stream one by one, and its end | runs | runs | runs | skipped: Stream | runs -closes the scope of a stream with its end, and with its stop | runs | runs | runs | skipped: Stream | runs -handles a stream that produces everything at once | runs | runs | runs | skipped: Stream | runs -pulls the next element of a stream once it has handled the one before | runs | runs | runs | skipped: Stream | runs -stops a stream when its state is left, and takes no element of it after that | runs | runs | runs | skipped: Stream | runs -fails after a defect of a stream | runs | runs | runs | skipped: Stream | runs -routes the snapshots and the output of process logic, and drops those of an earlier run | runs | runs | runs | skipped: Logic | runs -closes the scope of process logic with its end, and with its stop | runs | runs | runs | skipped: Logic | runs -runs an invoked child machine, which reports to it and ends with an output | runs | runs | runs | runs | runs -fails with an invoked child machine that fails | runs | runs | runs | runs | runs -owns the children its work spawns, until it stops them or ends | runs | runs | runs | skipped: OwnedChildren | runs -stops the children its work spawned when its owner stops it | runs | runs | runs | skipped: OwnedChildren, Stop | runs -spawns process logic from its work, and stops it by its address | runs | runs | runs | skipped: OwnedChildren | runs -stops its work and takes no more events when its owner stops it | runs | runs | runs | skipped: Stop | runs +scenario | LocalMachine (reference planner) | LocalMachine (indexed planner) | AtomMachine | ClusterMachine | Machine.toStep +settles in its initial state before any event | runs | runs | runs | differs | runs +starts from its input | runs | runs | runs | runs | runs +moves between states and carries their data | runs | runs | runs | runs | runs +takes an event that a constructor of its protocol built | runs | runs | runs | runs | runs +takes an event that no active state handles, and does nothing | runs | runs | runs | runs | runs +offers an event that a guard or a branch declines to the ancestor | runs | runs | runs | runs | runs +updates retained state, and exits and enters only what it is told to | runs | runs | runs | runs | runs +enters a compound state from its root and leaves it from its leaf | runs | runs | runs | runs | runs +handles an event in two regions as one step, unless a child stays | runs | runs | runs | runs | runs +lets the first of two regions win what both change | runs | runs | runs | runs | runs +returns to what shallow and deep history remember | runs | runs | runs | runs | runs +routes through choices without settling in one | runs | runs | runs | runs | runs +settles after the eventless and completion transitions of a step | runs | runs | runs | runs | runs +plans raised events in the step that raises them, in order | runs | runs | runs | runs | runs +emits the events of every kind of transition, in order | runs | runs | runs | runs | runs +ends in a final state with its output, and takes no event after it | runs | runs | runs | differs | runs +ends at once when its initial state is final | runs | runs | runs | differs | runs +refuses the payload of an event that its schema refuses | runs | runs | runs | runs | runs +a transition throws | runs | runs | runs | differs | runs +a step never settles | runs | runs | runs | differs | runs +a transition leads to a state that its schema refuses | runs | runs | runs | differs | runs +a transition emits an event that its schema refuses | runs | runs | runs | differs | runs +cannot settle in its initial state | runs | runs | runs | differs | runs +handles the events of one sender in the order they were sent | runs | runs | runs | runs | runs +carries class instances and transformed fields in events and states | runs | runs | runs | runs | runs +names itself to its transitions and to its work | runs | runs | runs | runs | runs +takes the event that its own command sends to it, in a later step | runs | runs | runs | runs | runs +routes the output of an effect through onDone | runs | runs | runs | runs | runs +routes the typed failure of an effect through onFailure | runs | runs | runs | runs | runs +does not restart the work of a state that stays active | runs | runs | runs | runs | runs +stops the work of a state it leaves, and starts it anew when it returns | runs | runs | runs | runs | runs +ignores a result that ends the work of a state while it is left | runs | runs | runs | runs | runs +ignores a typed failure that ends the work of a state while it is left | runs | runs | runs | runs | runs +ignores a defect that ends the work of a state while it is left | runs | runs | runs | runs | runs +fails after a typed failure without onFailure | runs | runs | runs | runs | runs +fails after a defect of its work | runs | runs | runs | runs | runs +fails after an interruption of its work | runs | runs | runs | runs | runs +fails after an output without onDone | runs | runs | runs | runs | runs +fails when the result of work cannot be applied | runs | runs | runs | runs | runs +fails when work cannot start, in the state that owns it | runs | runs | runs | runs | runs +starts the invocations of a state in their order, and ends them on their own | runs | runs | runs | runs | runs +runs the work of parallel regions on their own, from the outside in | runs | runs | runs | runs | runs +handles the end of work that does not suspend in a later step | runs | runs | runs | runs | runs +starts no work for a state it only passes through | runs | runs | runs | runs | runs +maps the input of work from the state and the event that entered it | runs | runs | runs | runs | runs +stops and starts the work of every level that a step exits and enters | runs | runs | runs | runs | runs +stops all work when it ends, also that of states that stay active | runs | runs | runs | differs | runs +stops work of states that stay active after publishing the final state and emissions | runs | runs | runs | runs | runs +retries work through a choice, and finishes with its output | runs | runs | runs | runs | runs +emits and raises events from the outcome of work | runs | runs | runs | runs | runs +starts the work of its initial state before any event | runs | runs | runs | differs | runs +takes the events that its own work sends to it | runs | runs | runs | runs | runs +lets the first of two ends that come together win | runs | runs | runs | runs | runs +prefers the typed failure of work that also dies | runs | runs | runs | runs | runs +closes the scope of work with its end, and with its stop | runs | runs | runs | runs | runs +maps the input of work that the outcome of other work starts | runs | runs | runs | runs | runs +starts work in the order in which one step enters states | runs | runs | runs | runs | runs +has released the work of the states it leaves before it starts that of the states it enters | runs | runs | runs | runs | runs +fires a timer at its duration, which its state parameterizes | runs | runs | runs | runs | runs +cancels a timer when its state is left | runs | runs | runs | runs | runs +starts a timer over when its state is entered again | runs | runs | runs | runs | runs +fires a timer without a duration, after the state that owns it | runs | runs | runs | runs | runs +stops the effect next to a timer that fires first | runs | runs | runs | runs | runs +cancels the timer next to an effect that ends first | runs | runs | runs | runs | runs +keeps a timer that waits when the effect next to it ends and stays | runs | runs | runs | runs | runs +fires the timers of two regions at their own times, and in order when they are due together | runs | runs | runs | runs | runs +fires a timer that stays once, until its state is entered again | runs | runs | runs | runs | runs +fires again and again in a state that its completion enters again | runs | runs | runs | runs | runs +fails when the completion of a timer cannot be applied | runs | runs | runs | runs | runs +fails when the duration of a timer throws, in the state that owns it | runs | runs | runs | runs | runs +fails when the input of a timer names no duration, in the state that owns it | runs | runs | runs | runs | runs +evaluates a duration in order with the other invocations of its state | runs | runs | runs | differs | runs +never fires a timer of infinite duration | runs | runs | runs | runs | runs +counts the timer of its initial state from its start | runs | runs | runs | differs | runs +restarts while work runs | runs | runs | runs | runs | runs +restarts while a timer waits | runs | runs | runs | differs | runs +restarts after a timer fell due | runs | runs | runs | differs | runs +restarts in a state whose work has ended | runs | runs | runs | differs | runs +restarts while the work of regions runs | runs | runs | runs | runs | runs +restarts with a history to return to | runs | runs | runs | runs | runs +restarts after it ended | runs | runs | runs | differs | runs +restarts after it failed | runs | runs | runs | differs | runs +restarts with decoded values | runs | runs | runs | runs | runs +restarts after one of two regions completed | runs | runs | runs | runs | runs +restarts in a state whose work ends at once | runs | runs | runs | runs | runs +handles the elements of a stream one by one, and its end | runs | runs | runs | skipped: Stream | runs +closes the scope of a stream with its end, and with its stop | runs | runs | runs | skipped: Stream | runs +handles a stream that produces everything at once | runs | runs | runs | skipped: Stream | runs +pulls the next element of a stream once it has handled the one before | runs | runs | runs | skipped: Stream | runs +stops a stream when its state is left, and takes no element of it after that | runs | runs | runs | skipped: Stream | runs +fails after a defect of a stream | runs | runs | runs | skipped: Stream | runs +routes the snapshots and the output of process logic, and drops those of an earlier run | runs | runs | runs | skipped: Logic | runs +closes the scope of process logic with its end, and with its stop | runs | runs | runs | skipped: Logic | runs +runs an invoked child machine, which reports to it and ends with an output | runs | runs | runs | runs | runs +fails with an invoked child machine that fails | runs | runs | runs | runs | runs +owns the children its work spawns, until it stops them or ends | runs | runs | runs | skipped: OwnedChildren | runs +stops the children its work spawned when its owner stops it | runs | runs | runs | skipped: OwnedChildren, Stop | runs +spawns process logic from its work, and stops it by its address | runs | runs | runs | skipped: OwnedChildren | runs +stops its work and takes no more events when its owner stops it | runs | runs | runs | skipped: Stop | runs diff --git a/packages/effect-machine/test/conformance/support/hosts/step.ts b/packages/effect-machine/test/conformance/support/hosts/step.ts index 37622544..f477224c 100644 --- a/packages/effect-machine/test/conformance/support/hosts/step.ts +++ b/packages/effect-machine/test/conformance/support/hosts/step.ts @@ -345,10 +345,10 @@ export const stepHost: Host = { self: endpoint, parent, spawn: () => notOffered("children of process logic"), - sendTo: ((target: Machine.MachineTarget | string, event: unknown) => + sendTo: (target: Machine.MachineTarget | string, event: unknown) => typeof target === "string" ? notOffered("children of process logic") - : target.send(event)) as Machine.Logic.InitialContext["sendTo"], + : target.send(event), stopChild: () => notOffered("children of process logic") } const setState = (next: unknown) => diff --git a/packages/effect-machine/test/internal/ObservationDifferential.test.ts b/packages/effect-machine/test/internal/ObservationDifferential.test.ts index 14e54e55..a3222504 100644 --- a/packages/effect-machine/test/internal/ObservationDifferential.test.ts +++ b/packages/effect-machine/test/internal/ObservationDifferential.test.ts @@ -13,7 +13,7 @@ describe("Observation across runtime strategies", () => { expected: "indexed-flat", label: "structural state reentry" })) - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { it.effect(`${strategy}: preserves waiting and invocation ownership across reentry`, () => Effect.gen(function*() { const { spans, tracer } = yield* recordingTracer diff --git a/packages/effect-machine/test/internal/machine/ScopedLifetime.test.ts b/packages/effect-machine/test/internal/machine/ScopedLifetime.test.ts index 25b1c2ea..7af14107 100644 --- a/packages/effect-machine/test/internal/machine/ScopedLifetime.test.ts +++ b/packages/effect-machine/test/internal/machine/ScopedLifetime.test.ts @@ -2,7 +2,6 @@ import { assert, describe, it } from "@effect/vitest" import { Effect, Ref, Stream } from "effect" import { Machine } from "../../../src/index.js" import * as Process from "../../../src/internal/machine/process.js" -import type * as Runtime from "../../../src/internal/machine/runtime.js" const makeWatcher = (released: Ref.Ref) => Machine.make({ @@ -14,7 +13,7 @@ const makeWatcher = (released: Ref.Ref) => states: { Watching: { invoke: { src: "watch", onDone: { stay: true } } } } }) -const strategies: ReadonlyArray = ["generic", "compiled"] +const strategies: ReadonlyArray = ["reference", "indexed"] describe("Machine scoped lifetime strategies", () => { for (const strategy of strategies) { diff --git a/packages/effect-machine/test/internal/machine/capability.test.ts b/packages/effect-machine/test/internal/machine/capability.test.ts index aa7836ba..55fb0c9a 100644 --- a/packages/effect-machine/test/internal/machine/capability.test.ts +++ b/packages/effect-machine/test/internal/machine/capability.test.ts @@ -28,10 +28,10 @@ type CounterRef = Machine.MachineRef const startOwner = ( work: Effect.Effect< void, - Machine.ChildAlreadyExistsError | Machine.StoppedError, + Machine.ChildAlreadyExistsError | Machine.StoppedError | Machine.MachineSchemaDecodeError, Machine.MachineRuntime | Machine.ChildMachineRuntime >, - strategy: "generic" | "compiled" + strategy: Process.LocalPlannerStrategy ) => { const owner = Machine.make({ id: "Owner", @@ -46,8 +46,8 @@ const startOwner = ( return Process.startWithRuntimeStrategyForTesting(owner, strategy) } -for (const strategy of ["generic", "compiled"] as const) { - describe(`MachineRuntime on the ${strategy} local runtime`, () => { +for (const strategy of ["reference", "indexed"] as const) { + describe(`MachineRuntime on the ${strategy} planner`, () => { it.effect("spawns, sends to, and stops process logic owned by the machine", () => Effect.gen(function*() { const spawned = yield* Deferred.make() diff --git a/packages/effect-machine/test/internal/machine/invocationStart.test.ts b/packages/effect-machine/test/internal/machine/invocationStart.test.ts index 0bdf9172..1f2d5231 100644 --- a/packages/effect-machine/test/internal/machine/invocationStart.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationStart.test.ts @@ -37,8 +37,8 @@ const makeMachine = (steps: Array, duration: (seconds: number) => Durati }) describe("local timer invocations", () => { - for (const strategy of ["generic", "compiled"] as const) { - describe(`${strategy} runtime`, () => { + for (const strategy of ["reference", "indexed"] as const) { + describe(`${strategy} planner`, () => { it.effect("constructs a timer after the state is entered and earlier invocations have started", () => Effect.gen(function*() { const steps: Array = [] diff --git a/packages/effect-machine/test/internal/machine/planningFailures.test.ts b/packages/effect-machine/test/internal/machine/planningFailures.test.ts index 69a833b4..e690dc37 100644 --- a/packages/effect-machine/test/internal/machine/planningFailures.test.ts +++ b/packages/effect-machine/test/internal/machine/planningFailures.test.ts @@ -79,7 +79,7 @@ describe("planning failure classification", () => { ) }) - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { it.effect(`${strategy}: wraps an initializer defect in StartupError`, () => Effect.gen(function*() { const error = yield* Effect.flip( diff --git a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts index 526fa137..cc73423b 100644 --- a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts +++ b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts @@ -510,6 +510,64 @@ describe("Machine.toStep planner and ownership", () => { } })) + it("matches startSnapshot against start for active, final, and failing childless machines", () => { + const FinalAtStart = Machine.make({ + root: Machine.state({ states: { Done: { type: "final", output: Schema.Number } } }), + events: Machine.events({}) + }).handle({ + initial: { target: "Done" }, + states: { Done: { output: () => 42 } } + }) + const boom = new Error("boom") + const FailingStart = Machine.make({ + root: Machine.state({ states: { Idle: { fields: { count: Schema.Number } } } }), + events: Machine.events({}) + }).handle({ + initial: { + target: "Idle", + data: () => { + throw boom + } + }, + states: { Idle: {} } + }) + for (const machine of [Counter, Regions, FinalAtStart, FailingStart, Worker]) { + for ( + const plan of [ExecutionPlan.compileExecutionPlan(machine), ExecutionPlan.referenceExecutionPlan(machine)] + ) { + for (const ownership of ["Owned", "Persistent"] as const) { + const kernel = Step.kernel(machine, ownership, plan) + if (machine === Worker) { + assert.strictEqual(kernel.startSnapshot, undefined) + continue + } + if (kernel.startSnapshot === undefined) continue + const planning = new Step.Planning(machine, kernel.plan, self, undefined, undefined) + const expected = kernel.start(planning, [], true) + if (Exit.isFailure(expected)) { + let thrown: unknown + try { + kernel.startSnapshot(planning, []) + } catch (error) { + thrown = error + } + assert.instanceOf(thrown, Machine.StartupError) + assert.strictEqual( + Cause.squash(thrown.cause), + Cause.squash((Cause.squash(expected.cause) as Machine.StartupError).cause) + ) + } else { + const direct = kernel.startSnapshot(planning, []) + assert.deepStrictEqual(direct.state, expected.value.snapshot) + const exit = expected.value.exit + assert.strictEqual(direct.done, exit !== undefined && Exit.isSuccess(exit)) + assert.deepStrictEqual(direct.output, exit !== undefined && Exit.isSuccess(exit) ? exit.value : undefined) + } + } + } + } + }) + it("are not the states of the persistent step functions", () => { const owned: Step.OwnedMachineStep = counter() const persistent: Step.MachineStep = Step.make(Counter, { self }) diff --git a/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts b/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts index 3da97b37..52240f12 100644 --- a/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts +++ b/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts @@ -60,7 +60,7 @@ const makeFlatMachine = () => { }) } describe("machine planner and runtime strategies", () => { - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { it.effect(`keeps independent root lifecycles isolated with the ${strategy} runtime`, () => Effect.gen(function*() { const machine = makeFlatMachine() @@ -798,7 +798,7 @@ describe("machine planner and runtime strategies", () => { } } }) - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(machine, strategy) const updated = yield* ref.changes.pipe( Stream.filter((snapshot) => snapshot.status === "active" && snapshot.state.state.value.value === 2), @@ -862,7 +862,7 @@ describe("machine planner and runtime strategies", () => { } } }) - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { value = 1 const ref = yield* openWithRuntimeStrategy(machine, strategy) const observed = yield* ref.emissions.pipe( @@ -909,7 +909,7 @@ describe("machine planner and runtime strategies", () => { } } }) - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const prepared = yield* prepareWithRuntimeStrategy(machine, strategy) const observed = yield* prepared.emissions.pipe( Stream.take(1), @@ -925,7 +925,7 @@ describe("machine planner and runtime strategies", () => { Effect.scoped(Effect.gen(function*() { const machine = makeFlatMachine() const results: Array> = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const prepared = yield* prepareWithRuntimeStrategy(machine, strategy) const observed = yield* prepared.inspection.pipe( Stream.runCollect, @@ -946,7 +946,7 @@ describe("machine planner and runtime strategies", () => { Effect.gen(function*() { const machine = makeFlatMachine() const traces: Array> = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(machine, strategy) const trace: Array = [] for (const event of [new Noop({}), new Increment({}), new Reenter({}), new Increment({}), new Finish({})]) { @@ -998,7 +998,7 @@ describe("machine planner and runtime strategies", () => { } }) const traces: Array> = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { started = yield* Deferred.make() const ref = yield* openWithRuntimeStrategy(machine, strategy) // Delivery is synchronous once startup has settled and the machine is @@ -1027,7 +1027,7 @@ describe("machine planner and runtime strategies", () => { Effect.gen(function*() { const machine = makeFlatMachine() const results: Array = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(machine, strategy) const probe = yield* MachineTest.probe(machine, ref) const steps = [] @@ -1059,7 +1059,7 @@ describe("machine planner and runtime strategies", () => { it.effect("does not mutate retained public snapshots in either runtime strategy", () => Effect.gen(function*() { const machine = makeFlatMachine() - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(machine, strategy) const retained = yield* ref.snapshot const retainedEncoding = yield* Machine.encodeSnapshot(machine, retained.state) @@ -1115,7 +1115,7 @@ describe("machine planner and runtime strategies", () => { }) assert.strictEqual(ExecutionPlan.selectExecutionPlanForTesting(machine, "auto").strategy, "indexed-flat") const results: Array = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(machine, strategy) results.push({ output: yield* ref.join, @@ -1212,7 +1212,7 @@ describe("machine planner and runtime strategies", () => { } }) const outputs: Array = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const ref = yield* openWithRuntimeStrategy(parentMachine, strategy) outputs.push(yield* ref.join) } @@ -1293,7 +1293,7 @@ describe("machine planner and runtime strategies", () => { steps.push({ event, plan }) state = plan.next } - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { yield* verifyManagedExecution({ machine, open: openWithRuntimeStrategy(machine, strategy), @@ -1413,7 +1413,7 @@ describe("machine planner and runtime strategies", () => { it.effect("matches generic and compiled managed runtimes when a stale invocation result is queued", () => Effect.scoped(Effect.gen(function*() { const results: Array = [] - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { const holdEntered = yield* Deferred.make() const releaseHold = yield* Deferred.make() const attempts = [yield* Deferred.make(), yield* Deferred.make()] diff --git a/packages/effect-machine/test/internal/machine/support/conformanceHosts.ts b/packages/effect-machine/test/internal/machine/support/conformanceHosts.ts index 465ba8ba..f8e48447 100644 --- a/packages/effect-machine/test/internal/machine/support/conformanceHosts.ts +++ b/packages/effect-machine/test/internal/machine/support/conformanceHosts.ts @@ -1,16 +1,17 @@ /** Hosts of the conformance suite that need internals of the library. */ +import type { LocalPlannerStrategy } from "../../../../src/internal/machine/process.js" import type { Host } from "../../../conformance/support/host.js" import { makeLocalHost } from "../../../conformance/support/hosts/local.js" import { openWithRuntimeStrategy, resumeWithRuntimeStrategy } from "./strategyDifferential.js" -const localHost = (strategy: "generic" | "compiled"): Host => +const localHost = (strategy: LocalPlannerStrategy, label: string): Host => makeLocalHost({ - name: `LocalMachine (${strategy})`, + name: `LocalMachine (${label})`, start: (machine, ...input) => openWithRuntimeStrategy(machine, strategy, ...input), resume: (machine, snapshot) => resumeWithRuntimeStrategy(machine, snapshot, strategy) }) /** The reference of the suite. */ -export const genericHost: Host = localHost("generic") +export const referencePlannerHost: Host = localHost("reference", "reference planner") -export const compiledHost: Host = localHost("compiled") +export const indexedPlannerHost: Host = localHost("indexed", "indexed planner") diff --git a/packages/effect-machine/test/internal/machine/support/strategyDifferential.ts b/packages/effect-machine/test/internal/machine/support/strategyDifferential.ts index be45dfd4..8b40459b 100644 --- a/packages/effect-machine/test/internal/machine/support/strategyDifferential.ts +++ b/packages/effect-machine/test/internal/machine/support/strategyDifferential.ts @@ -125,14 +125,14 @@ export const verifyPlannerStrategies: ): Effect.Effect, unknown> => Process.startWithRuntimeStrategyForTesting(machine, strategy, ...args) as any export const prepareWithRuntimeStrategy = ( machine: Machine.Machine.Any, - strategy: "generic" | "compiled" + strategy: Process.LocalPlannerStrategy ): Effect.Effect< { readonly emissions: import("effect/Stream").Stream @@ -145,14 +145,14 @@ export const prepareWithRuntimeStrategy = ( export const resumeWithRuntimeStrategy = ( machine: Machine.Machine.Any, snapshot: Machine.Machine.Snapshot, - strategy: "generic" | "compiled" + strategy: Process.LocalPlannerStrategy ): Effect.Effect, unknown> => Process.resumeWithRuntimeStrategyForTesting(machine, snapshot, strategy) as any export const prepareResumedWithRuntimeStrategy = ( machine: Machine.Machine.Any, snapshot: Machine.Machine.Snapshot, - strategy: "generic" | "compiled" + strategy: Process.LocalPlannerStrategy ): Effect.Effect< { readonly inspection: import("effect/Stream").Stream diff --git a/packages/effect-machine/test/machine/ChildStoppedByParent.test.ts b/packages/effect-machine/test/machine/ChildStoppedByParent.test.ts index c4683eb5..4f16ceb4 100644 --- a/packages/effect-machine/test/machine/ChildStoppedByParent.test.ts +++ b/packages/effect-machine/test/machine/ChildStoppedByParent.test.ts @@ -73,7 +73,7 @@ describe("a child invocation's onDone notifies a parent that stops the child", ( ["asynchronous", Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 10)))] ] as const ) { - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { it.live(`${name} invocation, ${strategy} parent`, () => Effect.gen(function*() { const { Child, machine: definition } = makeParent(work) diff --git a/packages/effect-machine/test/machine/InvocationGeneration.test.ts b/packages/effect-machine/test/machine/InvocationGeneration.test.ts index bda85875..66d3adc9 100644 --- a/packages/effect-machine/test/machine/InvocationGeneration.test.ts +++ b/packages/effect-machine/test/machine/InvocationGeneration.test.ts @@ -161,7 +161,7 @@ const isFence = (event: unknown) => typeof event === "object" && event !== null && "_tag" in event && event._tag === "Fence" describe("queued invocation generations", () => { - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { for (const reentry of ["reenter", "exit and enter", "retained"] as const) { for (const outcome of outcomes) { it.effect( @@ -362,7 +362,7 @@ const queueBehindHold = Effect.fn(function*(options: { const Result = { fields: { result: Schema.Number } } describe("invocation generations at owner boundaries", () => { - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { it.effect(`${strategy} keeps a parallel sibling's queued result when another region reenters`, () => Effect.gen(function*() { const gate = yield* makeGate() diff --git a/packages/effect-machine/test/machine/InvocationTurn.test.ts b/packages/effect-machine/test/machine/InvocationTurn.test.ts index 3fba8dd8..24e30a82 100644 --- a/packages/effect-machine/test/machine/InvocationTurn.test.ts +++ b/packages/effect-machine/test/machine/InvocationTurn.test.ts @@ -82,7 +82,7 @@ const makeHostMachine = (started: Array, release: Deferred.Deferred) => snapshot.state.state.path describe("invocations entered by a send", () => { - for (const strategy of ["generic", "compiled"] as const) { + for (const strategy of ["reference", "indexed"] as const) { describe(`${strategy} runtime`, () => { it.effect("runs invoked work until it first suspends before send returns", () => Effect.gen(function*() { diff --git a/packages/effect-machine/test/machine/SendRejection.test.ts b/packages/effect-machine/test/machine/SendRejection.test.ts new file mode 100644 index 00000000..7460e706 --- /dev/null +++ b/packages/effect-machine/test/machine/SendRejection.test.ts @@ -0,0 +1,344 @@ +import { assert, describe, it } from "@effect/vitest" +import { Cause, Deferred, Effect, Exit, Option, Schema } from "effect" +import { AsyncResult, AtomRegistry } from "effect/reactivity" +import { LocalMachine, Machine } from "../../src/index.js" +import { AtomMachine } from "../../src/unstable/reactivity/index.js" + +const CounterEvents = Machine.events({ + Add: { amount: Schema.Number } +}) + +const makeCounter = (id = "Counter") => + Machine.make({ + id, + root: Machine.state({ + states: { + Open: { fields: { total: Schema.Number } } + } + }), + events: CounterEvents + }).handle({ + initial: { target: "Open", data: { total: 0 } }, + states: { + Open: { + on: { + Add: { target: "Open", data: ({ event, state }) => ({ total: state.total + event.amount }) } + } + } + } + }) + +const invalidAdd = { _tag: "Add", amount: "bad" } as never + +describe("send and sendTo schema rejection semantics", () => { + it.effect("MachineRef.send rejects refused events and keeps the machine running", () => + Effect.gen(function*() { + const ref = yield* LocalMachine.start(makeCounter()) + const error = yield* Effect.flip(ref.send(invalidAdd)) + assert.instanceOf(error, Machine.MachineSchemaDecodeError) + assert.strictEqual(error.boundary, "event") + assert.strictEqual((yield* ref.snapshot).status, "active") + + yield* ref.send({ _tag: "Add", amount: 3 }) + const state = yield* ref.state + assert.strictEqual(state.state.path === "Open" ? state.state.value.total : -1, 3) + }).pipe(Effect.scoped)) + + it.effect("MachineTarget.send on self, external ref, and parent rejects refused events and keeps receivers running", () => + Effect.gen(function*() { + const other = yield* LocalMachine.start(makeCounter("Other")) + const results = { + self: yield* Deferred.make(), + other: yield* Deferred.make(), + parent: yield* Deferred.make() + } + + const ParentEvents = Machine.events({ Notice: { count: Schema.Number } }) + const childMachine = Machine.make({ + id: "Child", + root: Machine.state({ states: { Active: {} } }), + events: CounterEvents, + parent: Machine.parent(ParentEvents), + effects: { + badParent: (parent: Machine.MachineTarget) => + Effect.flatMap( + Effect.flip(parent.send({ _tag: "Notice", count: "bad" } as never)), + (error) => Deferred.succeed(results.parent, error) + ).pipe(Effect.orDie) + } + }).handle({ + initial: { target: "Active" }, + states: { + Active: { + invoke: { src: "badParent", input: ({ parent }) => parent, onDone: { stay: true } } + } + } + }) + const Child = Machine.child("child", childMachine) + + const parentMachine = Machine.make({ + id: "Parent", + root: Machine.state({ states: { Running: { fields: { notices: Schema.Number } } } }), + events: ParentEvents, + children: { child: Child }, + effects: { + badSelf: (self: Machine.MachineTarget) => + Effect.flatMap( + Effect.flip(self.send({ _tag: "Notice", count: "bad" } as never)), + (error) => Deferred.succeed(results.self, error) + ).pipe(Effect.orDie), + badOther: Effect.flatMap( + Effect.flip(other.send(invalidAdd)), + (error) => Deferred.succeed(results.other, error) + ).pipe(Effect.orDie) + } + }).handle({ + initial: { target: "Running", data: { notices: 0 } }, + states: { + Running: { + on: { + Notice: { target: "Running", data: ({ event, state }) => ({ notices: state.notices + event.count }) } + }, + invoke: [ + { src: "child" }, + { src: "badSelf", input: ({ self }) => self, onDone: { stay: true } }, + { src: "badOther", onDone: { stay: true } } + ] + } + } + }) + + const parentRef = yield* LocalMachine.start(parentMachine) + const [selfErr, otherErr, parentErr] = yield* Effect.all([ + Deferred.await(results.self), + Deferred.await(results.other), + Deferred.await(results.parent) + ]) + assert.instanceOf(selfErr, Machine.MachineSchemaDecodeError) + assert.instanceOf(otherErr, Machine.MachineSchemaDecodeError) + assert.instanceOf(parentErr, Machine.MachineSchemaDecodeError) + + // All receivers stayed active and process valid events. + yield* parentRef.send({ _tag: "Notice", count: 5 }) + yield* other.send({ _tag: "Add", amount: 7 }) + const parentState = yield* parentRef.state + const otherState = yield* other.state + assert.strictEqual(parentState.state.path === "Running" ? parentState.state.value.notices : -1, 5) + assert.strictEqual(otherState.state.path === "Open" ? otherState.state.value.total : -1, 7) + }).pipe(Effect.scoped)) + + it.effect("ChildOwner.sendTo, Machine.sendTo(child), and Machine.sendTo(address) reject refused events", () => + Effect.gen(function*() { + const Child = Machine.child("worker", makeCounter("Worker")) + const WorkerAddr = Machine.childAddress>("worker") + const LogicAddr = Machine.childAddress("logic-worker") + const logicReceived = yield* Deferred.make() + const errors = yield* Deferred.make>() + + const simpleLogic = Machine.logic({ + initial: 0, + run: (context) => + Effect.flatMap(context.receive, (value) => Deferred.succeed(logicReceived, value).pipe(Effect.asVoid)) + }) + + const ownerMachine = Machine.make({ + id: "Owner", + root: Machine.state({ states: { Active: {} } }), + events: Machine.events({}), + children: { worker: Child }, + effects: { + probe: (children: Machine.ChildOwner) => + Effect.gen(function*() { + yield* Machine.spawn(simpleLogic, { id: LogicAddr }) + const ownerErr = yield* Effect.flip(children.sendTo(Child, invalidAdd)) + const descriptorErr = yield* Effect.flip(Machine.sendTo(Child, invalidAdd)) + const addressErr = yield* Effect.flip(Machine.sendTo(WorkerAddr, invalidAdd)) + // Logic has no schema, so Machine.sendTo(LogicAddr, ...) delivers cleanly. + yield* Machine.sendTo(LogicAddr, 42) + yield* Deferred.succeed(errors, [ownerErr, descriptorErr, addressErr]) + }).pipe(Effect.orDie) + } + }).handle({ + initial: { target: "Active" }, + states: { + Active: { + invoke: [ + { src: "worker" }, + { src: "probe", input: ({ children }) => children, onDone: { stay: true } } + ] + } + } + }) + + const owner = yield* LocalMachine.start(ownerMachine) + const [ownerErr, descriptorErr, addressErr] = yield* Deferred.await(errors) + assert.instanceOf(ownerErr, Machine.MachineSchemaDecodeError) + assert.instanceOf(descriptorErr, Machine.MachineSchemaDecodeError) + assert.instanceOf(addressErr, Machine.MachineSchemaDecodeError) + assert.strictEqual(yield* Deferred.await(logicReceived), 42) + + // Child machine remained active and accepts valid events. + const childRef = Option.getOrThrow(yield* owner.child(Child)) + assert.strictEqual((yield* childRef.snapshot).status, "active") + yield* childRef.send({ _tag: "Add", amount: 9 }) + const childState = yield* childRef.state + assert.strictEqual(childState.state.path === "Open" ? childState.state.value.total : -1, 9) + }).pipe(Effect.scoped)) + + it.effect("Logic.Endpoint.send and Logic.InitialContext.sendTo reject refused events on parent and child machines", () => + Effect.gen(function*() { + const ParentEvents = Machine.events({ Ping: { n: Schema.Number } }) + const Child = Machine.child("child", makeCounter("Child")) + const results = yield* Deferred.make>() + + const probeLogic = Machine.logic({ + initial: null, + run: (context) => + Effect.gen(function*() { + const parent = context.parent! + const viaEndpoint = yield* Effect.flip(parent.send({ _tag: "Ping", n: "bad" })) + const viaSendToEndpoint = yield* Effect.flip(context.sendTo(parent, { _tag: "Ping", n: "bad" })) + yield* Deferred.succeed(results, [viaEndpoint, viaSendToEndpoint]) + }).pipe(Effect.orDie) + }) + + const ProbeAddr = Machine.childAddress("probe-logic") + const parentMachine = Machine.make({ + id: "Parent", + root: Machine.state({ states: { Active: { fields: { sum: Schema.Number } } } }), + events: ParentEvents, + children: { child: Child }, + logic: { probe: probeLogic } + }).handle({ + initial: { target: "Active", data: { sum: 0 } }, + states: { + Active: { + on: { Ping: { target: "Active", data: ({ event, state }) => ({ sum: state.sum + event.n }) } }, + invoke: [{ src: "child" }, { src: "probe", id: "probe-logic", address: ProbeAddr, onDone: { stay: true } }] + } + } + }) + + // Also verify inspected machines via LocalMachine.prepare. + const prepared = yield* LocalMachine.prepare(parentMachine) + const ref = yield* prepared.start + const [viaEndpoint, viaSendToEndpoint] = yield* Deferred.await(results) + assert.instanceOf(viaEndpoint, Machine.MachineSchemaDecodeError) + assert.instanceOf(viaSendToEndpoint, Machine.MachineSchemaDecodeError) + + assert.strictEqual((yield* ref.snapshot).status, "active") + yield* ref.send({ _tag: "Ping", n: 11 }) + const state = yield* ref.state + assert.strictEqual(state.state.path === "Active" ? state.state.value.sum : -1, 11) + }).pipe(Effect.scoped)) + + it.effect("AtomMachine send atoms (root and child) reject refused events and keep machines running", () => + Effect.scoped(Effect.gen(function*() { + const registry = yield* Effect.acquireRelease( + Effect.sync(() => AtomRegistry.make()), + (r) => Effect.sync(() => r.dispose()) + ) + const Child = Machine.child("child", makeCounter("AtomChild")) + const parentDef = Machine.make({ + id: "AtomParent", + root: Machine.state({ states: { Open: { fields: { total: Schema.Number } } } }), + events: CounterEvents, + children: { child: Child } + }).handle({ + initial: { target: "Open", data: { total: 0 } }, + states: { + Open: { + invoke: { src: "child" }, + on: { Add: { target: "Open", data: ({ event, state }) => ({ total: state.total + event.amount }) } } + } + } + }) + const bridge = AtomMachine.make(parentDef) + const childBridge = bridge.child(Child) + const mountAtom = (atom: Parameters[0]) => + Effect.acquireRelease(Effect.sync(() => registry.mount(atom)), (release) => Effect.sync(release)) + yield* mountAtom(bridge.snapshot) + yield* mountAtom(childBridge.snapshot) + yield* AtomRegistry.getResult(registry, bridge.ref) + + registry.set(bridge.send, invalidAdd) + const rootResult = registry.get(bridge.send) + assert.isTrue(AsyncResult.isFailure(rootResult)) + if (AsyncResult.isFailure(rootResult)) { + assert.instanceOf(Option.getOrThrow(Cause.findErrorOption(rootResult.cause)), Machine.MachineSchemaDecodeError) + } + + registry.set(childBridge.send, invalidAdd) + const childResult = registry.get(childBridge.send) + assert.isTrue(AsyncResult.isFailure(childResult)) + if (AsyncResult.isFailure(childResult)) { + assert.instanceOf(Option.getOrThrow(Cause.findErrorOption(childResult.cause)), Machine.MachineSchemaDecodeError) + } + + // Both root and child stayed active and handle valid events. + registry.set(bridge.send, { _tag: "Add", amount: 4 }) + registry.set(childBridge.send, { _tag: "Add", amount: 6 }) + const rootSnap = yield* AtomRegistry.getResult(registry, bridge.snapshot) + assert.strictEqual( + rootSnap.status === "active" && rootSnap.state.state.path === "Open" ? rootSnap.state.state.value.total : -1, + 4 + ) + const childSnap = Option.getOrThrow(yield* AtomRegistry.getResult(registry, childBridge.snapshot)) + assert.strictEqual( + childSnap.status === "active" && childSnap.state.state.path === "Open" ? childSnap.state.state.value.total : -1, + 6 + ) + }))) + + it.effect("transition commands enqueue.sendTo still fail the receiving machine when an event is refused", () => + Effect.gen(function*() { + const Child = Machine.child("child", makeCounter("CommandChild")) + const ParentEvents = Machine.events({ + BadSelf: {}, + BadChild: {}, + Good: { n: Schema.Number } + }) + + const machine = Machine.make({ + id: "CommandOwner", + root: Machine.state({ states: { Active: {} } }), + events: ParentEvents, + children: { child: Child } + }).handle({ + initial: { target: "Active" }, + states: { + Active: { + invoke: { src: "child" }, + on: { + BadSelf: { + stay: true, + commands: ({ self }, enqueue) => enqueue.sendTo(self, { _tag: "Good", n: "bad" } as never) + }, + BadChild: { + stay: true, + commands: (_, enqueue) => enqueue.sendTo(Child, invalidAdd) + }, + Good: { stay: true } + } + } + } + }) + + // Self command fails the owner when planned. + const selfOwner = yield* LocalMachine.start(machine) + yield* selfOwner.send({ _tag: "BadSelf" }) + const selfExit = yield* Effect.exit(selfOwner.join) + assert.isTrue(Exit.isFailure(selfExit)) + const selfSnap = yield* selfOwner.snapshot + assert.strictEqual(selfSnap.status, "failed") + + // Child command fails the child when planned. + const childOwner = yield* LocalMachine.start(machine) + const childRef = Option.getOrThrow(yield* childOwner.child(Child)) + yield* childOwner.send({ _tag: "BadChild" }) + const childExit = yield* Effect.exit(childRef.join) + assert.isTrue(Exit.isFailure(childExit)) + const childSnap = yield* childRef.snapshot + assert.strictEqual(childSnap.status, "failed") + }).pipe(Effect.scoped)) +}) diff --git a/packages/effect-machine/test/machine/support/invocationLifecycleModel.ts b/packages/effect-machine/test/machine/support/invocationLifecycleModel.ts index 21d3267c..3a42e8dd 100644 --- a/packages/effect-machine/test/machine/support/invocationLifecycleModel.ts +++ b/packages/effect-machine/test/machine/support/invocationLifecycleModel.ts @@ -97,7 +97,8 @@ export const makeInvocationProbe: Effect.Effect = Effect.gen(fu return Effect.never.pipe( Effect.onInterrupt(() => sendTo(parent, behavior.event(epoch)).pipe( - Effect.catchTag("StoppedError", () => Effect.void) + Effect.catchTag("StoppedError", () => Effect.void), + Effect.orDie ) ), Effect.asVoid diff --git a/packages/effect-machine/test/unstable/cluster/Sends.test.ts b/packages/effect-machine/test/unstable/cluster/Sends.test.ts index 14ed1c0f..2eba1b53 100644 --- a/packages/effect-machine/test/unstable/cluster/Sends.test.ts +++ b/packages/effect-machine/test/unstable/cluster/Sends.test.ts @@ -235,6 +235,111 @@ describe("ClusterMachine machines that send to each other", () => { assert.isTrue(Exit.isFailure(exit) && Exit.hasDies(exit)) })) + it.effect("reject refused events with MachineSchemaDecodeError on target.send, self.send, parent.send, and sendTo(child) while keeping receivers running", () => + Effect.gen(function*() { + const ChildEvents = Machine.events({ Bump: { n: Schema.Number } }) + const ParentEvents = Machine.events({ Probe: {}, Notify: { n: Schema.Number } }) + const recorded: Array = [] + + const childDef = Machine.make({ + id: "ClusterChild", + root: Machine.state({ states: { Active: { fields: { total: Schema.Number } } } }), + events: ChildEvents, + parent: Machine.parent(ParentEvents), + effects: { + badParent: (parent: Machine.MachineTarget) => + Effect.flatMap( + Effect.flip(parent.send({ _tag: "Notify", n: "bad" } as never)), + (error) => + Effect.sync(() => { + recorded.push(["parent", error]) + }) + ).pipe(Effect.orDie) + } + }).handle({ + initial: { target: "Active", data: { total: 0 } }, + states: { + Active: { + on: { Bump: { target: "Active", data: ({ event, state }) => ({ total: state.total + event.n }) } }, + invoke: { src: "badParent", input: ({ parent }) => parent, onDone: { stay: true } } + } + } + }) + const Child = Machine.child("child", childDef) + + const parentDef = Machine.make({ + id: "ClusterParent", + root: Machine.state({ states: { Idle: {}, Probing: { fields: { count: Schema.Number } } } }), + events: ParentEvents, + children: { child: Child }, + effects: { + probe: ({ children, self }: { + readonly self: Machine.MachineTarget + readonly children: Machine.ChildOwner + }) => + Effect.gen(function*() { + const targetErr = yield* Effect.flip( + Ledger.target("ledger-1").send({ _tag: "Add", amount: "bad" } as never) + ) + const selfErr = yield* Effect.flip(self.send({ _tag: "Notify", n: "bad" } as never)) + const childOwnerErr = yield* Effect.flip(children.sendTo(Child, { _tag: "Bump", n: "bad" } as never)) + const sendToErr = yield* Effect.flip(Machine.sendTo(Child, { _tag: "Bump", n: "bad" } as never)) + recorded.push(["target", targetErr], ["self", selfErr], ["children.sendTo", childOwnerErr], [ + "Machine.sendTo", + sendToErr + ]) + // Valid send after rejections still works. + yield* Ledger.target("ledger-1").send({ _tag: "Add", amount: 3 }) + yield* Machine.sendTo(Child, { _tag: "Bump", n: 4 }) + }).pipe(Effect.orDie) + } + }).handle({ + initial: { target: "Idle" }, + states: { + Idle: { on: { Probe: { target: "Probing", data: { count: 0 } } } }, + Probing: { + on: { Notify: { target: "Probing", data: ({ event, state }) => ({ count: state.count + event.n }) } }, + invoke: [ + { src: "child" }, + { src: "probe", input: ({ children, self }) => ({ self, children }), onDone: { stay: true } } + ] + } + } + }) + const Parent = ClusterMachine.make("ClusterParent", parentDef, { version: "1" }) + + const storage = makeTestStorage() + const messages = yield* makeMessages + yield* TestClock.adjust("1 second") + const scope = yield* Scope.fork(yield* Effect.scope) + const context = yield* Layer.mergeAll(Parent.toLayer(), Ledger.toLayer()).pipe( + Layer.provide(Layer.succeed(ClusterMachine.Storage, storage.service)), + Layer.provideMerge(Sharding.layer), + Layer.provide(Runners.layerNoop), + Layer.provide(Layer.succeed(MessageStorage.MessageStorage, messages.storage)), + Layer.provide(RunnerStorage.layerMemory), + Layer.provide(RunnerHealth.layerNoop), + Layer.provide(config()), + Layer.buildWithScope(scope) + ) + yield* TestClock.adjust(1) + const parents = (yield* Effect.provideContext(Parent.client, context))("parent-1") + yield* parents.send({ _tag: "Probe" }) + yield* settle + + assert.strictEqual(recorded.length, 5) + for (const [, error] of recorded as Array<[string, unknown]>) { + assert.instanceOf(error, Machine.MachineSchemaDecodeError) + } + // Receivers kept running and processed valid events. + yield* parents.send({ _tag: "Notify", n: 2 }) + yield* settle + assert.deepStrictEqual(totalOf(storage, "ledger-1"), { _tag: "Open", total: 3 }) + const parentEntry = storage.entries.get(storageKey("ClusterParent", "parent-1")) + assert.strictEqual(parentEntry?.status._tag, "Active") + assert.deepStrictEqual(parentEntry?.snapshot.active.at(-1)?.value, { _tag: "Probing", count: 2 }) + }).pipe(Effect.scoped)) + for (const dialect of dialects) { it.effect(`roll back what a step sends with its checkpoint, on ${dialect.name}`, () => { let failing = true diff --git a/packages/effect-machine/typetest/machine/InvocationSupport.tst.ts b/packages/effect-machine/typetest/machine/InvocationSupport.tst.ts index 6c38e2fd..822a22c6 100644 --- a/packages/effect-machine/typetest/machine/InvocationSupport.tst.ts +++ b/packages/effect-machine/typetest/machine/InvocationSupport.tst.ts @@ -359,7 +359,7 @@ describe("ClusterMachine", () => { it("runs work that acts on the child machine of its state, and refuses work on a child address", () => { const Quiet = Machine.child("quiet", quiet) expect(Machine.sendTo(Quiet, { _tag: "Start" })).type.toBe< - Effect.Effect + Effect.Effect >() expect(Machine.stopChild(Quiet)).type.toBe>() expect(Machine.stopChild(address)).type.toBe>() diff --git a/packages/effect-machine/typetest/machine/LocalMachine.tst.ts b/packages/effect-machine/typetest/machine/LocalMachine.tst.ts index c37fb7d8..b6467e5a 100644 --- a/packages/effect-machine/typetest/machine/LocalMachine.tst.ts +++ b/packages/effect-machine/typetest/machine/LocalMachine.tst.ts @@ -105,7 +105,9 @@ describe("MachineRuntime", () => { Machine.MachineRuntime | Database > >() - expect(Machine.sendTo(Address, 1)).type.toBe>() + expect(Machine.sendTo(Address, 1)).type.toBe< + Effect.Effect + >() expect(Machine.stopChild(Address)).type.toBe>() expect(Machine.sendTo).type.not.toBeCallableWith(Address, "1") }) diff --git a/scripts/fixtures/consumer/declarations.ts b/scripts/fixtures/consumer/declarations.ts index 5716a649..0b978cf2 100644 --- a/scripts/fixtures/consumer/declarations.ts +++ b/scripts/fixtures/consumer/declarations.ts @@ -17,7 +17,8 @@ export const sendInferred = (child: Machine.ChildAddress, event: number) export const sendAnnotated = ( child: Machine.ChildAddress, event: number -): Effect.Effect => Machine.sendTo(child, event) +): Effect.Effect => + Machine.sendTo(child, event) export const spawnInferred = Machine.spawn(Machine.logic({ initial: 0, run: () => Effect.never }), { id: "worker" }) From a576013b876f8a6231d21c678e9008eca30f3586 Mon Sep 17 00:00:00 2001 From: SandroMaglione Date: Sun, 29 Nov 2026 10:01:41 +1300 Subject: [PATCH 2/2] Eliminate closure overhead in childlessStep and processScope command delivery --- .../src/internal/machine/runtimeCompiled.ts | 47 ++++++++++--------- .../src/internal/machine/runtimeProtocol.ts | 24 ++++++++-- .../src/internal/machine/step.ts | 47 ++++++++++--------- .../src/internal/machine/stepHost.ts | 4 +- 4 files changed, 70 insertions(+), 52 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 0db06fc4..2343cb28 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -17,6 +17,7 @@ import * as Semaphore from "effect/Semaphore" import * as Stream from "effect/Stream" import type * as Take from "effect/Take" import type { Inspection } from "../../LocalMachine.js" +import type { MachineTarget } from "../../Machine.js" import { type ChildSelector } from "./childRegistry.js" import { MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" @@ -37,6 +38,7 @@ import { decodeSent, type Deliverable, deliverEvent, + deliverFromProcess, deliverMachineTarget, type EmissionRuntime, EmissionsClosed, @@ -129,6 +131,12 @@ class CompiledAddress implements ProcessEndpoint, Deliverable { ): Effect.Effect { return this.process.deliver(event, source, causedBy) } + [deliverFromProcess]( + target: MachineTarget | ChildSelector, + event: unknown + ): Effect.Effect { + return this.process.deliverTo(target, event) + } } /** @@ -346,17 +354,6 @@ abstract class LocalProcess implements MachineRef { this.inspectionSubject, this.causation() ), - deliverTo: (target, event) => - isMachineTarget(target) - ? this.inspector === undefined - ? deliverMachineTarget(target, event, undefined, undefined) - : deliverMachineTarget(target, event, this.inspectionSubject, this.causation()) - : this.childRuntime.deliverTo( - target, - event, - this.inspectionSubject, - this.causation() - ), stopChild: this.childRuntime.stop, failCause: (cause: Cause.Cause) => this.failCause(cause), inspectInitial: this.inspector === undefined @@ -423,17 +420,6 @@ abstract class LocalProcess implements MachineRef { self.inspectionSubject, self.causation() ), - deliverTo: (target, event) => - isMachineTarget(target) - ? self.inspector === undefined - ? deliverMachineTarget(target, event, undefined, undefined) - : deliverMachineTarget(target, event, self.inspectionSubject, self.causation()) - : self.childRuntime.deliverTo( - target, - event, - self.inspectionSubject, - self.causation() - ), stopChild: self.childRuntime.stop, failCause: (cause: Cause.Cause) => self.failCause(cause), inspectInitial: self.inspector === undefined @@ -615,6 +601,23 @@ abstract class LocalProcess implements MachineRef { }) } + /** Delivers a transition command from this process to a target or child. */ + deliverTo( + target: MachineTarget | ChildSelector, + event: unknown + ): Effect.Effect { + return isMachineTarget(target) + ? this.inspector === undefined + ? deliverMachineTarget(target, event, undefined, undefined) + : deliverMachineTarget(target, event, this.inspectionSubject, this.causation()) + : this.childRuntime.deliverTo( + target, + event, + this.inspectionSubject, + this.causation() + ) + } + /** A transition-command or internal-work delivery. */ deliver( event: unknown, diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index f2be62b6..8f59093b 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -73,6 +73,9 @@ export const isSnapshotObservable = (value: unknown): value is SnapshotObservabl */ export const deliverEvent: unique symbol = Symbol.for("effect/Machine/deliverEvent") +/** @internal */ +export const deliverFromProcess: unique symbol = Symbol.for("effect/Machine/deliverFromProcess") + /** @internal */ export interface Deliverable { readonly [deliverEvent]: ( @@ -294,6 +297,10 @@ export interface ProcessEndpoint { causedBy: Inspection.Causation | undefined ) => Effect.Effect readonly [deliverEvent]?: Deliverable[typeof deliverEvent] + readonly [deliverFromProcess]?: ( + target: MachineTarget | ChildSelector, + event: unknown + ) => Effect.Effect readonly [acknowledgedSend]?: | ((event: Event) => Effect.Effect, unknown | StoppedError>) | undefined @@ -359,6 +366,18 @@ const deliverToChild = ( ? sendMachineTarget(ref, event, source, causedBy) as Effect.Effect : ref[deliverEvent](event, source, causedBy) +/** Delivers a transition command from a running local process to a target or child. */ +export const deliverFromScope = ( + scope: ProcessInitialContext, + target: MachineTarget | ChildSelector, + event: unknown +): Effect.Effect => + scope.self[deliverFromProcess] !== undefined + ? scope.self[deliverFromProcess](target, event) + : isMachineTarget(target) + ? deliverMachineTarget(target, event, scope.self.inspectionSubject, undefined) + : scope.sendTo(target, event) + export interface ProcessInitialContext { readonly self: ProcessEndpoint readonly parent: ProcessEndpoint | undefined @@ -375,11 +394,6 @@ export interface ProcessInitialContext { ): Effect.Effect (child: ChildSelector, event: unknown): Effect.Effect } - /** Delivers a transition command to a target or child without caller-side schema rejection. */ - readonly deliverTo: ( - target: MachineTarget | ChildSelector, - event: unknown - ) => Effect.Effect readonly stopChild: (child: ChildSelector) => Effect.Effect /** @internal */ readonly failCause: (cause: Cause.Cause) => Effect.Effect diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index d322cd65..5b65c53d 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -786,6 +786,30 @@ class WorkOf { const unchanged = (state: State): Step => new Step(state, undefined, empty, empty, empty, empty, empty) +/** Builds the step of a childless machine for a planned macrostep. */ +const childlessStep = ( + state: State, + planned: ExecutionPlan.ExecutionMacrostep, + commands: ReadonlyArray +): Step => + new Step( + new State( + state.planning, + planned.next, + undefined, + undefined, + empty, + state.runs, + planned.done ? Exit.succeed(planned.output) : undefined + ), + planned.event, + planned.microsteps, + planned.emittedEvents, + commands, + empty, + empty + ) + /** A planning throw: typed for the planner's own errors, a defect otherwise. */ const exitOfThrow = (error: unknown): Exit.Exit => isPlanningError(error) ? Exit.fail(error) : Exit.die(error) @@ -1080,29 +1104,6 @@ const build = ( ) } - /** Builds the step of a childless machine for a planned macrostep. */ - const childlessStep = ( - state: State, - planned: ExecutionPlan.ExecutionMacrostep, - commands: ReadonlyArray - ): Step => - planned.done - ? ended( - reached(state.planning, planned.next, undefined, undefined, state.runs), - empty, - Exit.succeed(planned.output), - { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } - ) - : new Step( - new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), - planned.event, - planned.microsteps, - planned.emittedEvents, - commands, - empty, - empty - ) - /** * Plans one event on a state that runs `running`: a public event that `send` * decoded, or the invocation event of a result. diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index 7cd2bf4d..736d9622 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -101,9 +101,9 @@ const runCommands = (commands: ReadonlyArray, scope: Scope): Effec Effect.forEach(commands, (command) => { switch (command._tag) { case "Send": - return scope.deliverTo(command.target, command.event) + return Runtime.deliverFromScope(scope, command.target, command.event) case "SendToChild": - return scope.deliverTo(command.child, command.event) + return Runtime.deliverFromScope(scope, command.child, command.event) case "StopChild": return scope.stopChild(command.child) }