@typeonce/effect-machine 0.33.0 → 0.35.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 +272 -628
- package/dist/Machine.d.ts +1076 -896
- package/dist/Machine.d.ts.map +1 -1
- package/dist/Machine.js +141 -90
- package/dist/Machine.js.map +1 -1
- package/dist/internal/machine/childRegistry.d.ts +1 -1
- package/dist/internal/machine/childRegistry.d.ts.map +1 -1
- package/dist/internal/machine/cluster.d.ts +2 -50
- package/dist/internal/machine/cluster.d.ts.map +1 -1
- package/dist/internal/machine/cluster.js +4 -27
- package/dist/internal/machine/cluster.js.map +1 -1
- package/dist/internal/machine/clusterProtocol.d.ts +35 -0
- package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
- package/dist/internal/machine/clusterProtocol.js +28 -0
- package/dist/internal/machine/clusterProtocol.js.map +1 -0
- package/dist/internal/machine/commandRuntime.d.ts +1 -1
- package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
- package/dist/internal/machine/configuration.d.ts +2 -2
- package/dist/internal/machine/configuration.d.ts.map +1 -1
- package/dist/internal/machine/configuration.js +38 -64
- package/dist/internal/machine/configuration.js.map +1 -1
- package/dist/internal/machine/declaration.d.ts +17 -0
- package/dist/internal/machine/declaration.d.ts.map +1 -0
- package/dist/internal/machine/declaration.js +120 -0
- package/dist/internal/machine/declaration.js.map +1 -0
- package/dist/internal/machine/executionPlan.d.ts.map +1 -1
- package/dist/internal/machine/executionPlan.js +15 -22
- package/dist/internal/machine/executionPlan.js.map +1 -1
- package/dist/internal/machine/implementation.d.ts +34 -0
- package/dist/internal/machine/implementation.d.ts.map +1 -0
- package/dist/internal/machine/implementation.js +3 -0
- package/dist/internal/machine/implementation.js.map +1 -0
- package/dist/internal/machine/initialDeclaration.d.ts +14 -0
- package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
- package/dist/internal/machine/initialDeclaration.js +137 -0
- package/dist/internal/machine/initialDeclaration.js.map +1 -0
- package/dist/internal/machine/invocation.d.ts +1 -1
- package/dist/internal/machine/invocation.d.ts.map +1 -1
- package/dist/internal/machine/invocation.js +1 -1
- package/dist/internal/machine/invocation.js.map +1 -1
- package/dist/internal/machine/invocationDefinition.d.ts +1 -1
- package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
- package/dist/internal/machine/machine.d.ts +13 -4
- package/dist/internal/machine/machine.d.ts.map +1 -1
- package/dist/internal/machine/machine.js +169 -388
- package/dist/internal/machine/machine.js.map +1 -1
- package/dist/internal/machine/planner.d.ts +8 -0
- package/dist/internal/machine/planner.d.ts.map +1 -1
- package/dist/internal/machine/planner.js +37 -78
- package/dist/internal/machine/planner.js.map +1 -1
- package/dist/internal/machine/process.d.ts +8 -7
- package/dist/internal/machine/process.d.ts.map +1 -1
- package/dist/internal/machine/process.js +16 -12
- package/dist/internal/machine/process.js.map +1 -1
- package/dist/internal/machine/protocol.d.ts +1 -1
- package/dist/internal/machine/protocol.d.ts.map +1 -1
- package/dist/internal/machine/protocol.js.map +1 -1
- package/dist/internal/machine/runtime.d.ts +2 -230
- package/dist/internal/machine/runtime.d.ts.map +1 -1
- package/dist/internal/machine/runtime.js +8 -1857
- package/dist/internal/machine/runtime.js.map +1 -1
- package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
- package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
- package/dist/internal/machine/runtimeCompiled.js +867 -0
- package/dist/internal/machine/runtimeCompiled.js.map +1 -0
- package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
- package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
- package/dist/internal/machine/runtimeGeneric.js +471 -0
- package/dist/internal/machine/runtimeGeneric.js.map +1 -0
- package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
- package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
- package/dist/internal/machine/runtimeProtocol.js +561 -0
- package/dist/internal/machine/runtimeProtocol.js.map +1 -0
- package/dist/internal/machine/stateDefinition.d.ts +1 -1
- package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
- package/dist/internal/machine/stateDefinition.js +1 -13
- package/dist/internal/machine/stateDefinition.js.map +1 -1
- package/dist/internal/machine/targetReference.d.ts +15 -0
- package/dist/internal/machine/targetReference.d.ts.map +1 -0
- package/dist/internal/machine/targetReference.js +41 -0
- package/dist/internal/machine/targetReference.js.map +1 -0
- package/dist/internal/machine/topology.d.ts.map +1 -1
- package/dist/internal/machine/topology.js +5 -3
- package/dist/internal/machine/topology.js.map +1 -1
- package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
- package/dist/internal/testing/machine/finiteModel.js +53 -46
- package/dist/internal/testing/machine/finiteModel.js.map +1 -1
- package/dist/internal/testing/machine/probe.js +1 -1
- package/dist/internal/testing/machine/probe.js.map +1 -1
- package/dist/internal/testing/machine/verification.d.ts.map +1 -1
- package/dist/internal/testing/machine/verification.js +7 -1
- package/dist/internal/testing/machine/verification.js.map +1 -1
- package/dist/testing/MachineTest.d.ts +105 -73
- package/dist/testing/MachineTest.d.ts.map +1 -1
- package/dist/testing/MachineTest.js +105 -73
- package/dist/testing/MachineTest.js.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.d.ts +18 -13
- package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.js +18 -25
- package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
- package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.js +41 -24
- package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
- package/docs/agent-guide.md +66 -91
- package/docs/machine-review.md +19 -49
- package/docs/root-api.md +62 -62
- package/package.json +1 -1
- package/src/Machine.ts +1836 -2907
- package/src/internal/machine/childRegistry.ts +1 -1
- package/src/internal/machine/cluster.ts +7 -73
- package/src/internal/machine/clusterProtocol.ts +56 -0
- package/src/internal/machine/commandRuntime.ts +1 -1
- package/src/internal/machine/configuration.ts +53 -65
- package/src/internal/machine/declaration.ts +140 -0
- package/src/internal/machine/executionPlan.ts +16 -22
- package/src/internal/machine/implementation.ts +41 -0
- package/src/internal/machine/initialDeclaration.ts +157 -0
- package/src/internal/machine/invocation.ts +3 -3
- package/src/internal/machine/invocationDefinition.ts +1 -1
- package/src/internal/machine/machine.ts +225 -576
- package/src/internal/machine/planner.ts +84 -118
- package/src/internal/machine/process.ts +40 -33
- package/src/internal/machine/protocol.ts +3 -3
- package/src/internal/machine/runtime.ts +20 -3037
- package/src/internal/machine/runtimeCompiled.ts +1166 -0
- package/src/internal/machine/runtimeGeneric.ts +799 -0
- package/src/internal/machine/runtimeProtocol.ts +1213 -0
- package/src/internal/machine/stateDefinition.ts +1 -15
- package/src/internal/machine/targetReference.ts +55 -0
- package/src/internal/machine/topology.ts +5 -3
- package/src/internal/testing/machine/finiteModel.ts +58 -53
- package/src/internal/testing/machine/probe.ts +1 -1
- package/src/internal/testing/machine/verification.ts +7 -1
- package/src/testing/MachineTest.ts +105 -73
- package/src/unstable/cluster/ClusterMachine.ts +22 -25
- package/src/unstable/reactivity/AtomMachine.ts +41 -24
|
@@ -0,0 +1,1213 @@
|
|
|
1
|
+
/** Shared local process contracts, ownership, and observation. */
|
|
2
|
+
import * as Cause from "effect/Cause"
|
|
3
|
+
import * as Channel from "effect/Channel"
|
|
4
|
+
import * as Context from "effect/Context"
|
|
5
|
+
import * as Deferred from "effect/Deferred"
|
|
6
|
+
import * as Effect from "effect/Effect"
|
|
7
|
+
import * as Exit from "effect/Exit"
|
|
8
|
+
import * as Option from "effect/Option"
|
|
9
|
+
import * as PubSub from "effect/PubSub"
|
|
10
|
+
import * as Scope from "effect/Scope"
|
|
11
|
+
import * as Stream from "effect/Stream"
|
|
12
|
+
import type * as Take from "effect/Take"
|
|
13
|
+
import type {
|
|
14
|
+
MachineRef as PublicMachineRef,
|
|
15
|
+
Prepared as PublicPrepared,
|
|
16
|
+
RuntimeOutcome as PublicRuntimeOutcome,
|
|
17
|
+
RuntimeSnapshot as PublicRuntimeSnapshot
|
|
18
|
+
} from "../../Machine.js"
|
|
19
|
+
import type { ChildMachine, Inspection, Machine as MachineDefinition, MachineTarget } from "../../Machine.js"
|
|
20
|
+
import {
|
|
21
|
+
type ChildDescriptor,
|
|
22
|
+
type ChildEntry,
|
|
23
|
+
type ChildKey,
|
|
24
|
+
type ChildObserver,
|
|
25
|
+
type ChildRegistry,
|
|
26
|
+
type ChildSelector,
|
|
27
|
+
matchesChild,
|
|
28
|
+
offerChildObservation,
|
|
29
|
+
registerChild,
|
|
30
|
+
selectRegistryChild,
|
|
31
|
+
takeChildObservations,
|
|
32
|
+
unregisterChild
|
|
33
|
+
} from "./childRegistry.js"
|
|
34
|
+
import { ChildAlreadyExistsError, StoppedError } from "./errors.js"
|
|
35
|
+
import * as InspectionRuntime from "./inspectionRuntime.js"
|
|
36
|
+
import { ChildMachineLogicTypeId } from "./symbols.js"
|
|
37
|
+
|
|
38
|
+
/** @internal */
|
|
39
|
+
export const activeSnapshotObserver: unique symbol = Symbol.for("effect/Machine/activeSnapshotObserver")
|
|
40
|
+
|
|
41
|
+
/** @internal */
|
|
42
|
+
const sendParentOverride: unique symbol = Symbol.for("effect/Machine/sendParentOverride")
|
|
43
|
+
|
|
44
|
+
/** @internal */
|
|
45
|
+
export const acknowledgedSend: unique symbol = Symbol.for("effect/Machine/acknowledgedSend")
|
|
46
|
+
|
|
47
|
+
/** @internal */
|
|
48
|
+
export interface AcknowledgedDelivery<State> {
|
|
49
|
+
readonly before: State
|
|
50
|
+
readonly plan: unknown
|
|
51
|
+
readonly after: State
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const AcknowledgedMessageTypeId: unique symbol = Symbol("effect/Machine/AcknowledgedMessage")
|
|
55
|
+
|
|
56
|
+
/** @internal */
|
|
57
|
+
interface AcknowledgedMessage<Event> {
|
|
58
|
+
readonly [AcknowledgedMessageTypeId]: true
|
|
59
|
+
readonly event: Event
|
|
60
|
+
readonly deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
|
|
61
|
+
readonly inspection?: InspectedDelivery
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @internal */
|
|
65
|
+
export type ProcessMessage<Event> = Event | AcknowledgedMessage<Event>
|
|
66
|
+
|
|
67
|
+
/** @internal */
|
|
68
|
+
export const isAcknowledgedMessage = <Event>(
|
|
69
|
+
message: ProcessMessage<Event>
|
|
70
|
+
): message is AcknowledgedMessage<Event> =>
|
|
71
|
+
typeof message === "object" && message !== null && AcknowledgedMessageTypeId in message
|
|
72
|
+
|
|
73
|
+
/** @internal */
|
|
74
|
+
export const messageEvent = <Event>(message: ProcessMessage<Event>): Event =>
|
|
75
|
+
isAcknowledgedMessage(message) ? message.event : message
|
|
76
|
+
|
|
77
|
+
export const succeedAcknowledgedMessage = <State>(
|
|
78
|
+
message: ProcessMessage<unknown> | undefined,
|
|
79
|
+
delivery: AcknowledgedDelivery<State>
|
|
80
|
+
): void => {
|
|
81
|
+
if (message !== undefined && isAcknowledgedMessage(message)) {
|
|
82
|
+
if (message.deferred !== undefined) {
|
|
83
|
+
Deferred.doneUnsafe(message.deferred, Effect.succeed(delivery as AcknowledgedDelivery<unknown>))
|
|
84
|
+
}
|
|
85
|
+
message.inspection?.complete(delivery as AcknowledgedDelivery<unknown>)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const failAcknowledgedMessage = (
|
|
90
|
+
message: ProcessMessage<unknown> | undefined,
|
|
91
|
+
cause: Cause.Cause<unknown>
|
|
92
|
+
): void => {
|
|
93
|
+
if (message !== undefined && isAcknowledgedMessage(message)) {
|
|
94
|
+
if (message.deferred !== undefined) Deferred.doneUnsafe(message.deferred, Effect.failCause(cause))
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const stopAcknowledgedMessage = (message: ProcessMessage<unknown> | undefined): void => {
|
|
99
|
+
if (message !== undefined && isAcknowledgedMessage(message)) {
|
|
100
|
+
if (message.deferred !== undefined) Deferred.doneUnsafe(message.deferred, Effect.fail(new StoppedError()))
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface InspectedDelivery {
|
|
105
|
+
readonly deliveryId: number
|
|
106
|
+
readonly macrostepId: number
|
|
107
|
+
readonly source: Inspection.Subject | undefined
|
|
108
|
+
readonly event: unknown
|
|
109
|
+
readonly causedBy: Inspection.Causation | undefined
|
|
110
|
+
readonly complete: (delivery: AcknowledgedDelivery<unknown>) => void
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export type InspectedOffer<Event> = (
|
|
114
|
+
event: Event,
|
|
115
|
+
source: Inspection.Subject | undefined,
|
|
116
|
+
causedBy: Inspection.Causation | undefined,
|
|
117
|
+
deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
|
|
118
|
+
) => Effect.Effect<void, StoppedError>
|
|
119
|
+
|
|
120
|
+
export type RuntimeSnapshot<State, Error = never, Output = never> = PublicRuntimeSnapshot<State, Error, Output>
|
|
121
|
+
|
|
122
|
+
export interface VersionedSnapshot<State, Error, Output> {
|
|
123
|
+
readonly revision: number
|
|
124
|
+
readonly snapshot: RuntimeSnapshot<State, Error, Output>
|
|
125
|
+
readonly terminalizing: boolean
|
|
126
|
+
readonly changes: PubSub.PubSub<Take.Take<VersionedSnapshot<State, Error, Output>>> | undefined
|
|
127
|
+
/** Compiled drains retain one non-empty publication chunk until their next Effect boundary. */
|
|
128
|
+
pendingChanges?: VersionedSnapshotBatch<State, Error, Output> | undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
type VersionedSnapshotBatch<State, Error, Output> = [
|
|
132
|
+
VersionedSnapshot<State, Error, Output>,
|
|
133
|
+
...Array<VersionedSnapshot<State, Error, Output>>
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
export type RuntimeOutcome<State, Error = never, Output = never> = PublicRuntimeOutcome<State, Error, Output>
|
|
137
|
+
|
|
138
|
+
export interface MachineRef<out State, in Event, out Error = never, out Output = never, out Emitted = never>
|
|
139
|
+
extends Omit<PublicMachineRef<State, Event, Error, Output, Emitted>, "child" | "childChanges">
|
|
140
|
+
{
|
|
141
|
+
/** @internal */
|
|
142
|
+
readonly inspectionSubject?: Inspection.Subject
|
|
143
|
+
/** @internal */
|
|
144
|
+
readonly sendInspected?: ProcessAddress<Event>["sendInspected"]
|
|
145
|
+
readonly [acknowledgedSend]?: (
|
|
146
|
+
event: Event
|
|
147
|
+
) => Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>
|
|
148
|
+
readonly child: (child: any) => Effect.Effect<Option.Option<any>>
|
|
149
|
+
readonly childChanges: (child: any) => Stream.Stream<Option.Option<any>>
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface PreparedProcess<
|
|
153
|
+
out State,
|
|
154
|
+
in Event,
|
|
155
|
+
out Error,
|
|
156
|
+
out Output,
|
|
157
|
+
out Emitted,
|
|
158
|
+
out StartError,
|
|
159
|
+
StartRequirements
|
|
160
|
+
> extends Omit<PublicPrepared<State, Event, Error, Output, Emitted, StartError, StartRequirements>, "start"> {
|
|
161
|
+
readonly start: Effect.Effect<MachineRef<State, Event, Error, Output, Emitted>, StartError, StartRequirements>
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface ProcessAddress<in Event> {
|
|
165
|
+
readonly id: string
|
|
166
|
+
readonly sessionId: string
|
|
167
|
+
readonly inspectionSubject?: Inspection.Subject
|
|
168
|
+
readonly stop: Effect.Effect<void>
|
|
169
|
+
readonly send: (event: Event) => Effect.Effect<void, StoppedError>
|
|
170
|
+
readonly sendInspected?: (
|
|
171
|
+
event: Event,
|
|
172
|
+
source: Inspection.Subject | undefined,
|
|
173
|
+
causedBy: Inspection.Causation | undefined
|
|
174
|
+
) => Effect.Effect<void, StoppedError>
|
|
175
|
+
readonly [acknowledgedSend]?: (
|
|
176
|
+
event: Event
|
|
177
|
+
) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export const isMachineTarget = (value: unknown): value is MachineTarget<unknown> =>
|
|
181
|
+
typeof value === "object" && value !== null && "send" in value && typeof value.send === "function"
|
|
182
|
+
|
|
183
|
+
export const sendMachineTarget = (
|
|
184
|
+
target: MachineTarget<unknown>,
|
|
185
|
+
event: unknown,
|
|
186
|
+
source: Inspection.Subject | undefined,
|
|
187
|
+
causedBy: Inspection.Causation | undefined
|
|
188
|
+
): Effect.Effect<void, StoppedError> =>
|
|
189
|
+
"inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function"
|
|
190
|
+
? target.sendInspected(event, source, causedBy)
|
|
191
|
+
: target.send(event)
|
|
192
|
+
|
|
193
|
+
export interface ProcessScope<Event> {
|
|
194
|
+
readonly self: ProcessAddress<Event>
|
|
195
|
+
readonly parent: ProcessAddress<unknown> | undefined
|
|
196
|
+
readonly spawn: ProcessSpawn<Event>
|
|
197
|
+
readonly sendParent: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
198
|
+
readonly emit: (event: unknown) => Effect.Effect<void>
|
|
199
|
+
readonly sendTo: {
|
|
200
|
+
<TargetEvent>(target: MachineTarget<TargetEvent>, event: TargetEvent): Effect.Effect<void, StoppedError>
|
|
201
|
+
(child: ChildSelector, event: unknown): Effect.Effect<void, StoppedError>
|
|
202
|
+
}
|
|
203
|
+
readonly stopChild: (child: ChildSelector) => Effect.Effect<void>
|
|
204
|
+
/** @internal */
|
|
205
|
+
readonly failCause: (cause: Cause.Cause<unknown>) => Effect.Effect<void>
|
|
206
|
+
/** @internal */
|
|
207
|
+
readonly inspectInitial: (
|
|
208
|
+
initialEntryPaths: ReadonlyArray<string>,
|
|
209
|
+
microsteps?: ReadonlyArray<unknown>
|
|
210
|
+
) => void
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export interface ProcessContext<State, Event> extends ProcessScope<Event> {
|
|
214
|
+
readonly receive: Effect.Effect<Event>
|
|
215
|
+
/** @internal */
|
|
216
|
+
readonly poll?: Effect.Effect<Option.Option<Event>>
|
|
217
|
+
/** @internal */
|
|
218
|
+
readonly receiveMessage?: Effect.Effect<ProcessMessage<Event>>
|
|
219
|
+
/** @internal */
|
|
220
|
+
readonly pollMessage?: Effect.Effect<Option.Option<ProcessMessage<Event>>>
|
|
221
|
+
/** @internal */
|
|
222
|
+
readonly completeMessage?: (delivery: AcknowledgedDelivery<State>) => void
|
|
223
|
+
readonly state: Effect.Effect<State>
|
|
224
|
+
readonly setState: (state: State) => Effect.Effect<void>
|
|
225
|
+
readonly updateState: <E, R>(
|
|
226
|
+
f: (state: State) => Effect.Effect<State, E, R>
|
|
227
|
+
) => Effect.Effect<void, E, R>
|
|
228
|
+
/** Present only when a compiled statechart is forced through the generic runtime. @internal */
|
|
229
|
+
readonly ownedChildren?: OwnedChildRuntime
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Owner-local execution context for compiled statecharts.
|
|
234
|
+
*
|
|
235
|
+
* Unlike `ProcessContext`, synchronous mailbox and state operations do not
|
|
236
|
+
* introduce an Effect boundary. The compiled drain still returns an Effect so
|
|
237
|
+
* machine commands, invokes, observation callbacks, interruption, and the Effect
|
|
238
|
+
* scheduler remain explicit at their actual boundaries.
|
|
239
|
+
*
|
|
240
|
+
* @internal
|
|
241
|
+
*/
|
|
242
|
+
export interface CompiledProcessContext<State, Event> {
|
|
243
|
+
readonly scope: ProcessScope<Event>
|
|
244
|
+
readonly ownedChildren: OwnedChildRuntime
|
|
245
|
+
readonly poll: () => Option.Option<Event>
|
|
246
|
+
readonly pollMessage: () => Option.Option<ProcessMessage<Event>>
|
|
247
|
+
readonly state: () => State
|
|
248
|
+
readonly completeMessage: (delivery: AcknowledgedDelivery<State>) => void
|
|
249
|
+
readonly commit: (state: State) => Effect.Effect<void> | undefined
|
|
250
|
+
/**
|
|
251
|
+
* Publishes the current synchronous segment before continuing with work that
|
|
252
|
+
* may suspend, run user effects, or make the committed state observable.
|
|
253
|
+
*/
|
|
254
|
+
readonly runAfterChanges: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
|
|
255
|
+
executionState: unknown
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export type CompiledProcessInitial<State, Output> =
|
|
259
|
+
| { readonly state: State; readonly done: false; readonly output: undefined }
|
|
260
|
+
| { readonly state: State; readonly done: true; readonly output: Output }
|
|
261
|
+
| {
|
|
262
|
+
readonly state: State
|
|
263
|
+
readonly done: boolean
|
|
264
|
+
readonly output: Output | undefined
|
|
265
|
+
readonly executionState: unknown
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
type CompiledProcessDrain<State, Event, Error, Requirements, Output> =
|
|
269
|
+
| {
|
|
270
|
+
readonly _tag: "Process"
|
|
271
|
+
readonly run: (
|
|
272
|
+
context: ProcessContext<State, Event>
|
|
273
|
+
) => Effect.Effect<Option.Option<Output>, Error, Requirements>
|
|
274
|
+
}
|
|
275
|
+
| {
|
|
276
|
+
readonly _tag: "Owned"
|
|
277
|
+
readonly run: (
|
|
278
|
+
context: CompiledProcessContext<State, Event>
|
|
279
|
+
) => Effect.Effect<Option.Option<Output>, Error, Requirements>
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The complete capability descriptor consumed by the compact process runtime.
|
|
284
|
+
* Generic process logic omits this field entirely.
|
|
285
|
+
*
|
|
286
|
+
* @internal
|
|
287
|
+
*/
|
|
288
|
+
export interface CompiledProcessExecution<
|
|
289
|
+
State,
|
|
290
|
+
Event,
|
|
291
|
+
Error,
|
|
292
|
+
Requirements,
|
|
293
|
+
Output,
|
|
294
|
+
InitialError
|
|
295
|
+
> {
|
|
296
|
+
readonly _tag: "Compiled"
|
|
297
|
+
readonly childless: boolean
|
|
298
|
+
readonly initial?: (
|
|
299
|
+
scope: ProcessScope<Event>
|
|
300
|
+
) => Effect.Effect<CompiledProcessInitial<State, Output>, InitialError, Requirements>
|
|
301
|
+
readonly initialSync?: (
|
|
302
|
+
scope: ProcessScope<Event>
|
|
303
|
+
) => CompiledProcessInitial<State, Output>
|
|
304
|
+
readonly drain: CompiledProcessDrain<State, Event, Error, Requirements, Output>
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
type ProcessExecution<State, Event, Error, Requirements, Output, InitialError> =
|
|
308
|
+
| {
|
|
309
|
+
readonly _tag: "Childless"
|
|
310
|
+
}
|
|
311
|
+
| CompiledProcessExecution<State, Event, Error, Requirements, Output, InitialError>
|
|
312
|
+
|
|
313
|
+
export const executionIsChildless = (
|
|
314
|
+
execution: ProcessExecution<any, any, any, any, any, any> | undefined
|
|
315
|
+
): boolean => execution?._tag === "Childless" || execution?.childless === true
|
|
316
|
+
|
|
317
|
+
export interface CompactProcessMailbox<Event> {
|
|
318
|
+
items: Array<ProcessMessage<Event>> | undefined
|
|
319
|
+
index: number
|
|
320
|
+
closed: boolean
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export const offerCompactMailbox = <Event>(
|
|
324
|
+
mailbox: CompactProcessMailbox<Event>,
|
|
325
|
+
event: ProcessMessage<Event>
|
|
326
|
+
): void => {
|
|
327
|
+
const items = mailbox.items ?? []
|
|
328
|
+
mailbox.items = items
|
|
329
|
+
items.push(event)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export const pollCompactMailbox = <Event>(
|
|
333
|
+
mailbox: CompactProcessMailbox<Event>
|
|
334
|
+
): Option.Option<ProcessMessage<Event>> => {
|
|
335
|
+
if (mailbox.items === undefined) {
|
|
336
|
+
return Option.none()
|
|
337
|
+
}
|
|
338
|
+
const event = mailbox.items[mailbox.index]!
|
|
339
|
+
mailbox.index += 1
|
|
340
|
+
if (mailbox.index === mailbox.items.length) {
|
|
341
|
+
mailbox.items = undefined
|
|
342
|
+
mailbox.index = 0
|
|
343
|
+
}
|
|
344
|
+
return Option.some(event)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export const closeCompactMailbox = (mailbox: CompactProcessMailbox<unknown>): void => {
|
|
348
|
+
if (mailbox.items !== undefined) {
|
|
349
|
+
for (let index = mailbox.index; index < mailbox.items.length; index += 1) {
|
|
350
|
+
stopAcknowledgedMessage(mailbox.items[index])
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
mailbox.closed = true
|
|
354
|
+
mailbox.items = undefined
|
|
355
|
+
mailbox.index = 0
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export interface ProcessLogic<
|
|
359
|
+
State,
|
|
360
|
+
Event,
|
|
361
|
+
out Error = never,
|
|
362
|
+
out Requirements = never,
|
|
363
|
+
out Output = never,
|
|
364
|
+
out InitialError = never
|
|
365
|
+
> {
|
|
366
|
+
/** @internal */
|
|
367
|
+
readonly execution?: ProcessExecution<State, Event, Error, Requirements, Output, InitialError>
|
|
368
|
+
/** @internal */
|
|
369
|
+
readonly inspection?: {
|
|
370
|
+
readonly kind: Inspection.Subject["kind"]
|
|
371
|
+
readonly definition?: MachineDefinition.Any
|
|
372
|
+
}
|
|
373
|
+
initial(scope: ProcessScope<Event>): Effect.Effect<State, InitialError, Requirements>
|
|
374
|
+
run(context: ProcessContext<State, Event>): Effect.Effect<Output, Error, Requirements>
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
interface ProcessSpawn<OwnerEvent = unknown> {
|
|
378
|
+
<const Child extends ChildMachine.Any>(
|
|
379
|
+
child: Child & ChildMachine.Executable<Child> & ChildMachine.ParentCompatibility<Child, OwnerEvent>,
|
|
380
|
+
...options: ChildMachine.SpawnArgs<Child>
|
|
381
|
+
): Effect.Effect<
|
|
382
|
+
ChildMachine.Ref<Child>,
|
|
383
|
+
ChildAlreadyExistsError | ChildMachine.StartError<Child>,
|
|
384
|
+
ChildMachine.StartRequirements<Child>
|
|
385
|
+
>
|
|
386
|
+
<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
|
|
387
|
+
logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>
|
|
388
|
+
): Effect.Effect<
|
|
389
|
+
MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
|
|
390
|
+
ChildInitialError,
|
|
391
|
+
Exclude<ChildRequirements, Scope.Scope>
|
|
392
|
+
>
|
|
393
|
+
<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
|
|
394
|
+
logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>,
|
|
395
|
+
options: {
|
|
396
|
+
readonly id: string
|
|
397
|
+
readonly descriptor?: ChildDescriptor
|
|
398
|
+
readonly onOutcome?: (
|
|
399
|
+
outcome: RuntimeOutcome<ChildState, ChildError, ChildOutput>
|
|
400
|
+
) => Effect.Effect<void>
|
|
401
|
+
readonly [activeSnapshotObserver]?: (
|
|
402
|
+
snapshot: Extract<RuntimeSnapshot<ChildState, ChildError, ChildOutput>, { readonly status: "active" }>
|
|
403
|
+
) => Effect.Effect<void>
|
|
404
|
+
readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
405
|
+
}
|
|
406
|
+
): Effect.Effect<
|
|
407
|
+
MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
|
|
408
|
+
ChildAlreadyExistsError | ChildInitialError,
|
|
409
|
+
Exclude<ChildRequirements, Scope.Scope>
|
|
410
|
+
>
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export class MachineRuntime extends Context.Service<MachineRuntime, ProcessScope<any>>()(
|
|
414
|
+
"effect/Machine/MachineRuntime"
|
|
415
|
+
) {}
|
|
416
|
+
|
|
417
|
+
export const provideMachineRuntime = <A, E, R, Event>(
|
|
418
|
+
effect: Effect.Effect<A, E, R>,
|
|
419
|
+
scope: ProcessScope<Event>
|
|
420
|
+
): Effect.Effect<A, E, Exclude<R, MachineRuntime>> =>
|
|
421
|
+
Effect.provideService(effect, MachineRuntime, scope as ProcessScope<any>)
|
|
422
|
+
|
|
423
|
+
export const classifyOutcome = <State, Error, Output>(
|
|
424
|
+
snapshot: RuntimeSnapshot<State, Error, Output>
|
|
425
|
+
): RuntimeOutcome<State, Error, Output> | undefined => {
|
|
426
|
+
switch (snapshot.status) {
|
|
427
|
+
case "active": {
|
|
428
|
+
return undefined
|
|
429
|
+
}
|
|
430
|
+
case "done": {
|
|
431
|
+
return {
|
|
432
|
+
_tag: "Done",
|
|
433
|
+
output: snapshot.output,
|
|
434
|
+
snapshot
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
case "error": {
|
|
438
|
+
const failure = snapshot.cause.reasons.find(Cause.isFailReason)
|
|
439
|
+
if (failure !== undefined) {
|
|
440
|
+
return {
|
|
441
|
+
_tag: "Failure",
|
|
442
|
+
error: failure.error,
|
|
443
|
+
cause: snapshot.cause,
|
|
444
|
+
snapshot
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const defect = snapshot.cause.reasons.find(Cause.isDieReason)
|
|
448
|
+
if (defect !== undefined) {
|
|
449
|
+
return {
|
|
450
|
+
_tag: "Defect",
|
|
451
|
+
defect: defect.defect,
|
|
452
|
+
cause: snapshot.cause,
|
|
453
|
+
snapshot
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const interrupted = snapshot.cause.reasons.find(Cause.isInterruptReason)
|
|
457
|
+
if (interrupted !== undefined) {
|
|
458
|
+
return {
|
|
459
|
+
_tag: "Interrupted",
|
|
460
|
+
cause: snapshot.cause,
|
|
461
|
+
snapshot
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return {
|
|
465
|
+
_tag: "Cause",
|
|
466
|
+
cause: snapshot.cause,
|
|
467
|
+
snapshot
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
case "stopped": {
|
|
471
|
+
return {
|
|
472
|
+
_tag: "Stopped",
|
|
473
|
+
snapshot
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export const notifyActiveSnapshot = <State, Error, Output>(
|
|
480
|
+
onSnapshot: (
|
|
481
|
+
snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
|
|
482
|
+
) => Effect.Effect<void>,
|
|
483
|
+
snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
|
|
484
|
+
): Effect.Effect<void> =>
|
|
485
|
+
Effect.suspend(() => onSnapshot(snapshot)).pipe(
|
|
486
|
+
Effect.exit,
|
|
487
|
+
Effect.asVoid
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
export const watch = <State, Event, Error = never, Output = never>(
|
|
491
|
+
ref: MachineRef<State, Event, Error, Output>
|
|
492
|
+
): Stream.Stream<RuntimeOutcome<State, Error, Output>> =>
|
|
493
|
+
ref.changes.pipe(
|
|
494
|
+
Stream.filter((snapshot) => snapshot.status !== "active"),
|
|
495
|
+
Stream.map((snapshot) => classifyOutcome(snapshot)!),
|
|
496
|
+
Stream.take(1)
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
export interface ProcessRuntime {
|
|
500
|
+
readonly start: StartProcess
|
|
501
|
+
readonly startCompiledSync: (
|
|
502
|
+
logic: ProcessLogic<any, any, any, any, any, any>,
|
|
503
|
+
options: StartInternalOptions,
|
|
504
|
+
services: Context.Context<any>,
|
|
505
|
+
sessionId: string
|
|
506
|
+
) => Effect.Effect<MachineRef<any, any, any, any>, any, any>
|
|
507
|
+
readonly nextSessionId: Effect.Effect<string>
|
|
508
|
+
inspection?: InspectionRuntime.Runtime
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export const makeProcessRuntime = (
|
|
512
|
+
start: StartProcess,
|
|
513
|
+
startCompiledSync: ProcessRuntime["startCompiledSync"]
|
|
514
|
+
): Effect.Effect<ProcessRuntime> => {
|
|
515
|
+
// Strategy hooks belong to the shared prototype. Each root owns only its
|
|
516
|
+
// session counter and optional inspection runtime, independent of other roots.
|
|
517
|
+
class Runtime implements ProcessRuntime {
|
|
518
|
+
declare inspection?: InspectionRuntime.Runtime
|
|
519
|
+
readonly nextSessionId: Effect.Effect<string>
|
|
520
|
+
|
|
521
|
+
constructor() {
|
|
522
|
+
let sessionIdCounter = 0
|
|
523
|
+
this.nextSessionId = Effect.sync(() => `machine:${sessionIdCounter++}`)
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
get start(): StartProcess {
|
|
527
|
+
return start
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
get startCompiledSync(): ProcessRuntime["startCompiledSync"] {
|
|
531
|
+
return startCompiledSync
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return Effect.sync(() => new Runtime())
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export const inspectionSubject = (
|
|
538
|
+
logic: ProcessLogic<any, any, any, any, any, any>,
|
|
539
|
+
id: string,
|
|
540
|
+
sessionId: string
|
|
541
|
+
): Inspection.Subject => ({
|
|
542
|
+
id,
|
|
543
|
+
sessionId,
|
|
544
|
+
kind: logic.inspection?.kind ?? "Logic"
|
|
545
|
+
})
|
|
546
|
+
|
|
547
|
+
export const messageCausation = (
|
|
548
|
+
message: ProcessMessage<unknown> | undefined,
|
|
549
|
+
initializing: boolean
|
|
550
|
+
): Inspection.Causation | undefined =>
|
|
551
|
+
initializing
|
|
552
|
+
? { _tag: "Initialization" }
|
|
553
|
+
: message !== undefined && isAcknowledgedMessage(message) && message.inspection !== undefined
|
|
554
|
+
? { _tag: "Macrostep", macrostepId: message.inspection.macrostepId }
|
|
555
|
+
: undefined
|
|
556
|
+
|
|
557
|
+
export const makeInspectedMessage = <Event>(
|
|
558
|
+
inspection: InspectionRuntime.Runtime,
|
|
559
|
+
subject: Inspection.Subject,
|
|
560
|
+
event: Event,
|
|
561
|
+
source: Inspection.Subject | undefined,
|
|
562
|
+
causedBy: Inspection.Causation | undefined,
|
|
563
|
+
deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
|
|
564
|
+
): AcknowledgedMessage<Event> => {
|
|
565
|
+
const deliveryId = inspection.nextDeliveryId()
|
|
566
|
+
const macrostepId = inspection.nextMacrostepId()
|
|
567
|
+
const inspected: InspectedDelivery = {
|
|
568
|
+
deliveryId,
|
|
569
|
+
macrostepId,
|
|
570
|
+
source,
|
|
571
|
+
event,
|
|
572
|
+
causedBy,
|
|
573
|
+
complete: (delivery) => {
|
|
574
|
+
const microsteps = InspectionRuntime.microsteps(delivery.plan)
|
|
575
|
+
inspection.publishUnsafe({
|
|
576
|
+
_tag: "EventProcessed",
|
|
577
|
+
subject,
|
|
578
|
+
macrostepId,
|
|
579
|
+
deliveryId,
|
|
580
|
+
source,
|
|
581
|
+
event,
|
|
582
|
+
before: { status: "active", state: delivery.before },
|
|
583
|
+
after: { status: "active", state: delivery.after },
|
|
584
|
+
handled: microsteps.some((microstep) => microstep.transitions.length > 0),
|
|
585
|
+
configurationChanged: microsteps.some((microstep) => microstep.changed),
|
|
586
|
+
microsteps
|
|
587
|
+
})
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return {
|
|
591
|
+
[AcknowledgedMessageTypeId]: true,
|
|
592
|
+
event,
|
|
593
|
+
...(deferred === undefined ? undefined : { deferred }),
|
|
594
|
+
inspection: inspected
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
export const publishInspectedSent = (
|
|
599
|
+
inspection: InspectionRuntime.Runtime,
|
|
600
|
+
subject: Inspection.Subject,
|
|
601
|
+
message: ProcessMessage<unknown>
|
|
602
|
+
): void => {
|
|
603
|
+
if (!isAcknowledgedMessage(message) || message.inspection === undefined) return
|
|
604
|
+
const delivery = message.inspection
|
|
605
|
+
inspection.publishUnsafe({
|
|
606
|
+
_tag: "EventSent",
|
|
607
|
+
subject,
|
|
608
|
+
deliveryId: delivery.deliveryId,
|
|
609
|
+
source: delivery.source,
|
|
610
|
+
target: InspectionRuntime.endpoint(subject),
|
|
611
|
+
event: delivery.event,
|
|
612
|
+
causedBy: delivery.causedBy
|
|
613
|
+
})
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
export interface StartInternalOptions {
|
|
617
|
+
readonly detached?: boolean
|
|
618
|
+
readonly id?: string
|
|
619
|
+
readonly sessionId?: string
|
|
620
|
+
readonly emissions?: EmissionRuntime
|
|
621
|
+
readonly onOutcome?: (outcome: RuntimeOutcome<any, any, any>) => Effect.Effect<void>
|
|
622
|
+
readonly onSnapshot?: (
|
|
623
|
+
snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
|
|
624
|
+
) => Effect.Effect<void>
|
|
625
|
+
readonly onReady?: (
|
|
626
|
+
ref: MachineRef<any, any, any, any>,
|
|
627
|
+
requestStop: Effect.Effect<void>
|
|
628
|
+
) => Effect.Effect<void>
|
|
629
|
+
readonly onReadySync?: (ref: MachineRef<any, any, any, any>) => boolean
|
|
630
|
+
readonly onStop?: Effect.Effect<void>
|
|
631
|
+
readonly onStopSync?: () => void
|
|
632
|
+
readonly skipStoppedOutcome?: boolean
|
|
633
|
+
readonly parent?: ProcessAddress<unknown>
|
|
634
|
+
readonly runtime: ProcessRuntime
|
|
635
|
+
readonly sendParent?: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
636
|
+
readonly origin?: Inspection.Origin
|
|
637
|
+
readonly activity?: {
|
|
638
|
+
readonly id: string
|
|
639
|
+
readonly owner: Inspection.Subject
|
|
640
|
+
readonly ownerPath: string
|
|
641
|
+
readonly kind: Inspection.Activity["kind"]
|
|
642
|
+
}
|
|
643
|
+
readonly inspectionRoot?: boolean
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** @internal */
|
|
647
|
+
interface OwnedChildSpawnOptions {
|
|
648
|
+
readonly key: string
|
|
649
|
+
readonly path: string
|
|
650
|
+
readonly id: string
|
|
651
|
+
readonly duplicateId: string
|
|
652
|
+
readonly descriptor?: ChildDescriptor
|
|
653
|
+
readonly onOutcome: (
|
|
654
|
+
isCurrent: () => boolean,
|
|
655
|
+
outcome: RuntimeOutcome<any, any, any>,
|
|
656
|
+
activitySessionId: string | undefined
|
|
657
|
+
) => Effect.Effect<void>
|
|
658
|
+
readonly onSnapshot?: (
|
|
659
|
+
isCurrent: () => boolean,
|
|
660
|
+
snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
|
|
661
|
+
) => Effect.Effect<void>
|
|
662
|
+
readonly sendParent: (
|
|
663
|
+
isCurrent: () => boolean,
|
|
664
|
+
event: unknown
|
|
665
|
+
) => Effect.Effect<void, StoppedError>
|
|
666
|
+
readonly activityKind?: Inspection.Activity["kind"]
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** @internal */
|
|
670
|
+
export interface OwnedChildRuntime {
|
|
671
|
+
readonly spawn: (
|
|
672
|
+
makeLogic: () => ProcessLogic<any, any, any, any, any, any>,
|
|
673
|
+
options: OwnedChildSpawnOptions
|
|
674
|
+
) => Effect.Effect<void, any, any>
|
|
675
|
+
readonly stopAll: () => Effect.Effect<void>
|
|
676
|
+
readonly stopPaths: (paths: ReadonlyArray<string>) => Effect.Effect<void> | undefined
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
export interface ChildRuntime {
|
|
680
|
+
readonly close: <A, E>(exit: Exit.Exit<A, E>) => Effect.Effect<void>
|
|
681
|
+
readonly spawn: ProcessSpawn
|
|
682
|
+
readonly get: <ChildState, ChildEvent, ChildError, ChildOutput>(
|
|
683
|
+
child: ChildSelector
|
|
684
|
+
) => Effect.Effect<Option.Option<MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>>>
|
|
685
|
+
readonly changes: <ChildState, ChildEvent, ChildError, ChildOutput>(
|
|
686
|
+
child: ChildSelector
|
|
687
|
+
) => Stream.Stream<Option.Option<MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>>>
|
|
688
|
+
readonly sendTo: (
|
|
689
|
+
child: ChildSelector,
|
|
690
|
+
event: unknown,
|
|
691
|
+
source?: Inspection.Subject,
|
|
692
|
+
causedBy?: Inspection.Causation
|
|
693
|
+
) => Effect.Effect<void, StoppedError>
|
|
694
|
+
readonly stop: (child: ChildSelector) => Effect.Effect<void>
|
|
695
|
+
readonly owned: OwnedChildRuntime
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
class OwnedChildRuntimeImpl implements OwnedChildRuntime {
|
|
699
|
+
private scopedServices: Context.Context<any> | undefined
|
|
700
|
+
|
|
701
|
+
constructor(
|
|
702
|
+
private readonly registry: ChildRegistry,
|
|
703
|
+
private readonly self: ProcessAddress<any>,
|
|
704
|
+
private readonly runtime: ProcessRuntime,
|
|
705
|
+
private readonly services?: Context.Context<any>,
|
|
706
|
+
private readonly sendAcknowledged?: (
|
|
707
|
+
event: unknown
|
|
708
|
+
) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
|
|
709
|
+
) {}
|
|
710
|
+
|
|
711
|
+
private has(key: string): boolean {
|
|
712
|
+
for (const entry of this.registry.children.values()) {
|
|
713
|
+
if (entry.ownerActive && entry.ownerKey === key) return true
|
|
714
|
+
}
|
|
715
|
+
return false
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
private stopEntry(entry: ChildEntry): Effect.Effect<void> {
|
|
719
|
+
entry.ownerActive = false
|
|
720
|
+
return entry._tag === "Started" ? entry.ref.stop : Effect.void
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
spawn(
|
|
724
|
+
makeLogic: () => ProcessLogic<any, any, any, any, any, any>,
|
|
725
|
+
options: OwnedChildSpawnOptions
|
|
726
|
+
): Effect.Effect<void, any, any> {
|
|
727
|
+
const token = Symbol()
|
|
728
|
+
let startedChild: MachineRef<any, any, any, any> | undefined
|
|
729
|
+
const isCurrent = (): boolean => {
|
|
730
|
+
const entry = this.registry.children.get(options.id)
|
|
731
|
+
return entry?.token === token && entry.ownerKey === options.key && entry.ownerActive === true
|
|
732
|
+
}
|
|
733
|
+
return Effect.suspend(() => {
|
|
734
|
+
if (this.registry.closed) return Effect.interrupt
|
|
735
|
+
if (this.has(options.key) || this.registry.children.has(options.id)) {
|
|
736
|
+
return Effect.fail(new ChildAlreadyExistsError({ id: options.duplicateId }))
|
|
737
|
+
}
|
|
738
|
+
const logic = makeLogic()
|
|
739
|
+
const scope = this.registry.scope ??= Scope.makeUnsafe("parallel")
|
|
740
|
+
this.registry.children.set(options.id, {
|
|
741
|
+
_tag: "Starting",
|
|
742
|
+
token,
|
|
743
|
+
ownerKey: options.key,
|
|
744
|
+
ownerPath: options.path,
|
|
745
|
+
ownerActive: true
|
|
746
|
+
})
|
|
747
|
+
const parent: ProcessAddress<unknown> = {
|
|
748
|
+
...this.self,
|
|
749
|
+
send: (event) => options.sendParent(isCurrent, event),
|
|
750
|
+
sendInspected: (event, source, causedBy) =>
|
|
751
|
+
isCurrent() ? sendMachineTarget(this.self, event, source, causedBy) : Effect.void,
|
|
752
|
+
...(this.sendAcknowledged === undefined
|
|
753
|
+
? undefined
|
|
754
|
+
: {
|
|
755
|
+
[acknowledgedSend]: (event: unknown) =>
|
|
756
|
+
isCurrent()
|
|
757
|
+
? this.sendAcknowledged!(event)
|
|
758
|
+
: Effect.interrupt
|
|
759
|
+
})
|
|
760
|
+
}
|
|
761
|
+
const startOptions: StartInternalOptions = {
|
|
762
|
+
detached: true,
|
|
763
|
+
id: options.id,
|
|
764
|
+
sendParent: (event) => options.sendParent(isCurrent, event),
|
|
765
|
+
onOutcome: (outcome) => options.onOutcome(isCurrent, outcome, startedChild?.sessionId),
|
|
766
|
+
...(options.onSnapshot === undefined
|
|
767
|
+
? undefined
|
|
768
|
+
: { onSnapshot: (snapshot) => options.onSnapshot!(isCurrent, snapshot) }),
|
|
769
|
+
onReadySync: (child) => {
|
|
770
|
+
startedChild = child
|
|
771
|
+
return registerChild(this.registry, options.id, token, child, options.descriptor)
|
|
772
|
+
},
|
|
773
|
+
onStopSync: () => unregisterChild(this.registry, options.id, token),
|
|
774
|
+
skipStoppedOutcome: true,
|
|
775
|
+
parent,
|
|
776
|
+
runtime: this.runtime,
|
|
777
|
+
origin: { _tag: "Invoke", ownerPath: options.path, invokeId: options.duplicateId },
|
|
778
|
+
...(options.activityKind === undefined || this.runtime.inspection === undefined ||
|
|
779
|
+
this.self.inspectionSubject === undefined
|
|
780
|
+
? undefined
|
|
781
|
+
: {
|
|
782
|
+
activity: {
|
|
783
|
+
id: options.duplicateId,
|
|
784
|
+
owner: this.self.inspectionSubject,
|
|
785
|
+
ownerPath: options.path,
|
|
786
|
+
kind: options.activityKind
|
|
787
|
+
}
|
|
788
|
+
})
|
|
789
|
+
}
|
|
790
|
+
const execution = logic.execution
|
|
791
|
+
const synchronous = this.services !== undefined && options.onSnapshot === undefined &&
|
|
792
|
+
execution?._tag === "Compiled" && execution.childless && execution.drain._tag === "Owned" &&
|
|
793
|
+
execution.initialSync !== undefined
|
|
794
|
+
const start = synchronous
|
|
795
|
+
? Effect.flatMap(
|
|
796
|
+
this.runtime.nextSessionId,
|
|
797
|
+
(sessionId) =>
|
|
798
|
+
this.runtime.startCompiledSync(
|
|
799
|
+
logic,
|
|
800
|
+
startOptions,
|
|
801
|
+
this.scopedServices ??= Context.add(this.services!, Scope.Scope, scope),
|
|
802
|
+
sessionId
|
|
803
|
+
)
|
|
804
|
+
)
|
|
805
|
+
: this.runtime.start(logic, startOptions)
|
|
806
|
+
const guarded = start.pipe(
|
|
807
|
+
Effect.onExit((exit) => {
|
|
808
|
+
if (Exit.isSuccess(exit)) return Effect.void
|
|
809
|
+
unregisterChild(this.registry, options.id, token)
|
|
810
|
+
return startedChild === undefined ? Effect.void : startedChild.stop
|
|
811
|
+
})
|
|
812
|
+
)
|
|
813
|
+
return (synchronous ? guarded : Scope.provide(guarded, scope)).pipe(Effect.asVoid)
|
|
814
|
+
})
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
stopAll(): Effect.Effect<void> {
|
|
818
|
+
return Effect.suspend(() => {
|
|
819
|
+
const effects: Array<Effect.Effect<void>> = []
|
|
820
|
+
for (const entry of this.registry.children.values()) {
|
|
821
|
+
if (entry.ownerActive) effects.push(this.stopEntry(entry))
|
|
822
|
+
}
|
|
823
|
+
return effects.length === 0
|
|
824
|
+
? Effect.void
|
|
825
|
+
: effects.length === 1
|
|
826
|
+
? effects[0]!
|
|
827
|
+
: Effect.all(effects, { concurrency: "unbounded", discard: true })
|
|
828
|
+
})
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
stopPaths(paths: ReadonlyArray<string>): Effect.Effect<void> | undefined {
|
|
832
|
+
if (paths.length === 0) return undefined
|
|
833
|
+
const pathSet = new Set(paths)
|
|
834
|
+
const effects: Array<Effect.Effect<void>> = []
|
|
835
|
+
for (const entry of this.registry.children.values()) {
|
|
836
|
+
if (entry.ownerActive && entry.ownerPath !== undefined && pathSet.has(entry.ownerPath)) {
|
|
837
|
+
effects.push(this.stopEntry(entry))
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return effects.length === 0
|
|
841
|
+
? undefined
|
|
842
|
+
: effects.length === 1
|
|
843
|
+
? effects[0]!
|
|
844
|
+
: Effect.all(effects, { concurrency: "unbounded", discard: true })
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
const noChildChanges = Stream.succeed(Option.none()).pipe(Stream.concat(Stream.never))
|
|
849
|
+
export const noParentSend = (_event: unknown): Effect.Effect<void, StoppedError> => Effect.void
|
|
850
|
+
export const noInspectInitial = (_paths: ReadonlyArray<string>, _microsteps?: ReadonlyArray<unknown>): void => {}
|
|
851
|
+
export const noCausation = (): Inspection.Causation | undefined => undefined
|
|
852
|
+
export const EmissionsClosed: unique symbol = Symbol("effect/Machine/EmissionsClosed")
|
|
853
|
+
|
|
854
|
+
export type LazyEmissions = PubSub.PubSub<unknown> | typeof EmissionsClosed | undefined
|
|
855
|
+
|
|
856
|
+
export interface EmissionRuntime {
|
|
857
|
+
readonly emit: (event: unknown) => Effect.Effect<void>
|
|
858
|
+
readonly close: () => Effect.Effect<void>
|
|
859
|
+
readonly stream: Stream.Stream<unknown>
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
export const makeEmissionRuntime = (): EmissionRuntime => {
|
|
863
|
+
let emissions: LazyEmissions
|
|
864
|
+
const getOrCreate: Effect.Effect<PubSub.PubSub<unknown> | undefined> = Effect.suspend(() => {
|
|
865
|
+
const observed = emissions
|
|
866
|
+
if (observed === EmissionsClosed) return Effect.succeed(undefined)
|
|
867
|
+
if (observed !== undefined) return Effect.succeed(observed)
|
|
868
|
+
return PubSub.unbounded<unknown>().pipe(
|
|
869
|
+
Effect.flatMap((candidate) =>
|
|
870
|
+
Effect.sync(() => {
|
|
871
|
+
const latest = emissions
|
|
872
|
+
if (latest === EmissionsClosed) return [undefined, true] as const
|
|
873
|
+
if (latest !== undefined) return [latest, true] as const
|
|
874
|
+
emissions = candidate
|
|
875
|
+
return [candidate, false] as const
|
|
876
|
+
}).pipe(
|
|
877
|
+
Effect.flatMap(([selected, discard]) =>
|
|
878
|
+
discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)
|
|
879
|
+
)
|
|
880
|
+
)
|
|
881
|
+
)
|
|
882
|
+
)
|
|
883
|
+
})
|
|
884
|
+
return {
|
|
885
|
+
emit: (event) =>
|
|
886
|
+
Effect.suspend(() =>
|
|
887
|
+
emissions === undefined || emissions === EmissionsClosed
|
|
888
|
+
? Effect.void
|
|
889
|
+
: PubSub.publish(emissions, event).pipe(Effect.asVoid)
|
|
890
|
+
),
|
|
891
|
+
close: () => {
|
|
892
|
+
const observed = emissions
|
|
893
|
+
emissions = EmissionsClosed
|
|
894
|
+
return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed)
|
|
895
|
+
},
|
|
896
|
+
stream: Stream.unwrap(
|
|
897
|
+
getOrCreate.pipe(
|
|
898
|
+
Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))
|
|
899
|
+
)
|
|
900
|
+
)
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
export const childlessRuntime: ChildRuntime = {
|
|
905
|
+
close: () => Effect.void,
|
|
906
|
+
spawn: (() => Effect.die(new Error("Childless machine logic cannot spawn a process"))) as ProcessSpawn,
|
|
907
|
+
get: () => Effect.succeed(Option.none()),
|
|
908
|
+
changes: () => noChildChanges,
|
|
909
|
+
sendTo: () => Effect.void,
|
|
910
|
+
stop: () => Effect.void,
|
|
911
|
+
owned: {
|
|
912
|
+
spawn: () => Effect.die(new Error("Childless machine logic cannot spawn an owned process")),
|
|
913
|
+
stopAll: () => Effect.void,
|
|
914
|
+
stopPaths: () => undefined
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
export const makeChildRuntimeSync = (
|
|
919
|
+
self: ProcessAddress<any>,
|
|
920
|
+
runtime: ProcessRuntime,
|
|
921
|
+
services?: Context.Context<any>,
|
|
922
|
+
sendAcknowledged?: (
|
|
923
|
+
event: unknown
|
|
924
|
+
) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
|
|
925
|
+
): ChildRuntime => {
|
|
926
|
+
// Child-registry decisions are synchronous and every access below runs in
|
|
927
|
+
// one Effect.sync / Effect.suspend step. Keep the unobserved representation
|
|
928
|
+
// compact; selector-specific handoffs are installed only while
|
|
929
|
+
// childChanges streams are running.
|
|
930
|
+
const registry: ChildRegistry = {
|
|
931
|
+
closed: false,
|
|
932
|
+
children: new Map(),
|
|
933
|
+
observers: undefined,
|
|
934
|
+
scope: undefined
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
const close = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> =>
|
|
938
|
+
Effect.suspend(() => {
|
|
939
|
+
if (registry.closed) {
|
|
940
|
+
return Effect.void
|
|
941
|
+
}
|
|
942
|
+
registry.closed = true
|
|
943
|
+
if (registry.scope === undefined) {
|
|
944
|
+
return Effect.void
|
|
945
|
+
}
|
|
946
|
+
const finalizers = Scope.closeUnsafe(registry.scope, exit)
|
|
947
|
+
let first: Effect.Effect<void> | undefined
|
|
948
|
+
let rest: Array<Effect.Effect<void>> | undefined
|
|
949
|
+
for (const entry of registry.children.values()) {
|
|
950
|
+
if (entry._tag !== "Started") {
|
|
951
|
+
continue
|
|
952
|
+
}
|
|
953
|
+
if (first === undefined) {
|
|
954
|
+
first = entry.ref.stop
|
|
955
|
+
} else {
|
|
956
|
+
rest ??= [first]
|
|
957
|
+
rest.push(entry.ref.stop)
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
if (finalizers !== undefined) {
|
|
961
|
+
if (first === undefined) {
|
|
962
|
+
first = finalizers
|
|
963
|
+
} else {
|
|
964
|
+
rest ??= [first]
|
|
965
|
+
rest.push(finalizers)
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
const cleanup = rest ?? first
|
|
969
|
+
return cleanup === undefined
|
|
970
|
+
? Effect.void
|
|
971
|
+
: Array.isArray(cleanup)
|
|
972
|
+
? Effect.all(cleanup, { concurrency: "unbounded", discard: true })
|
|
973
|
+
: cleanup
|
|
974
|
+
})
|
|
975
|
+
|
|
976
|
+
const unregister = (
|
|
977
|
+
key: ChildKey,
|
|
978
|
+
token: symbol
|
|
979
|
+
): Effect.Effect<void> => Effect.sync(() => unregisterChild(registry, key, token))
|
|
980
|
+
|
|
981
|
+
const register = (
|
|
982
|
+
key: ChildKey,
|
|
983
|
+
token: symbol,
|
|
984
|
+
ref: MachineRef<any, any, any, any>,
|
|
985
|
+
descriptor: ChildDescriptor | undefined
|
|
986
|
+
): Effect.Effect<boolean> => Effect.sync(() => registerChild(registry, key, token, ref, descriptor))
|
|
987
|
+
|
|
988
|
+
const get: ChildRuntime["get"] = (child) => {
|
|
989
|
+
const id = typeof child === "string" ? child : child.id
|
|
990
|
+
return Effect.sync(() => {
|
|
991
|
+
if (registry.closed) {
|
|
992
|
+
return Option.none()
|
|
993
|
+
}
|
|
994
|
+
const entry = registry.children.get(id)
|
|
995
|
+
return entry !== undefined && matchesChild(entry, child)
|
|
996
|
+
? Option.some(entry.ref)
|
|
997
|
+
: Option.none()
|
|
998
|
+
})
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const changes: ChildRuntime["changes"] = (child) => {
|
|
1002
|
+
const id = typeof child === "string" ? child : child.id
|
|
1003
|
+
return Stream.fromChannel(
|
|
1004
|
+
Channel.fromTransform((_, streamScope) =>
|
|
1005
|
+
Effect.sync((): ChildObserver => ({ child, id, values: undefined, waiter: undefined })).pipe(
|
|
1006
|
+
Effect.flatMap((observer) => {
|
|
1007
|
+
const removeObserver = Effect.sync(() => {
|
|
1008
|
+
if (registry.observers !== undefined) {
|
|
1009
|
+
registry.observers.delete(observer)
|
|
1010
|
+
if (registry.observers.size === 0) {
|
|
1011
|
+
registry.observers = undefined
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
observer.values = undefined
|
|
1015
|
+
observer.waiter = undefined
|
|
1016
|
+
})
|
|
1017
|
+
return Scope.addFinalizer(streamScope, removeObserver).pipe(
|
|
1018
|
+
Effect.andThen(
|
|
1019
|
+
Effect.sync(() => {
|
|
1020
|
+
if (!registry.closed && streamScope.state._tag !== "Closed") {
|
|
1021
|
+
registry.observers ??= new Set()
|
|
1022
|
+
registry.observers.add(observer)
|
|
1023
|
+
}
|
|
1024
|
+
offerChildObservation(observer, selectRegistryChild(registry, id, child))
|
|
1025
|
+
})
|
|
1026
|
+
),
|
|
1027
|
+
Effect.as(takeChildObservations(observer))
|
|
1028
|
+
)
|
|
1029
|
+
})
|
|
1030
|
+
)
|
|
1031
|
+
)
|
|
1032
|
+
)
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
const sendTo = (
|
|
1036
|
+
child: ChildSelector,
|
|
1037
|
+
event: unknown,
|
|
1038
|
+
source?: Inspection.Subject,
|
|
1039
|
+
causedBy?: Inspection.Causation
|
|
1040
|
+
): Effect.Effect<void, StoppedError> => {
|
|
1041
|
+
const id = typeof child === "string" ? child : child.id
|
|
1042
|
+
return Effect.suspend(() => {
|
|
1043
|
+
if (registry.closed) {
|
|
1044
|
+
return Effect.void
|
|
1045
|
+
}
|
|
1046
|
+
const entry = registry.children.get(id)
|
|
1047
|
+
return entry !== undefined && matchesChild(entry, child)
|
|
1048
|
+
? sendMachineTarget(entry.ref, event, source, causedBy)
|
|
1049
|
+
: Effect.void
|
|
1050
|
+
})
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
const stop = (child: ChildSelector): Effect.Effect<void> => {
|
|
1054
|
+
const id = typeof child === "string" ? child : child.id
|
|
1055
|
+
return Effect.suspend(() => {
|
|
1056
|
+
if (registry.closed) {
|
|
1057
|
+
return Effect.void
|
|
1058
|
+
}
|
|
1059
|
+
const entry = registry.children.get(id)
|
|
1060
|
+
return entry !== undefined && matchesChild(entry, child)
|
|
1061
|
+
? entry.ref.stop
|
|
1062
|
+
: Effect.void
|
|
1063
|
+
})
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
function spawn<const Child extends ChildMachine.Any>(
|
|
1067
|
+
child: Child & ChildMachine.Executable<Child> & ChildMachine.ParentCompatibility<Child, unknown>,
|
|
1068
|
+
...options: ChildMachine.SpawnArgs<Child>
|
|
1069
|
+
): Effect.Effect<
|
|
1070
|
+
ChildMachine.Ref<Child>,
|
|
1071
|
+
ChildAlreadyExistsError | ChildMachine.StartError<Child>,
|
|
1072
|
+
ChildMachine.StartRequirements<Child>
|
|
1073
|
+
>
|
|
1074
|
+
function spawn<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
|
|
1075
|
+
logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>
|
|
1076
|
+
): Effect.Effect<
|
|
1077
|
+
MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
|
|
1078
|
+
ChildInitialError,
|
|
1079
|
+
Exclude<ChildRequirements, Scope.Scope>
|
|
1080
|
+
>
|
|
1081
|
+
function spawn<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
|
|
1082
|
+
logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>,
|
|
1083
|
+
spawnOptions: {
|
|
1084
|
+
readonly id: string
|
|
1085
|
+
readonly descriptor?: ChildDescriptor
|
|
1086
|
+
readonly onOutcome?: (
|
|
1087
|
+
outcome: RuntimeOutcome<ChildState, ChildError, ChildOutput>
|
|
1088
|
+
) => Effect.Effect<void>
|
|
1089
|
+
readonly [activeSnapshotObserver]?: (
|
|
1090
|
+
snapshot: Extract<RuntimeSnapshot<ChildState, ChildError, ChildOutput>, { readonly status: "active" }>
|
|
1091
|
+
) => Effect.Effect<void>
|
|
1092
|
+
readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
1093
|
+
}
|
|
1094
|
+
): Effect.Effect<
|
|
1095
|
+
MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
|
|
1096
|
+
ChildAlreadyExistsError | ChildInitialError,
|
|
1097
|
+
Exclude<ChildRequirements, Scope.Scope>
|
|
1098
|
+
>
|
|
1099
|
+
function spawn(
|
|
1100
|
+
logicOrChild: ProcessLogic<any, any, any, any, any, any> | ChildMachine.Any,
|
|
1101
|
+
options?: {
|
|
1102
|
+
readonly id: string
|
|
1103
|
+
readonly descriptor?: ChildDescriptor
|
|
1104
|
+
readonly onOutcome?: (
|
|
1105
|
+
outcome: RuntimeOutcome<any, any, any>
|
|
1106
|
+
) => Effect.Effect<void>
|
|
1107
|
+
readonly [activeSnapshotObserver]?: (
|
|
1108
|
+
snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
|
|
1109
|
+
) => Effect.Effect<void>
|
|
1110
|
+
readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
1111
|
+
} | { readonly input?: unknown }
|
|
1112
|
+
): Effect.Effect<MachineRef<any, any, any, any>, any, any> {
|
|
1113
|
+
const descriptor = typeof logicOrChild === "object" && logicOrChild !== null &&
|
|
1114
|
+
ChildMachineLogicTypeId in logicOrChild
|
|
1115
|
+
? logicOrChild as ChildMachine.Any
|
|
1116
|
+
: undefined
|
|
1117
|
+
const logic = descriptor === undefined
|
|
1118
|
+
? logicOrChild as ProcessLogic<any, any, any, any, any, any>
|
|
1119
|
+
: descriptor[ChildMachineLogicTypeId](
|
|
1120
|
+
(options as { readonly input?: unknown } | undefined)?.input
|
|
1121
|
+
) as unknown as ProcessLogic<any, any, any, any, any, any>
|
|
1122
|
+
const spawnOptions = descriptor === undefined
|
|
1123
|
+
? options as {
|
|
1124
|
+
readonly id: string
|
|
1125
|
+
readonly descriptor?: ChildDescriptor
|
|
1126
|
+
readonly onOutcome?: (outcome: RuntimeOutcome<any, any, any>) => Effect.Effect<void>
|
|
1127
|
+
readonly [activeSnapshotObserver]?: (
|
|
1128
|
+
snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
|
|
1129
|
+
) => Effect.Effect<void>
|
|
1130
|
+
readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
|
|
1131
|
+
} | undefined
|
|
1132
|
+
: { id: descriptor.id, descriptor }
|
|
1133
|
+
const token = Symbol()
|
|
1134
|
+
const key = spawnOptions?.id ?? token
|
|
1135
|
+
let startedChild: MachineRef<any, any, any, any> | undefined
|
|
1136
|
+
return Effect.suspend(() => {
|
|
1137
|
+
if (registry.closed) {
|
|
1138
|
+
return Effect.interrupt
|
|
1139
|
+
}
|
|
1140
|
+
if (typeof key === "string" && registry.children.has(key)) {
|
|
1141
|
+
return Effect.fail(new ChildAlreadyExistsError({ id: key }))
|
|
1142
|
+
}
|
|
1143
|
+
registry.scope ??= Scope.makeUnsafe("parallel")
|
|
1144
|
+
registry.children.set(key, { _tag: "Starting", token })
|
|
1145
|
+
return runtime.start(logic, {
|
|
1146
|
+
detached: true,
|
|
1147
|
+
...(spawnOptions?.id === undefined ? undefined : { id: spawnOptions.id }),
|
|
1148
|
+
...(spawnOptions?.onOutcome === undefined ? undefined : { onOutcome: spawnOptions.onOutcome }),
|
|
1149
|
+
...(spawnOptions?.[activeSnapshotObserver] === undefined
|
|
1150
|
+
? undefined
|
|
1151
|
+
: { onSnapshot: spawnOptions[activeSnapshotObserver] }),
|
|
1152
|
+
...(spawnOptions?.[sendParentOverride] === undefined
|
|
1153
|
+
? undefined
|
|
1154
|
+
: { sendParent: spawnOptions[sendParentOverride] }),
|
|
1155
|
+
onReady: (child, requestChildStop) =>
|
|
1156
|
+
Effect.sync(() => {
|
|
1157
|
+
startedChild = child
|
|
1158
|
+
}).pipe(
|
|
1159
|
+
Effect.andThen(register(key, token, child, spawnOptions?.descriptor)),
|
|
1160
|
+
Effect.flatMap((registered) => registered ? Effect.void : requestChildStop)
|
|
1161
|
+
),
|
|
1162
|
+
onStop: unregister(key, token),
|
|
1163
|
+
parent: self,
|
|
1164
|
+
runtime,
|
|
1165
|
+
origin: { _tag: "Spawn", address: spawnOptions?.id }
|
|
1166
|
+
}).pipe(
|
|
1167
|
+
Effect.onExit((exit) =>
|
|
1168
|
+
Exit.isFailure(exit)
|
|
1169
|
+
? unregister(key, token).pipe(
|
|
1170
|
+
Effect.andThen(startedChild === undefined ? Effect.void : startedChild.stop)
|
|
1171
|
+
)
|
|
1172
|
+
: Effect.void
|
|
1173
|
+
),
|
|
1174
|
+
Scope.provide(registry.scope)
|
|
1175
|
+
)
|
|
1176
|
+
})
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
return {
|
|
1180
|
+
close,
|
|
1181
|
+
spawn,
|
|
1182
|
+
get,
|
|
1183
|
+
changes,
|
|
1184
|
+
sendTo,
|
|
1185
|
+
stop,
|
|
1186
|
+
owned: new OwnedChildRuntimeImpl(registry, self, runtime, services, sendAcknowledged)
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
export const makeChildRuntime = (
|
|
1191
|
+
self: ProcessAddress<any>,
|
|
1192
|
+
runtime: ProcessRuntime,
|
|
1193
|
+
services?: Context.Context<any>,
|
|
1194
|
+
sendAcknowledged?: (
|
|
1195
|
+
event: unknown
|
|
1196
|
+
) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
|
|
1197
|
+
): Effect.Effect<ChildRuntime> => Effect.sync(() => makeChildRuntimeSync(self, runtime, services, sendAcknowledged))
|
|
1198
|
+
|
|
1199
|
+
export type StartProcess = <
|
|
1200
|
+
State,
|
|
1201
|
+
Event,
|
|
1202
|
+
Error = never,
|
|
1203
|
+
Requirements = never,
|
|
1204
|
+
Output = never,
|
|
1205
|
+
InitialError = never
|
|
1206
|
+
>(
|
|
1207
|
+
logic: ProcessLogic<State, Event, Error, Requirements, Output, InitialError>,
|
|
1208
|
+
options: StartInternalOptions
|
|
1209
|
+
) => Effect.Effect<
|
|
1210
|
+
MachineRef<State, Event, Error, Output>,
|
|
1211
|
+
InitialError,
|
|
1212
|
+
Requirements
|
|
1213
|
+
>
|