@typeonce/effect-machine 0.41.1 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -4
- package/dist/Machine.d.ts +159 -27
- package/dist/Machine.d.ts.map +1 -1
- package/dist/Machine.js +20 -6
- package/dist/Machine.js.map +1 -1
- package/dist/internal/machine/atom.d.ts +3 -7
- package/dist/internal/machine/atom.d.ts.map +1 -1
- package/dist/internal/machine/atom.js +153 -87
- package/dist/internal/machine/atom.js.map +1 -1
- package/dist/internal/machine/childRegistry.d.ts +7 -0
- package/dist/internal/machine/childRegistry.d.ts.map +1 -1
- package/dist/internal/machine/childRegistry.js +7 -0
- package/dist/internal/machine/childRegistry.js.map +1 -1
- package/dist/internal/machine/invocation.d.ts.map +1 -1
- package/dist/internal/machine/invocation.js +13 -2
- package/dist/internal/machine/invocation.js.map +1 -1
- package/dist/internal/machine/invocationDefinition.d.ts +7 -0
- package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
- package/dist/internal/machine/invocationDefinition.js +16 -0
- package/dist/internal/machine/invocationDefinition.js.map +1 -1
- package/dist/internal/machine/machine.d.ts.map +1 -1
- package/dist/internal/machine/machine.js +69 -6
- package/dist/internal/machine/machine.js.map +1 -1
- package/dist/internal/machine/plannedSnapshot.d.ts +30 -0
- package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -0
- package/dist/internal/machine/plannedSnapshot.js +103 -0
- package/dist/internal/machine/plannedSnapshot.js.map +1 -0
- package/dist/internal/machine/planner.d.ts +5 -0
- package/dist/internal/machine/planner.d.ts.map +1 -1
- package/dist/internal/machine/planner.js +1 -1
- package/dist/internal/machine/planner.js.map +1 -1
- package/dist/internal/machine/runtime.d.ts +5 -4
- package/dist/internal/machine/runtime.d.ts.map +1 -1
- package/dist/internal/machine/runtime.js +60 -15
- package/dist/internal/machine/runtime.js.map +1 -1
- package/dist/internal/machine/runtimeCompiled.js +2 -2
- package/dist/internal/machine/runtimeCompiled.js.map +1 -1
- package/dist/internal/machine/runtimeGeneric.js +1 -1
- package/dist/internal/machine/runtimeGeneric.js.map +1 -1
- package/dist/internal/machine/runtimeProtocol.d.ts +2 -1
- package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
- package/dist/internal/machine/runtimeProtocol.js +2 -2
- package/dist/internal/machine/runtimeProtocol.js.map +1 -1
- package/dist/testing/MachineTest.d.ts +2 -2
- package/dist/testing/MachineTest.js +2 -2
- package/dist/unstable/reactivity/AtomMachine.d.ts +95 -19
- package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.js +13 -7
- package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
- package/docs/agent-guide.md +28 -5
- package/docs/effect-atom-react.md +262 -14
- package/docs/machine-review.md +18 -4
- package/package.json +1 -1
- package/src/Machine.ts +229 -32
- package/src/internal/machine/atom.ts +305 -113
- package/src/internal/machine/childRegistry.ts +9 -0
- package/src/internal/machine/invocation.ts +17 -2
- package/src/internal/machine/invocationDefinition.ts +19 -0
- package/src/internal/machine/machine.ts +65 -2
- package/src/internal/machine/plannedSnapshot.ts +113 -0
- package/src/internal/machine/planner.ts +1 -1
- package/src/internal/machine/runtime.ts +101 -28
- package/src/internal/machine/runtimeCompiled.ts +2 -2
- package/src/internal/machine/runtimeGeneric.ts +1 -1
- package/src/internal/machine/runtimeProtocol.ts +4 -2
- package/src/testing/MachineTest.ts +2 -2
- package/src/unstable/reactivity/AtomMachine.ts +104 -20
|
@@ -8,8 +8,9 @@ import * as Cause from "effect/Cause"
|
|
|
8
8
|
import * as Effect from "effect/Effect"
|
|
9
9
|
import * as Stream from "effect/Stream"
|
|
10
10
|
import type { ChildMachine, ChildOwner, Inspection, Logic, Machine } from "../../Machine.js"
|
|
11
|
+
import * as ChildRegistry from "./childRegistry.js"
|
|
11
12
|
import * as Configuration from "./configuration.js"
|
|
12
|
-
import { InfiniteTransitionError, MachineSchemaDecodeError, StoppedError } from "./errors.js"
|
|
13
|
+
import { ChildAlreadyExistsError, InfiniteTransitionError, MachineSchemaDecodeError, StoppedError } from "./errors.js"
|
|
13
14
|
import * as InvocationDefinition from "./invocationDefinition.js"
|
|
14
15
|
import * as InvocationEvent from "./invocationEvent.js"
|
|
15
16
|
import * as Planner from "./planner.js"
|
|
@@ -33,7 +34,8 @@ export interface AnyConfig {
|
|
|
33
34
|
export const makeKey = (path: string, id: string): string => `${path.length}:${path}${id}`
|
|
34
35
|
|
|
35
36
|
/** @internal */
|
|
36
|
-
export const makeChildId = (path: string, id: string): string =>
|
|
37
|
+
export const makeChildId = (path: string, id: string): string =>
|
|
38
|
+
`${ChildRegistry.invocationChildIdPrefix}${makeKey(path, id)}`
|
|
37
39
|
|
|
38
40
|
const oneShot = (effect: Effect.Effect<any, any, any>): Logic<void, never, any, any, any> => ({
|
|
39
41
|
initial: () => Effect.void,
|
|
@@ -272,6 +274,15 @@ const startResolved = (
|
|
|
272
274
|
})
|
|
273
275
|
})
|
|
274
276
|
|
|
277
|
+
// Logic addresses and child descriptor ids are caller-chosen. Keep them out of
|
|
278
|
+
// the namespace reserved for runtime-owned invocation ids; runtime-owned ids
|
|
279
|
+
// skip this check.
|
|
280
|
+
const reservedChildIdFailure = (
|
|
281
|
+
childId: string,
|
|
282
|
+
invokeId: string
|
|
283
|
+
): Effect.Effect<never, ChildAlreadyExistsError> | undefined =>
|
|
284
|
+
ChildRegistry.isReservedChildId(childId) ? Effect.fail(new ChildAlreadyExistsError({ id: invokeId })) : undefined
|
|
285
|
+
|
|
275
286
|
const start = (
|
|
276
287
|
scope: Runtime.ProcessScope<any>,
|
|
277
288
|
ownedChildren: Runtime.OwnedChildRuntime,
|
|
@@ -279,6 +290,8 @@ const start = (
|
|
|
279
290
|
config: AnyConfig
|
|
280
291
|
): Effect.Effect<void, any, any> => {
|
|
281
292
|
const invokeId = String(config.id)
|
|
293
|
+
const reserved = config.address === undefined ? undefined : reservedChildIdFailure(String(config.address), invokeId)
|
|
294
|
+
if (reserved !== undefined) return reserved
|
|
282
295
|
return startResolved(
|
|
283
296
|
scope,
|
|
284
297
|
ownedChildren,
|
|
@@ -305,6 +318,8 @@ const startStaticChild = (
|
|
|
305
318
|
// source function so each running parent does not retain a resolved config
|
|
306
319
|
// object and an otherwise redundant source closure.
|
|
307
320
|
const descriptor = raw.child
|
|
321
|
+
const reserved = reservedChildIdFailure(descriptor.id, descriptor.id)
|
|
322
|
+
if (reserved !== undefined) return reserved
|
|
308
323
|
return startResolved(
|
|
309
324
|
scope,
|
|
310
325
|
ownedChildren,
|
|
@@ -44,6 +44,25 @@ export const capture = (config: Record<PropertyKey, unknown>, path: string): Inv
|
|
|
44
44
|
return Object.freeze(config) as unknown as InvocationDefinition
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/** Lifecycle id that routes an invocation's outcomes within its owning state. */
|
|
48
|
+
export const lifecycleId = (definition: InvocationDefinition): string =>
|
|
49
|
+
"child" in definition ? definition.child.id : definition.id
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Rejects one state's invocations when two share a lifecycle id. Distinct ids
|
|
53
|
+
* keep runtime-owned invocation child ids collision-free.
|
|
54
|
+
*/
|
|
55
|
+
export const assertDistinctIds = (definitions: ReadonlyArray<InvocationDefinition>, path: string): void => {
|
|
56
|
+
const seen = new Set<string>()
|
|
57
|
+
for (const definition of definitions) {
|
|
58
|
+
const id = lifecycleId(definition)
|
|
59
|
+
if (seen.has(id)) {
|
|
60
|
+
throw new Error(`Machine invocations for state "${path}" must have distinct ids; "${id}" is declared twice`)
|
|
61
|
+
}
|
|
62
|
+
seen.add(id)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
47
66
|
/** Only captured state handlers cross this erased boundary. */
|
|
48
67
|
export const definitions = (invoke: unknown): ReadonlyArray<InvocationDefinition> =>
|
|
49
68
|
invoke === undefined
|
|
@@ -163,7 +163,8 @@ const captureDefinitionBranch = (
|
|
|
163
163
|
if (selection.updatePath !== undefined) {
|
|
164
164
|
const owner = stateNodes.byPath.get(selection.updatePath)
|
|
165
165
|
if (
|
|
166
|
-
selection.kind !== "state"
|
|
166
|
+
(selection.kind !== "state" && selection.kind !== "choice") ||
|
|
167
|
+
(selection.scope !== "local" && selection.scope !== "branch") ||
|
|
167
168
|
selection.path === undefined || owner === undefined || owner.schema === undefined ||
|
|
168
169
|
(owner.type !== "compound" && owner.type !== "parallel") ||
|
|
169
170
|
!Configuration.isDescendantOf(path, owner.path) ||
|
|
@@ -296,6 +297,15 @@ const constructBranch = (
|
|
|
296
297
|
source?: string
|
|
297
298
|
): unknown => {
|
|
298
299
|
const config = Construction.record(raw)
|
|
300
|
+
if (selection.kind === "choice" && selection.updatePath !== undefined) {
|
|
301
|
+
const { update, ...state } = config
|
|
302
|
+
if (Reflect.ownKeys(state).length > 0) throw new Error("Machine pseudo-state construction accepts no data")
|
|
303
|
+
const node = stateNodes.byPath.get(selection.path!)!
|
|
304
|
+
return Topology.makeCombinedTarget(
|
|
305
|
+
Topology.makeChoiceTarget(node.path, node.parent!),
|
|
306
|
+
Construction.update(stateNodes, selection.updatePath, update)
|
|
307
|
+
)
|
|
308
|
+
}
|
|
299
309
|
if (selection.kind === "none" || selection.kind === "history" || selection.kind === "choice") {
|
|
300
310
|
if (Reflect.ownKeys(config).length > 0) throw new Error("Machine pseudo-state construction accepts no data")
|
|
301
311
|
if (selection.kind === "none") return undefined
|
|
@@ -475,6 +485,8 @@ const normalizeObjectTransition = (
|
|
|
475
485
|
...(hasData ? { data: value } : {}),
|
|
476
486
|
...(config.decoded === undefined ? {} : { decoded: config.decoded })
|
|
477
487
|
}
|
|
488
|
+
: selection.kind === "choice"
|
|
489
|
+
? { update: { data: value, decoded: config.decoded } }
|
|
478
490
|
: {
|
|
479
491
|
...(value.target === undefined ? {} : { data: value.target, decoded: config.decoded }),
|
|
480
492
|
update: { data: value.update, decoded: config.decoded }
|
|
@@ -632,6 +644,7 @@ const captureInvokeDefinition = (
|
|
|
632
644
|
}
|
|
633
645
|
return InvocationDefinition.capture(captured, path)
|
|
634
646
|
})
|
|
647
|
+
InvocationDefinition.assertDistinctIds(capturedDefinitions, path)
|
|
635
648
|
if (Array.isArray(invoke)) return Object.freeze(capturedDefinitions)
|
|
636
649
|
return capturedDefinitions[0]
|
|
637
650
|
}
|
|
@@ -704,6 +717,54 @@ const flattenHandlers = (
|
|
|
704
717
|
}
|
|
705
718
|
}
|
|
706
719
|
|
|
720
|
+
const publicPath = (path: string): string => path === "" ? Declaration.rootPathName : path
|
|
721
|
+
|
|
722
|
+
// A choice entered with an owner update resolves after that update, so every
|
|
723
|
+
// branch it can reach, through nested choices, must keep the owner active.
|
|
724
|
+
const assertChoiceUpdatesRetainOwners = (machine: Machine.Any): void => {
|
|
725
|
+
let hasChoice = false
|
|
726
|
+
for (const node of machine.stateNodes.byPath.values()) {
|
|
727
|
+
if (node.type === "choice") {
|
|
728
|
+
hasChoice = true
|
|
729
|
+
break
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
if (!hasChoice) return
|
|
733
|
+
const definitions = Topology.transitionDefinitions(machine)
|
|
734
|
+
const choices = new Map<string, Machine.TransitionDefinition>()
|
|
735
|
+
for (const definition of definitions) {
|
|
736
|
+
if (definition.trigger.type === "choice") choices.set(definition.source, definition)
|
|
737
|
+
}
|
|
738
|
+
for (const definition of definitions) {
|
|
739
|
+
for (const branch of definition.branches) {
|
|
740
|
+
const owner = branch.updates[0]
|
|
741
|
+
const entered = branch.selection.path
|
|
742
|
+
if (branch.selection.kind !== "choice" || owner === undefined || entered === undefined) continue
|
|
743
|
+
const pending = [entered]
|
|
744
|
+
const visited = new Set<string>()
|
|
745
|
+
while (pending.length > 0) {
|
|
746
|
+
const choice = pending.shift()!
|
|
747
|
+
if (visited.has(choice)) continue
|
|
748
|
+
visited.add(choice)
|
|
749
|
+
for (const choiceBranch of choices.get(choice)?.branches ?? []) {
|
|
750
|
+
const { kind, path: target } = choiceBranch.selection
|
|
751
|
+
// Targetless and update-only choice branches are rejected by choice validation itself.
|
|
752
|
+
if (target === undefined || kind === "none" || kind === "update") continue
|
|
753
|
+
if (kind === "choice") {
|
|
754
|
+
pending.push(target)
|
|
755
|
+
} else if (!Configuration.isDescendantOf(target, owner)) {
|
|
756
|
+
const label = choiceBranch.type === "branch" ? `branch "${choiceBranch.key}"` : "transition"
|
|
757
|
+
throw new Error(
|
|
758
|
+
`Machine transition from "${publicPath(definition.source)}" updates "${publicPath(owner)}" before ` +
|
|
759
|
+
`choice "${choice}", whose ${label} targets "${publicPath(target)}" outside that owner`
|
|
760
|
+
)
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
707
768
|
const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration): Definition.Any["handle"] =>
|
|
708
769
|
((config: Record<string, unknown>) => {
|
|
709
770
|
const captured = InitialDeclaration.capture(declaration.root, config)
|
|
@@ -733,7 +794,9 @@ const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration):
|
|
|
733
794
|
compiled.input === undefined ? undefined : Protocol.decodeInputSync(compiled, compiled.input, input)
|
|
734
795
|
)
|
|
735
796
|
}, { "": captured.handlers })
|
|
736
|
-
|
|
797
|
+
const machine = makeWithHandlers(compiled, handlers)
|
|
798
|
+
assertChoiceUpdatesRetainOwners(machine)
|
|
799
|
+
return machine
|
|
737
800
|
}) as Definition.Any["handle"]
|
|
738
801
|
|
|
739
802
|
export const isMachine = (
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Startup snapshots planned without running a machine.
|
|
3
|
+
*
|
|
4
|
+
* Server reads of atom bridges render these snapshots instead of starting the
|
|
5
|
+
* runtime. Every function here is synchronous, executes no machine command and
|
|
6
|
+
* reports a plan that cannot be produced synchronously as `undefined`.
|
|
7
|
+
*
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as Effect from "effect/Effect"
|
|
12
|
+
import * as Option from "effect/Option"
|
|
13
|
+
import type { ChildMachine, ChildOwner, Machine, RuntimeSnapshot } from "../../Machine.js"
|
|
14
|
+
import * as Configuration from "./configuration.js"
|
|
15
|
+
import { StoppedError } from "./errors.js"
|
|
16
|
+
import * as InvocationDefinition from "./invocationDefinition.js"
|
|
17
|
+
import * as Planner from "./planner.js"
|
|
18
|
+
import * as Serialization from "./serialization.js"
|
|
19
|
+
|
|
20
|
+
/** A machine paired with the runtime snapshot it is planned to start with. */
|
|
21
|
+
export interface PlannedSnapshot {
|
|
22
|
+
readonly machine: Machine.Any
|
|
23
|
+
readonly snapshot: RuntimeSnapshot<Machine.Snapshot<any>, never, unknown>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Plans the snapshot a fresh start settles into, following the generic
|
|
28
|
+
* planner. Startup commands are planned and discarded.
|
|
29
|
+
*/
|
|
30
|
+
export const planStart = (machine: Machine.Any, args: ReadonlyArray<unknown>): PlannedSnapshot | undefined => {
|
|
31
|
+
try {
|
|
32
|
+
const planned = Planner.planInitialSync(machine, ...args)
|
|
33
|
+
return {
|
|
34
|
+
machine,
|
|
35
|
+
snapshot: planned.done
|
|
36
|
+
? { status: "done", state: planned.state, output: planned.output }
|
|
37
|
+
: { status: "active", state: planned.state }
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Plans the snapshot a resumed machine starts from. */
|
|
45
|
+
export const planResume = (machine: Machine.Any, snapshot: Machine.Snapshot<any>): PlannedSnapshot | undefined => {
|
|
46
|
+
try {
|
|
47
|
+
const normalized = Effect.runSyncExit(Serialization.normalizeSnapshotEffect(machine, snapshot))
|
|
48
|
+
if (normalized._tag === "Failure") return undefined
|
|
49
|
+
const state = normalized.value
|
|
50
|
+
if (!Planner.isFinalState(machine, state)) {
|
|
51
|
+
return { machine, snapshot: { status: "active", state } }
|
|
52
|
+
}
|
|
53
|
+
const output = Effect.runSyncExit(Planner.getFinalOutputEffect(machine, state, Planner.InitialEvent))
|
|
54
|
+
return output._tag === "Success"
|
|
55
|
+
? { machine, snapshot: { status: "done", state, output: output.value } }
|
|
56
|
+
: undefined
|
|
57
|
+
} catch {
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Input mappers are synchronous. Child operations they capture only run inside
|
|
63
|
+
// a live runtime, so a planned read exposes an owner that refuses them.
|
|
64
|
+
const unavailableChildren: ChildOwner<unknown> = {
|
|
65
|
+
spawn: () => Effect.die(new Error("Child operations are unavailable in a planned snapshot")),
|
|
66
|
+
sendTo: () => Effect.fail(new StoppedError()),
|
|
67
|
+
stop: () => Effect.void
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Plans the start of a fixed child descriptor invoked by the parent's planned
|
|
72
|
+
* configuration, mirroring the runtime's initial invocation order and entry
|
|
73
|
+
* context. `Option.none()` means the planned parent does not invoke it.
|
|
74
|
+
*/
|
|
75
|
+
export const planInvokedChild = (
|
|
76
|
+
parent: PlannedSnapshot,
|
|
77
|
+
descriptor: ChildMachine.Any
|
|
78
|
+
): Option.Option<PlannedSnapshot> | undefined => {
|
|
79
|
+
if (parent.snapshot.status !== "active") return Option.none()
|
|
80
|
+
try {
|
|
81
|
+
const machine = parent.machine
|
|
82
|
+
const configuration = Configuration.normalizeConfigurationSync(machine, parent.snapshot.state)
|
|
83
|
+
for (const path of Configuration.getInitialEntryPaths(machine, configuration)) {
|
|
84
|
+
const handlers = Configuration.getStateConfigByPath(machine, path)
|
|
85
|
+
for (const definition of InvocationDefinition.definitions(handlers?.invoke)) {
|
|
86
|
+
if (
|
|
87
|
+
!("child" in definition) || definition.child.id !== descriptor.id ||
|
|
88
|
+
definition.child.machine !== descriptor.machine
|
|
89
|
+
) continue
|
|
90
|
+
const child = descriptor.machine
|
|
91
|
+
let input: unknown = undefined
|
|
92
|
+
if ("input" in definition) {
|
|
93
|
+
input = typeof definition.input === "function"
|
|
94
|
+
? definition.input({
|
|
95
|
+
...(Configuration.getMachineReferences(configuration) ??
|
|
96
|
+
Planner.resolveMachineReferences(machine, configuration)),
|
|
97
|
+
children: unavailableChildren,
|
|
98
|
+
state: configuration.values.get(path),
|
|
99
|
+
containingState: Configuration.getParentValue(machine, configuration, path),
|
|
100
|
+
ancestors: Configuration.getParentValues(machine, configuration, path),
|
|
101
|
+
event: Planner.InitialEvent
|
|
102
|
+
})
|
|
103
|
+
: definition.input
|
|
104
|
+
}
|
|
105
|
+
const planned = planStart(child, child.input === undefined ? [] : [input])
|
|
106
|
+
return planned === undefined ? undefined : Option.some(planned)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return Option.none()
|
|
110
|
+
} catch {
|
|
111
|
+
return undefined
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -150,7 +150,7 @@ export const withMachineReferences = (
|
|
|
150
150
|
return scoped
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
const resolveMachineReferences = (
|
|
153
|
+
export const resolveMachineReferences = (
|
|
154
154
|
machine: Machine.Any,
|
|
155
155
|
configuration: ActiveConfiguration
|
|
156
156
|
): BehaviorMachineReferences => {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import * as Deferred from "effect/Deferred"
|
|
4
4
|
import * as Effect from "effect/Effect"
|
|
5
|
+
import * as Scope from "effect/Scope"
|
|
5
6
|
import * as Stream from "effect/Stream"
|
|
6
7
|
import * as InspectionRuntime from "./inspectionRuntime.js"
|
|
7
8
|
import { startCompactCompiledInternal, startCompiledSync } from "./runtimeCompiled.js"
|
|
@@ -28,6 +29,66 @@ const makeRuntime = makeProcessRuntime(startLogicInternal, startCompiledSync)
|
|
|
28
29
|
|
|
29
30
|
export type ProcessRuntimeStrategy = "generic" | "compiled" | "auto"
|
|
30
31
|
|
|
32
|
+
// A root machine is owned by the Scope that starts it, like `Effect.forkScoped`.
|
|
33
|
+
// Each owning Scope carries one ownership record with a single finalizer that
|
|
34
|
+
// stops the machines still alive, in reverse start order. The record's shared
|
|
35
|
+
// hooks register a machine when it is ready and release it synchronously when
|
|
36
|
+
// it terminates, so machines cost one set entry and long-lived scopes do not
|
|
37
|
+
// accumulate finalizers. Owned children keep their process-local ownership.
|
|
38
|
+
type OwnershipHooks = Pick<StartInternalOptions, "onReadySync" | "onStopSync">
|
|
39
|
+
|
|
40
|
+
interface ScopeOwnership {
|
|
41
|
+
readonly live: Set<MachineRef<any, any, any, any>>
|
|
42
|
+
readonly hooks: OwnershipHooks
|
|
43
|
+
closed: boolean
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const ownerships = new WeakMap<Scope.Scope, ScopeOwnership>()
|
|
47
|
+
|
|
48
|
+
const stopLive = (ownership: ScopeOwnership): Effect.Effect<void> =>
|
|
49
|
+
Effect.suspend(() => {
|
|
50
|
+
ownership.closed = true
|
|
51
|
+
const refs = Array.from(ownership.live).reverse()
|
|
52
|
+
ownership.live.clear()
|
|
53
|
+
return Effect.forEach(refs, (ref) => ref.stop, { discard: true })
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const makeOwnership = (): ScopeOwnership => {
|
|
57
|
+
const live = new Set<MachineRef<any, any, any, any>>()
|
|
58
|
+
const ownership: ScopeOwnership = {
|
|
59
|
+
live,
|
|
60
|
+
hooks: {
|
|
61
|
+
// Declining readiness makes the runtime stop the machine itself, which
|
|
62
|
+
// covers a Scope that closed before or while the machine started.
|
|
63
|
+
onReadySync: (ref) => {
|
|
64
|
+
if (ownership.closed) return false
|
|
65
|
+
live.add(ref)
|
|
66
|
+
return true
|
|
67
|
+
},
|
|
68
|
+
onStopSync: (ref) => {
|
|
69
|
+
live.delete(ref)
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
closed: false
|
|
73
|
+
}
|
|
74
|
+
return ownership
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const ownedByScope = <State, Event, Error, Output, Emitted, StartError, Requirements>(
|
|
78
|
+
start: (
|
|
79
|
+
hooks: OwnershipHooks
|
|
80
|
+
) => Effect.Effect<MachineRef<State, Event, Error, Output, Emitted>, StartError, Requirements>
|
|
81
|
+
): Effect.Effect<MachineRef<State, Event, Error, Output, Emitted>, StartError, Requirements | Scope.Scope> =>
|
|
82
|
+
Effect.flatMap(Effect.scope, (parent) => {
|
|
83
|
+
const existing = ownerships.get(parent)
|
|
84
|
+
if (existing !== undefined) return start(existing.hooks)
|
|
85
|
+
const ownership = makeOwnership()
|
|
86
|
+
ownerships.set(parent, ownership)
|
|
87
|
+
// A closed Scope runs the finalizer immediately, which marks the record
|
|
88
|
+
// closed so the machine started next stops right away.
|
|
89
|
+
return Effect.andThen(Scope.addFinalizer(parent, stopLive(ownership)), start(ownership.hooks))
|
|
90
|
+
})
|
|
91
|
+
|
|
31
92
|
const startProcessWithStrategy = Effect.fnUntraced(function*(
|
|
32
93
|
logic: ProcessLogic<any, any, any, any, any, any>,
|
|
33
94
|
strategy: ProcessRuntimeStrategy,
|
|
@@ -47,15 +108,15 @@ const startProcessWithStrategy = Effect.fnUntraced(function*(
|
|
|
47
108
|
runtime
|
|
48
109
|
}
|
|
49
110
|
if (strategy === "generic") {
|
|
50
|
-
return yield* startGenericInternal(logic, internalOptions)
|
|
111
|
+
return yield* ownedByScope((hooks) => startGenericInternal(logic, { ...internalOptions, ...hooks }))
|
|
51
112
|
}
|
|
52
113
|
if (strategy === "compiled") {
|
|
53
114
|
if (logic.execution?._tag !== "Compiled") {
|
|
54
115
|
return yield* Effect.die(new Error("Machine cannot force the compiled runtime for generic process logic"))
|
|
55
116
|
}
|
|
56
|
-
return yield* startCompactCompiledInternal(logic, internalOptions)
|
|
117
|
+
return yield* ownedByScope((hooks) => startCompactCompiledInternal(logic, { ...internalOptions, ...hooks }))
|
|
57
118
|
}
|
|
58
|
-
return yield* startLogicInternal(logic, internalOptions)
|
|
119
|
+
return yield* ownedByScope((hooks) => startLogicInternal(logic, { ...internalOptions, ...hooks }))
|
|
59
120
|
})
|
|
60
121
|
|
|
61
122
|
/** @internal Test-only startup strategy selection. */
|
|
@@ -75,7 +136,7 @@ export const startProcessWithStrategyForTesting = <
|
|
|
75
136
|
): Effect.Effect<
|
|
76
137
|
MachineRef<State, Event, Error, Output>,
|
|
77
138
|
InitialError,
|
|
78
|
-
Requirements
|
|
139
|
+
Requirements | Scope.Scope
|
|
79
140
|
> => startProcessWithStrategy(logic, strategy, options) as any
|
|
80
141
|
|
|
81
142
|
export const startProcess: <
|
|
@@ -93,7 +154,7 @@ export const startProcess: <
|
|
|
93
154
|
) => Effect.Effect<
|
|
94
155
|
MachineRef<State, Event, Error, Output>,
|
|
95
156
|
InitialError,
|
|
96
|
-
Requirements
|
|
157
|
+
Requirements | Scope.Scope
|
|
97
158
|
> = Effect.fnUntraced(function*<State, Event, Error, Requirements, Output, InitialError>(
|
|
98
159
|
logic: ProcessLogic<State, Event, Error, Requirements, Output, InitialError>,
|
|
99
160
|
options?: {
|
|
@@ -101,18 +162,22 @@ export const startProcess: <
|
|
|
101
162
|
}
|
|
102
163
|
) {
|
|
103
164
|
const runtime = yield* makeRuntime
|
|
104
|
-
return yield*
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
165
|
+
return yield* ownedByScope((hooks) =>
|
|
166
|
+
startLogicInternal(
|
|
167
|
+
logic,
|
|
168
|
+
options === undefined
|
|
169
|
+
? {
|
|
170
|
+
detached: true,
|
|
171
|
+
runtime,
|
|
172
|
+
...hooks
|
|
173
|
+
}
|
|
174
|
+
: {
|
|
175
|
+
...options,
|
|
176
|
+
detached: true,
|
|
177
|
+
runtime,
|
|
178
|
+
...hooks
|
|
179
|
+
}
|
|
180
|
+
)
|
|
116
181
|
)
|
|
117
182
|
})
|
|
118
183
|
|
|
@@ -155,17 +220,25 @@ const prepareProcessWithStrategy = Effect.fnUntraced(function*<
|
|
|
155
220
|
inspectionRoot: true,
|
|
156
221
|
origin: { _tag: "Root" }
|
|
157
222
|
}
|
|
158
|
-
const initialize =
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
223
|
+
const initialize = (hooks: OwnershipHooks) => {
|
|
224
|
+
const startOptions = { ...internalOptions, ...hooks }
|
|
225
|
+
return strategy === "generic"
|
|
226
|
+
? startGenericInternal(logic, startOptions)
|
|
227
|
+
: strategy === "compiled"
|
|
228
|
+
? logic.execution?._tag === "Compiled"
|
|
229
|
+
? startCompactCompiledInternal(logic, startOptions)
|
|
230
|
+
: Effect.die(new Error("Machine cannot force the compiled runtime for generic process logic"))
|
|
231
|
+
: startLogicInternal(logic, startOptions)
|
|
232
|
+
}
|
|
233
|
+
// `start` is one-shot: the Scope that first evaluates it owns the machine.
|
|
165
234
|
const start = yield* Effect.cached(
|
|
166
|
-
initialize.pipe(
|
|
235
|
+
ownedByScope(initialize).pipe(
|
|
167
236
|
Effect.onExit((exit) => Deferred.done(started, exit))
|
|
168
|
-
) as Effect.Effect<
|
|
237
|
+
) as Effect.Effect<
|
|
238
|
+
MachineRef<State, Event, Error, Output, Emitted>,
|
|
239
|
+
InitialError,
|
|
240
|
+
Requirements | Scope.Scope
|
|
241
|
+
>
|
|
169
242
|
)
|
|
170
243
|
return {
|
|
171
244
|
id: options?.id ?? sessionId,
|
|
@@ -193,7 +266,7 @@ export const prepareProcess: <
|
|
|
193
266
|
readonly id?: string
|
|
194
267
|
}
|
|
195
268
|
) => Effect.Effect<
|
|
196
|
-
PreparedProcess<State, Event, Error, Output, Emitted, InitialError, Requirements>
|
|
269
|
+
PreparedProcess<State, Event, Error, Output, Emitted, InitialError, Requirements | Scope.Scope>
|
|
197
270
|
> =
|
|
198
271
|
((logic: ProcessLogic<any, any, any, any, any, any>, options?: { readonly id?: string }) =>
|
|
199
272
|
prepareProcessWithStrategy(logic, "auto", options)) as any
|
|
@@ -214,5 +287,5 @@ export const prepareProcessWithStrategyForTesting = <
|
|
|
214
287
|
readonly id?: string
|
|
215
288
|
}
|
|
216
289
|
): Effect.Effect<
|
|
217
|
-
PreparedProcess<State, Event, Error, Output, Emitted, InitialError, Requirements>
|
|
290
|
+
PreparedProcess<State, Event, Error, Output, Emitted, InitialError, Requirements | Scope.Scope>
|
|
218
291
|
> => prepareProcessWithStrategy(logic, strategy, options) as any
|
|
@@ -648,7 +648,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
|
|
|
648
648
|
if (this.compiledContext !== undefined) {
|
|
649
649
|
this.compiledContext.executionState = undefined
|
|
650
650
|
}
|
|
651
|
-
this.options.onStopSync?.()
|
|
651
|
+
this.options.onStopSync?.(this)
|
|
652
652
|
this.completion = CompiledStoppedCompletion
|
|
653
653
|
this.lifecycle = "Completed"
|
|
654
654
|
if (this.waiter !== undefined) {
|
|
@@ -816,7 +816,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
|
|
|
816
816
|
: Effect.void
|
|
817
817
|
),
|
|
818
818
|
Effect.andThen(Effect.sync(() => {
|
|
819
|
-
this.options.onStopSync?.()
|
|
819
|
+
this.options.onStopSync?.(this)
|
|
820
820
|
this.runState = "Idle"
|
|
821
821
|
this.worker = undefined
|
|
822
822
|
this.interruptRequested = false
|
|
@@ -192,7 +192,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
|
|
|
192
192
|
Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void)
|
|
193
193
|
)
|
|
194
194
|
}
|
|
195
|
-
const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(onStopSync)
|
|
195
|
+
const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(() => onStopSync(ref))
|
|
196
196
|
const currentCausation = inspector === undefined
|
|
197
197
|
? noCausation
|
|
198
198
|
: (): Inspection.Causation | undefined => messageCausation(inFlightMessage, initializing)
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
type ChildObserver,
|
|
25
25
|
type ChildRegistry,
|
|
26
26
|
type ChildSelector,
|
|
27
|
+
isReservedChildId,
|
|
27
28
|
matchesChild,
|
|
28
29
|
offerChildObservation,
|
|
29
30
|
registerChild,
|
|
@@ -628,7 +629,8 @@ export interface StartInternalOptions {
|
|
|
628
629
|
) => Effect.Effect<void>
|
|
629
630
|
readonly onReadySync?: (ref: MachineRef<any, any, any, any>) => boolean
|
|
630
631
|
readonly onStop?: Effect.Effect<void>
|
|
631
|
-
|
|
632
|
+
/** Runs synchronously once the process has terminated, with its reference. */
|
|
633
|
+
readonly onStopSync?: (ref: MachineRef<any, any, any, any>) => void
|
|
632
634
|
readonly skipStoppedOutcome?: boolean
|
|
633
635
|
readonly parent?: ProcessAddress<unknown>
|
|
634
636
|
readonly runtime: ProcessRuntime
|
|
@@ -1137,7 +1139,7 @@ export const makeChildRuntimeSync = (
|
|
|
1137
1139
|
if (registry.closed) {
|
|
1138
1140
|
return Effect.interrupt
|
|
1139
1141
|
}
|
|
1140
|
-
if (typeof key === "string" && registry.children.has(key)) {
|
|
1142
|
+
if (typeof key === "string" && (registry.children.has(key) || isReservedChildId(key))) {
|
|
1141
1143
|
return Effect.fail(new ChildAlreadyExistsError({ id: key }))
|
|
1142
1144
|
}
|
|
1143
1145
|
registry.scope ??= Scope.makeUnsafe("parallel")
|
|
@@ -511,10 +511,10 @@ export { ProbeUnavailableError } from "../internal/testing/machine/probe.js"
|
|
|
511
511
|
* Idle: {}
|
|
512
512
|
* }
|
|
513
513
|
* })
|
|
514
|
-
* const program = Effect.gen(function*() {
|
|
514
|
+
* const program = Effect.scoped(Effect.gen(function*() {
|
|
515
515
|
* const ref = yield* Machine.start(machine)
|
|
516
516
|
* return yield* MachineTest.probe(machine, ref)
|
|
517
|
-
* })
|
|
517
|
+
* }))
|
|
518
518
|
* ```
|
|
519
519
|
*
|
|
520
520
|
* @category runtime testing
|