@typeonce/effect-machine 0.32.0 → 0.34.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.
Files changed (108) hide show
  1. package/README.md +216 -635
  2. package/dist/Machine.d.ts +814 -545
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -8
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/childRegistry.d.ts +1 -1
  7. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  8. package/dist/internal/machine/cluster.d.ts +2 -50
  9. package/dist/internal/machine/cluster.d.ts.map +1 -1
  10. package/dist/internal/machine/cluster.js +4 -27
  11. package/dist/internal/machine/cluster.js.map +1 -1
  12. package/dist/internal/machine/clusterProtocol.d.ts +35 -0
  13. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
  14. package/dist/internal/machine/clusterProtocol.js +28 -0
  15. package/dist/internal/machine/clusterProtocol.js.map +1 -0
  16. package/dist/internal/machine/commandRuntime.d.ts +1 -1
  17. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  18. package/dist/internal/machine/configuration.d.ts +2 -1
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -45
  21. package/dist/internal/machine/configuration.js.map +1 -1
  22. package/dist/internal/machine/declaration.d.ts +17 -0
  23. package/dist/internal/machine/declaration.d.ts.map +1 -0
  24. package/dist/internal/machine/declaration.js +120 -0
  25. package/dist/internal/machine/declaration.js.map +1 -0
  26. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  27. package/dist/internal/machine/executionPlan.js +5 -4
  28. package/dist/internal/machine/executionPlan.js.map +1 -1
  29. package/dist/internal/machine/implementation.d.ts +34 -0
  30. package/dist/internal/machine/implementation.d.ts.map +1 -0
  31. package/dist/internal/machine/implementation.js +3 -0
  32. package/dist/internal/machine/implementation.js.map +1 -0
  33. package/dist/internal/machine/invocation.d.ts +1 -1
  34. package/dist/internal/machine/invocation.d.ts.map +1 -1
  35. package/dist/internal/machine/invocation.js +1 -1
  36. package/dist/internal/machine/invocation.js.map +1 -1
  37. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  38. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  39. package/dist/internal/machine/machine.d.ts +13 -2
  40. package/dist/internal/machine/machine.d.ts.map +1 -1
  41. package/dist/internal/machine/machine.js +149 -280
  42. package/dist/internal/machine/machine.js.map +1 -1
  43. package/dist/internal/machine/planner.d.ts.map +1 -1
  44. package/dist/internal/machine/planner.js +12 -11
  45. package/dist/internal/machine/planner.js.map +1 -1
  46. package/dist/internal/machine/process.d.ts +8 -7
  47. package/dist/internal/machine/process.d.ts.map +1 -1
  48. package/dist/internal/machine/process.js +16 -12
  49. package/dist/internal/machine/process.js.map +1 -1
  50. package/dist/internal/machine/runtime.d.ts +2 -230
  51. package/dist/internal/machine/runtime.d.ts.map +1 -1
  52. package/dist/internal/machine/runtime.js +8 -1857
  53. package/dist/internal/machine/runtime.js.map +1 -1
  54. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  55. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  56. package/dist/internal/machine/runtimeCompiled.js +867 -0
  57. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  58. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  59. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  60. package/dist/internal/machine/runtimeGeneric.js +471 -0
  61. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  62. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  63. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeProtocol.js +561 -0
  65. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  66. package/dist/internal/machine/targetReference.d.ts +15 -0
  67. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  68. package/dist/internal/machine/targetReference.js +31 -0
  69. package/dist/internal/machine/targetReference.js.map +1 -0
  70. package/dist/internal/machine/topology.d.ts.map +1 -1
  71. package/dist/internal/machine/topology.js +2 -1
  72. package/dist/internal/machine/topology.js.map +1 -1
  73. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  74. package/dist/internal/testing/machine/finiteModel.js +38 -40
  75. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  76. package/dist/internal/testing/machine/probe.js +1 -1
  77. package/dist/internal/testing/machine/probe.js.map +1 -1
  78. package/dist/unstable/cluster/ClusterMachine.d.ts +5 -5
  79. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  80. package/dist/unstable/cluster/ClusterMachine.js +5 -17
  81. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  82. package/docs/agent-guide.md +66 -91
  83. package/docs/machine-review.md +19 -49
  84. package/docs/root-api.md +68 -23
  85. package/package.json +1 -1
  86. package/src/Machine.ts +1387 -2011
  87. package/src/internal/machine/childRegistry.ts +1 -1
  88. package/src/internal/machine/cluster.ts +7 -73
  89. package/src/internal/machine/clusterProtocol.ts +56 -0
  90. package/src/internal/machine/commandRuntime.ts +1 -1
  91. package/src/internal/machine/configuration.ts +53 -45
  92. package/src/internal/machine/declaration.ts +140 -0
  93. package/src/internal/machine/executionPlan.ts +6 -5
  94. package/src/internal/machine/implementation.ts +41 -0
  95. package/src/internal/machine/invocation.ts +3 -3
  96. package/src/internal/machine/invocationDefinition.ts +1 -1
  97. package/src/internal/machine/machine.ts +210 -389
  98. package/src/internal/machine/planner.ts +54 -35
  99. package/src/internal/machine/process.ts +40 -33
  100. package/src/internal/machine/runtime.ts +20 -3037
  101. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  102. package/src/internal/machine/runtimeGeneric.ts +799 -0
  103. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  104. package/src/internal/machine/targetReference.ts +40 -0
  105. package/src/internal/machine/topology.ts +2 -1
  106. package/src/internal/testing/machine/finiteModel.ts +42 -43
  107. package/src/internal/testing/machine/probe.ts +1 -1
  108. package/src/unstable/cluster/ClusterMachine.ts +9 -17
@@ -1,3047 +1,30 @@
1
- /**
2
- * Internal machine process runtime helpers.
3
- *
4
- * @since 0.4.0
5
- */
1
+ /** Local process startup and execution strategy selection. */
6
2
 
7
- import * as Cause from "effect/Cause"
8
- import * as Channel from "effect/Channel"
9
- import * as Context from "effect/Context"
10
3
  import * as Deferred from "effect/Deferred"
11
4
  import * as Effect from "effect/Effect"
12
- import * as Exit from "effect/Exit"
13
- import * as Fiber from "effect/Fiber"
14
- import * as Option from "effect/Option"
15
- import * as PubSub from "effect/PubSub"
16
- import * as Queue from "effect/Queue"
17
- import * as Scope from "effect/Scope"
18
5
  import * as Stream from "effect/Stream"
19
- import * as SynchronizedRef from "effect/SynchronizedRef"
20
- import type * as Take from "effect/Take"
21
- import type { RuntimeOutcome as PublicRuntimeOutcome, RuntimeSnapshot as PublicRuntimeSnapshot } from "../../Machine.js"
22
- import type { ChildMachine, Inspection, Machine as MachineDefinition, MachineTarget } from "../../Machine.js"
23
- import {
24
- type ChildDescriptor,
25
- type ChildEntry,
26
- type ChildKey,
27
- type ChildObserver,
28
- type ChildRegistry,
29
- type ChildSelector,
30
- matchesChild,
31
- offerChildObservation,
32
- registerChild,
33
- selectRegistryChild,
34
- takeChildObservations,
35
- unregisterChild
36
- } from "./childRegistry.js"
37
- import { ChildAlreadyExistsError, StoppedError } from "./errors.js"
38
6
  import * as InspectionRuntime from "./inspectionRuntime.js"
39
- import { ChildMachineLogicTypeId } from "./symbols.js"
40
-
41
- /** @internal */
42
- export const activeSnapshotObserver: unique symbol = Symbol.for("effect/Machine/activeSnapshotObserver")
43
-
44
- /** @internal */
45
- export const sendParentOverride: unique symbol = Symbol.for("effect/Machine/sendParentOverride")
46
-
47
- /** @internal */
48
- export const acknowledgedSend: unique symbol = Symbol.for("effect/Machine/acknowledgedSend")
49
-
50
- /** @internal */
51
- export interface AcknowledgedDelivery<State> {
52
- readonly before: State
53
- readonly plan: unknown
54
- readonly after: State
55
- }
56
-
57
- const AcknowledgedMessageTypeId: unique symbol = Symbol("effect/Machine/AcknowledgedMessage")
58
-
59
- /** @internal */
60
- export interface AcknowledgedMessage<Event> {
61
- readonly [AcknowledgedMessageTypeId]: true
62
- readonly event: Event
63
- readonly deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
64
- readonly inspection?: InspectedDelivery
65
- }
66
-
67
- /** @internal */
68
- export type ProcessMessage<Event> = Event | AcknowledgedMessage<Event>
69
-
70
- /** @internal */
71
- export const isAcknowledgedMessage = <Event>(
72
- message: ProcessMessage<Event>
73
- ): message is AcknowledgedMessage<Event> =>
74
- typeof message === "object" && message !== null && AcknowledgedMessageTypeId in message
75
-
76
- /** @internal */
77
- export const messageEvent = <Event>(message: ProcessMessage<Event>): Event =>
78
- isAcknowledgedMessage(message) ? message.event : message
79
-
80
- const succeedAcknowledgedMessage = <State>(
81
- message: ProcessMessage<unknown> | undefined,
82
- delivery: AcknowledgedDelivery<State>
83
- ): void => {
84
- if (message !== undefined && isAcknowledgedMessage(message)) {
85
- if (message.deferred !== undefined) {
86
- Deferred.doneUnsafe(message.deferred, Effect.succeed(delivery as AcknowledgedDelivery<unknown>))
87
- }
88
- message.inspection?.complete(delivery as AcknowledgedDelivery<unknown>)
89
- }
90
- }
91
-
92
- const failAcknowledgedMessage = (
93
- message: ProcessMessage<unknown> | undefined,
94
- cause: Cause.Cause<unknown>
95
- ): void => {
96
- if (message !== undefined && isAcknowledgedMessage(message)) {
97
- if (message.deferred !== undefined) Deferred.doneUnsafe(message.deferred, Effect.failCause(cause))
98
- }
99
- }
100
-
101
- const stopAcknowledgedMessage = (message: ProcessMessage<unknown> | undefined): void => {
102
- if (message !== undefined && isAcknowledgedMessage(message)) {
103
- if (message.deferred !== undefined) Deferred.doneUnsafe(message.deferred, Effect.fail(new StoppedError()))
104
- }
105
- }
106
-
107
- interface InspectedDelivery {
108
- readonly deliveryId: number
109
- readonly macrostepId: number
110
- readonly source: Inspection.Subject | undefined
111
- readonly event: unknown
112
- readonly causedBy: Inspection.Causation | undefined
113
- readonly complete: (delivery: AcknowledgedDelivery<unknown>) => void
114
- }
115
-
116
- type InspectedOffer<Event> = (
117
- event: Event,
118
- source: Inspection.Subject | undefined,
119
- causedBy: Inspection.Causation | undefined,
120
- deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
121
- ) => Effect.Effect<void, StoppedError>
122
-
123
- export type RuntimeSnapshot<State, Error = never, Output = never> = PublicRuntimeSnapshot<State, Error, Output>
124
-
125
- interface VersionedSnapshot<State, Error, Output> {
126
- readonly revision: number
127
- readonly snapshot: RuntimeSnapshot<State, Error, Output>
128
- readonly terminalizing: boolean
129
- readonly changes: PubSub.PubSub<Take.Take<VersionedSnapshot<State, Error, Output>>> | undefined
130
- /** Compiled drains retain one non-empty publication chunk until their next Effect boundary. */
131
- pendingChanges?: VersionedSnapshotBatch<State, Error, Output> | undefined
132
- }
133
-
134
- type VersionedSnapshotBatch<State, Error, Output> = [
135
- VersionedSnapshot<State, Error, Output>,
136
- ...Array<VersionedSnapshot<State, Error, Output>>
137
- ]
138
-
139
- export type RuntimeOutcome<State, Error = never, Output = never> = PublicRuntimeOutcome<State, Error, Output>
140
-
141
- export interface MachineRef<out State, in Event, out Error = never, out Output = never, out Emitted = never> {
142
- readonly id: string
143
- readonly sessionId: string
144
- readonly state: Effect.Effect<State>
145
- readonly snapshot: Effect.Effect<RuntimeSnapshot<State, Error, Output>>
146
- readonly changes: Stream.Stream<RuntimeSnapshot<State, Error, Output>>
147
- readonly emissions: Stream.Stream<Emitted>
148
- readonly join: Effect.Effect<Output, Error | StoppedError>
149
- readonly stop: Effect.Effect<void>
150
- readonly send: (event: Event) => Effect.Effect<void, StoppedError>
151
- /** @internal */
152
- readonly inspectionSubject?: Inspection.Subject
153
- /** @internal */
154
- readonly sendInspected?: ProcessAddress<Event>["sendInspected"]
155
- readonly [acknowledgedSend]?: (
156
- event: Event
157
- ) => Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>
158
- readonly child: (child: any) => Effect.Effect<Option.Option<any>>
159
- readonly childChanges: (child: any) => Stream.Stream<Option.Option<any>>
160
- }
161
-
162
- export interface PreparedProcess<
163
- out State,
164
- in Event,
165
- out Error,
166
- out Output,
167
- out Emitted,
168
- out StartError,
169
- StartRequirements
170
- > {
171
- readonly id: string
172
- readonly sessionId: string
173
- readonly changes: Stream.Stream<RuntimeSnapshot<State, Error, Output>, StartError>
174
- readonly emissions: Stream.Stream<Emitted>
175
- readonly inspection: Stream.Stream<Inspection.Event>
176
- readonly start: Effect.Effect<MachineRef<State, Event, Error, Output, Emitted>, StartError, StartRequirements>
177
- }
178
-
179
- interface ProcessAddress<in Event> {
180
- readonly id: string
181
- readonly sessionId: string
182
- readonly inspectionSubject?: Inspection.Subject
183
- readonly stop: Effect.Effect<void>
184
- readonly send: (event: Event) => Effect.Effect<void, StoppedError>
185
- readonly sendInspected?: (
186
- event: Event,
187
- source: Inspection.Subject | undefined,
188
- causedBy: Inspection.Causation | undefined
189
- ) => Effect.Effect<void, StoppedError>
190
- readonly [acknowledgedSend]?: (
191
- event: Event
192
- ) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
193
- }
194
-
195
- const isMachineTarget = (value: unknown): value is MachineTarget<unknown> =>
196
- typeof value === "object" && value !== null && "send" in value && typeof value.send === "function"
197
-
198
- const sendMachineTarget = (
199
- target: MachineTarget<unknown>,
200
- event: unknown,
201
- source: Inspection.Subject | undefined,
202
- causedBy: Inspection.Causation | undefined
203
- ): Effect.Effect<void, StoppedError> =>
204
- "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function"
205
- ? target.sendInspected(event, source, causedBy)
206
- : target.send(event)
207
-
208
- export interface ProcessScope<Event> {
209
- readonly self: ProcessAddress<Event>
210
- readonly parent: ProcessAddress<unknown> | undefined
211
- readonly spawn: ProcessSpawn<Event>
212
- readonly sendParent: (event: unknown) => Effect.Effect<void, StoppedError>
213
- readonly emit: (event: unknown) => Effect.Effect<void>
214
- readonly sendTo: {
215
- <TargetEvent>(target: MachineTarget<TargetEvent>, event: TargetEvent): Effect.Effect<void, StoppedError>
216
- (child: ChildSelector, event: unknown): Effect.Effect<void, StoppedError>
217
- }
218
- readonly stopChild: (child: ChildSelector) => Effect.Effect<void>
219
- /** @internal */
220
- readonly failCause: (cause: Cause.Cause<unknown>) => Effect.Effect<void>
221
- /** @internal */
222
- readonly inspectInitial: (
223
- initialEntryPaths: ReadonlyArray<string>,
224
- microsteps?: ReadonlyArray<unknown>
225
- ) => void
226
- }
227
-
228
- export interface ProcessContext<State, Event> extends ProcessScope<Event> {
229
- readonly receive: Effect.Effect<Event>
230
- /** @internal */
231
- readonly poll?: Effect.Effect<Option.Option<Event>>
232
- /** @internal */
233
- readonly receiveMessage?: Effect.Effect<ProcessMessage<Event>>
234
- /** @internal */
235
- readonly pollMessage?: Effect.Effect<Option.Option<ProcessMessage<Event>>>
236
- /** @internal */
237
- readonly completeMessage?: (delivery: AcknowledgedDelivery<State>) => void
238
- readonly state: Effect.Effect<State>
239
- readonly setState: (state: State) => Effect.Effect<void>
240
- readonly updateState: <E, R>(
241
- f: (state: State) => Effect.Effect<State, E, R>
242
- ) => Effect.Effect<void, E, R>
243
- /** Present only when a compiled statechart is forced through the generic runtime. @internal */
244
- readonly ownedChildren?: OwnedChildRuntime
245
- }
246
-
247
- /**
248
- * Owner-local execution context for compiled statecharts.
249
- *
250
- * Unlike `ProcessContext`, synchronous mailbox and state operations do not
251
- * introduce an Effect boundary. The compiled drain still returns an Effect so
252
- * machine commands, invokes, observation callbacks, interruption, and the Effect
253
- * scheduler remain explicit at their actual boundaries.
254
- *
255
- * @internal
256
- */
257
- export interface CompiledProcessContext<State, Event> {
258
- readonly scope: ProcessScope<Event>
259
- readonly ownedChildren: OwnedChildRuntime
260
- readonly poll: () => Option.Option<Event>
261
- readonly pollMessage: () => Option.Option<ProcessMessage<Event>>
262
- readonly state: () => State
263
- readonly completeMessage: (delivery: AcknowledgedDelivery<State>) => void
264
- readonly commit: (state: State) => Effect.Effect<void> | undefined
265
- /**
266
- * Publishes the current synchronous segment before continuing with work that
267
- * may suspend, run user effects, or make the committed state observable.
268
- */
269
- readonly runAfterChanges: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
270
- executionState: unknown
271
- }
272
-
273
- type CompiledProcessInitial<State, Output> =
274
- | { readonly state: State; readonly done: false; readonly output: undefined }
275
- | { readonly state: State; readonly done: true; readonly output: Output }
276
- | {
277
- readonly state: State
278
- readonly done: boolean
279
- readonly output: Output | undefined
280
- readonly executionState: unknown
281
- }
282
-
283
- export type CompiledProcessDrain<State, Event, Error, Requirements, Output> =
284
- | {
285
- readonly _tag: "Process"
286
- readonly run: (
287
- context: ProcessContext<State, Event>
288
- ) => Effect.Effect<Option.Option<Output>, Error, Requirements>
289
- }
290
- | {
291
- readonly _tag: "Owned"
292
- readonly run: (
293
- context: CompiledProcessContext<State, Event>
294
- ) => Effect.Effect<Option.Option<Output>, Error, Requirements>
295
- }
296
-
297
- /**
298
- * The complete capability descriptor consumed by the compact process runtime.
299
- * Generic process logic omits this field entirely.
300
- *
301
- * @internal
302
- */
303
- export interface CompiledProcessExecution<
304
- State,
305
- Event,
306
- Error,
307
- Requirements,
308
- Output,
309
- InitialError
310
- > {
311
- readonly _tag: "Compiled"
312
- readonly childless: boolean
313
- readonly initial?: (
314
- scope: ProcessScope<Event>
315
- ) => Effect.Effect<CompiledProcessInitial<State, Output>, InitialError, Requirements>
316
- readonly initialSync?: (
317
- scope: ProcessScope<Event>
318
- ) => CompiledProcessInitial<State, Output>
319
- readonly drain: CompiledProcessDrain<State, Event, Error, Requirements, Output>
320
- }
321
-
322
- export type ProcessExecution<State, Event, Error, Requirements, Output, InitialError> =
323
- | {
324
- readonly _tag: "Childless"
325
- }
326
- | CompiledProcessExecution<State, Event, Error, Requirements, Output, InitialError>
327
-
328
- const executionIsChildless = (
329
- execution: ProcessExecution<any, any, any, any, any, any> | undefined
330
- ): boolean => execution?._tag === "Childless" || execution?.childless === true
331
-
332
- interface CompactProcessMailbox<Event> {
333
- items: Array<ProcessMessage<Event>> | undefined
334
- index: number
335
- closed: boolean
336
- }
337
-
338
- const offerCompactMailbox = <Event>(mailbox: CompactProcessMailbox<Event>, event: ProcessMessage<Event>): void => {
339
- const items = mailbox.items ?? []
340
- mailbox.items = items
341
- items.push(event)
342
- }
343
-
344
- const pollCompactMailbox = <Event>(mailbox: CompactProcessMailbox<Event>): Option.Option<ProcessMessage<Event>> => {
345
- if (mailbox.items === undefined) {
346
- return Option.none()
347
- }
348
- const event = mailbox.items[mailbox.index]!
349
- mailbox.index += 1
350
- if (mailbox.index === mailbox.items.length) {
351
- mailbox.items = undefined
352
- mailbox.index = 0
353
- }
354
- return Option.some(event)
355
- }
356
-
357
- const closeCompactMailbox = (mailbox: CompactProcessMailbox<unknown>): void => {
358
- if (mailbox.items !== undefined) {
359
- for (let index = mailbox.index; index < mailbox.items.length; index += 1) {
360
- stopAcknowledgedMessage(mailbox.items[index])
361
- }
362
- }
363
- mailbox.closed = true
364
- mailbox.items = undefined
365
- mailbox.index = 0
366
- }
367
-
368
- export interface ProcessLogic<
369
- State,
370
- Event,
371
- out Error = never,
372
- out Requirements = never,
373
- out Output = never,
374
- out InitialError = never
375
- > {
376
- /** @internal */
377
- readonly execution?: ProcessExecution<State, Event, Error, Requirements, Output, InitialError>
378
- /** @internal */
379
- readonly inspection?: {
380
- readonly kind: Inspection.Subject["kind"]
381
- readonly definition?: MachineDefinition.Any
382
- }
383
- initial(scope: ProcessScope<Event>): Effect.Effect<State, InitialError, Requirements>
384
- run(context: ProcessContext<State, Event>): Effect.Effect<Output, Error, Requirements>
385
- }
386
-
387
- export interface ProcessSpawn<OwnerEvent = unknown> {
388
- <const Child extends ChildMachine.Any>(
389
- child: Child & ChildMachine.Executable<Child> & ChildMachine.ParentCompatibility<Child, OwnerEvent>,
390
- ...options: ChildMachine.SpawnArgs<Child>
391
- ): Effect.Effect<
392
- ChildMachine.Ref<Child>,
393
- ChildAlreadyExistsError | ChildMachine.StartError<Child>,
394
- ChildMachine.StartRequirements<Child>
395
- >
396
- <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
397
- logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>
398
- ): Effect.Effect<
399
- MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
400
- ChildInitialError,
401
- Exclude<ChildRequirements, Scope.Scope>
402
- >
403
- <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
404
- logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>,
405
- options: {
406
- readonly id: string
407
- readonly descriptor?: ChildDescriptor
408
- readonly onOutcome?: (
409
- outcome: RuntimeOutcome<ChildState, ChildError, ChildOutput>
410
- ) => Effect.Effect<void>
411
- readonly [activeSnapshotObserver]?: (
412
- snapshot: Extract<RuntimeSnapshot<ChildState, ChildError, ChildOutput>, { readonly status: "active" }>
413
- ) => Effect.Effect<void>
414
- readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
415
- }
416
- ): Effect.Effect<
417
- MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
418
- ChildAlreadyExistsError | ChildInitialError,
419
- Exclude<ChildRequirements, Scope.Scope>
420
- >
421
- }
422
-
423
- export class MachineRuntime extends Context.Service<MachineRuntime, ProcessScope<any>>()(
424
- "effect/Machine/MachineRuntime"
425
- ) {}
426
-
427
- export const provideMachineRuntime = <A, E, R, Event>(
428
- effect: Effect.Effect<A, E, R>,
429
- scope: ProcessScope<Event>
430
- ): Effect.Effect<A, E, Exclude<R, MachineRuntime>> =>
431
- Effect.provideService(effect, MachineRuntime, scope as ProcessScope<any>)
432
-
433
- const classifyOutcome = <State, Error, Output>(
434
- snapshot: RuntimeSnapshot<State, Error, Output>
435
- ): RuntimeOutcome<State, Error, Output> | undefined => {
436
- switch (snapshot.status) {
437
- case "active": {
438
- return undefined
439
- }
440
- case "done": {
441
- return {
442
- _tag: "Done",
443
- output: snapshot.output,
444
- snapshot
445
- }
446
- }
447
- case "error": {
448
- const failure = snapshot.cause.reasons.find(Cause.isFailReason)
449
- if (failure !== undefined) {
450
- return {
451
- _tag: "Failure",
452
- error: failure.error,
453
- cause: snapshot.cause,
454
- snapshot
455
- }
456
- }
457
- const defect = snapshot.cause.reasons.find(Cause.isDieReason)
458
- if (defect !== undefined) {
459
- return {
460
- _tag: "Defect",
461
- defect: defect.defect,
462
- cause: snapshot.cause,
463
- snapshot
464
- }
465
- }
466
- const interrupted = snapshot.cause.reasons.find(Cause.isInterruptReason)
467
- if (interrupted !== undefined) {
468
- return {
469
- _tag: "Interrupted",
470
- cause: snapshot.cause,
471
- snapshot
472
- }
473
- }
474
- return {
475
- _tag: "Cause",
476
- cause: snapshot.cause,
477
- snapshot
478
- }
479
- }
480
- case "stopped": {
481
- return {
482
- _tag: "Stopped",
483
- snapshot
484
- }
485
- }
486
- }
487
- }
488
-
489
- const notifyActiveSnapshot = <State, Error, Output>(
490
- onSnapshot: (
491
- snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
492
- ) => Effect.Effect<void>,
493
- snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
494
- ): Effect.Effect<void> =>
495
- Effect.suspend(() => onSnapshot(snapshot)).pipe(
496
- Effect.exit,
497
- Effect.asVoid
498
- )
499
-
500
- export const watch = <State, Event, Error = never, Output = never>(
501
- ref: MachineRef<State, Event, Error, Output>
502
- ): Stream.Stream<RuntimeOutcome<State, Error, Output>> =>
503
- ref.changes.pipe(
504
- Stream.filter((snapshot) => snapshot.status !== "active"),
505
- Stream.map((snapshot) => classifyOutcome(snapshot)!),
506
- Stream.take(1)
507
- )
508
-
509
- interface ProcessRuntime {
510
- readonly nextSessionId: Effect.Effect<string>
511
- inspection?: InspectionRuntime.Runtime
512
- }
513
-
514
- const makeProcessRuntime: Effect.Effect<ProcessRuntime> = Effect.sync(() => {
515
- let sessionIdCounter = 0
516
- return {
517
- nextSessionId: Effect.sync(() => `machine:${sessionIdCounter++}`)
518
- }
519
- })
520
-
521
- const inspectionSubject = (
522
- logic: ProcessLogic<any, any, any, any, any, any>,
523
- id: string,
524
- sessionId: string
525
- ): Inspection.Subject => ({
526
- id,
527
- sessionId,
528
- kind: logic.inspection?.kind ?? "Logic"
529
- })
530
-
531
- const messageCausation = (
532
- message: ProcessMessage<unknown> | undefined,
533
- initializing: boolean
534
- ): Inspection.Causation | undefined =>
535
- initializing
536
- ? { _tag: "Initialization" }
537
- : message !== undefined && isAcknowledgedMessage(message) && message.inspection !== undefined
538
- ? { _tag: "Macrostep", macrostepId: message.inspection.macrostepId }
539
- : undefined
540
-
541
- const makeInspectedMessage = <Event>(
542
- inspection: InspectionRuntime.Runtime,
543
- subject: Inspection.Subject,
544
- event: Event,
545
- source: Inspection.Subject | undefined,
546
- causedBy: Inspection.Causation | undefined,
547
- deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
548
- ): AcknowledgedMessage<Event> => {
549
- const deliveryId = inspection.nextDeliveryId()
550
- const macrostepId = inspection.nextMacrostepId()
551
- const inspected: InspectedDelivery = {
552
- deliveryId,
553
- macrostepId,
554
- source,
555
- event,
556
- causedBy,
557
- complete: (delivery) => {
558
- const microsteps = InspectionRuntime.microsteps(delivery.plan)
559
- inspection.publishUnsafe({
560
- _tag: "EventProcessed",
561
- subject,
562
- macrostepId,
563
- deliveryId,
564
- source,
565
- event,
566
- before: { status: "active", state: delivery.before },
567
- after: { status: "active", state: delivery.after },
568
- handled: microsteps.some((microstep) => microstep.transitions.length > 0),
569
- configurationChanged: microsteps.some((microstep) => microstep.changed),
570
- microsteps
571
- })
572
- }
573
- }
574
- return {
575
- [AcknowledgedMessageTypeId]: true,
576
- event,
577
- ...(deferred === undefined ? undefined : { deferred }),
578
- inspection: inspected
579
- }
580
- }
581
-
582
- const publishInspectedSent = (
583
- inspection: InspectionRuntime.Runtime,
584
- subject: Inspection.Subject,
585
- message: ProcessMessage<unknown>
586
- ): void => {
587
- if (!isAcknowledgedMessage(message) || message.inspection === undefined) return
588
- const delivery = message.inspection
589
- inspection.publishUnsafe({
590
- _tag: "EventSent",
591
- subject,
592
- deliveryId: delivery.deliveryId,
593
- source: delivery.source,
594
- target: InspectionRuntime.endpoint(subject),
595
- event: delivery.event,
596
- causedBy: delivery.causedBy
597
- })
598
- }
599
-
600
- interface StartInternalOptions {
601
- readonly detached?: boolean
602
- readonly id?: string
603
- readonly sessionId?: string
604
- readonly emissions?: EmissionRuntime
605
- readonly onOutcome?: (outcome: RuntimeOutcome<any, any, any>) => Effect.Effect<void>
606
- readonly onSnapshot?: (
607
- snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
608
- ) => Effect.Effect<void>
609
- readonly onReady?: (
610
- ref: MachineRef<any, any, any, any>,
611
- requestStop: Effect.Effect<void>
612
- ) => Effect.Effect<void>
613
- readonly onReadySync?: (ref: MachineRef<any, any, any, any>) => boolean
614
- readonly onStop?: Effect.Effect<void>
615
- readonly onStopSync?: () => void
616
- readonly skipStoppedOutcome?: boolean
617
- readonly parent?: ProcessAddress<unknown>
618
- readonly runtime: ProcessRuntime
619
- readonly sendParent?: (event: unknown) => Effect.Effect<void, StoppedError>
620
- readonly origin?: Inspection.Origin
621
- readonly activity?: {
622
- readonly id: string
623
- readonly owner: Inspection.Subject
624
- readonly ownerPath: string
625
- readonly kind: Inspection.Activity["kind"]
626
- }
627
- readonly inspectionRoot?: boolean
628
- }
629
-
630
- /** @internal */
631
- export interface OwnedChildSpawnOptions {
632
- readonly key: string
633
- readonly path: string
634
- readonly id: string
635
- readonly duplicateId: string
636
- readonly descriptor?: ChildDescriptor
637
- readonly onOutcome: (
638
- isCurrent: () => boolean,
639
- outcome: RuntimeOutcome<any, any, any>,
640
- activitySessionId: string | undefined
641
- ) => Effect.Effect<void>
642
- readonly onSnapshot?: (
643
- isCurrent: () => boolean,
644
- snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
645
- ) => Effect.Effect<void>
646
- readonly sendParent: (
647
- isCurrent: () => boolean,
648
- event: unknown
649
- ) => Effect.Effect<void, StoppedError>
650
- readonly activityKind?: Inspection.Activity["kind"]
651
- }
652
-
653
- /** @internal */
654
- export interface OwnedChildRuntime {
655
- readonly spawn: (
656
- makeLogic: () => ProcessLogic<any, any, any, any, any, any>,
657
- options: OwnedChildSpawnOptions
658
- ) => Effect.Effect<void, any, any>
659
- readonly stopAll: () => Effect.Effect<void>
660
- readonly stopPaths: (paths: ReadonlyArray<string>) => Effect.Effect<void> | undefined
661
- }
662
-
663
- interface ChildRuntime {
664
- readonly close: <A, E>(exit: Exit.Exit<A, E>) => Effect.Effect<void>
665
- readonly spawn: ProcessSpawn
666
- readonly get: <ChildState, ChildEvent, ChildError, ChildOutput>(
667
- child: ChildSelector
668
- ) => Effect.Effect<Option.Option<MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>>>
669
- readonly changes: <ChildState, ChildEvent, ChildError, ChildOutput>(
670
- child: ChildSelector
671
- ) => Stream.Stream<Option.Option<MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>>>
672
- readonly sendTo: (
673
- child: ChildSelector,
674
- event: unknown,
675
- source?: Inspection.Subject,
676
- causedBy?: Inspection.Causation
677
- ) => Effect.Effect<void, StoppedError>
678
- readonly stop: (child: ChildSelector) => Effect.Effect<void>
679
- readonly owned: OwnedChildRuntime
680
- }
681
-
682
- class OwnedChildRuntimeImpl implements OwnedChildRuntime {
683
- private scopedServices: Context.Context<any> | undefined
684
-
685
- constructor(
686
- private readonly registry: ChildRegistry,
687
- private readonly self: ProcessAddress<any>,
688
- private readonly runtime: ProcessRuntime,
689
- private readonly services?: Context.Context<any>,
690
- private readonly sendAcknowledged?: (
691
- event: unknown
692
- ) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
693
- ) {}
694
-
695
- private has(key: string): boolean {
696
- for (const entry of this.registry.children.values()) {
697
- if (entry.ownerActive && entry.ownerKey === key) return true
698
- }
699
- return false
700
- }
701
-
702
- private stopEntry(entry: ChildEntry): Effect.Effect<void> {
703
- entry.ownerActive = false
704
- return entry._tag === "Started" ? entry.ref.stop : Effect.void
705
- }
706
-
707
- spawn(
708
- makeLogic: () => ProcessLogic<any, any, any, any, any, any>,
709
- options: OwnedChildSpawnOptions
710
- ): Effect.Effect<void, any, any> {
711
- const token = Symbol()
712
- let startedChild: MachineRef<any, any, any, any> | undefined
713
- const isCurrent = (): boolean => {
714
- const entry = this.registry.children.get(options.id)
715
- return entry?.token === token && entry.ownerKey === options.key && entry.ownerActive === true
716
- }
717
- return Effect.suspend(() => {
718
- if (this.registry.closed) return Effect.interrupt
719
- if (this.has(options.key) || this.registry.children.has(options.id)) {
720
- return Effect.fail(new ChildAlreadyExistsError({ id: options.duplicateId }))
721
- }
722
- const logic = makeLogic()
723
- const scope = this.registry.scope ??= Scope.makeUnsafe("parallel")
724
- this.registry.children.set(options.id, {
725
- _tag: "Starting",
726
- token,
727
- ownerKey: options.key,
728
- ownerPath: options.path,
729
- ownerActive: true
730
- })
731
- const parent: ProcessAddress<unknown> = {
732
- ...this.self,
733
- send: (event) => options.sendParent(isCurrent, event),
734
- sendInspected: (event, source, causedBy) =>
735
- isCurrent() ? sendMachineTarget(this.self, event, source, causedBy) : Effect.void,
736
- ...(this.sendAcknowledged === undefined
737
- ? undefined
738
- : {
739
- [acknowledgedSend]: (event: unknown) =>
740
- isCurrent()
741
- ? this.sendAcknowledged!(event)
742
- : Effect.interrupt
743
- })
744
- }
745
- const startOptions: StartInternalOptions = {
746
- detached: true,
747
- id: options.id,
748
- sendParent: (event) => options.sendParent(isCurrent, event),
749
- onOutcome: (outcome) => options.onOutcome(isCurrent, outcome, startedChild?.sessionId),
750
- ...(options.onSnapshot === undefined
751
- ? undefined
752
- : { onSnapshot: (snapshot) => options.onSnapshot!(isCurrent, snapshot) }),
753
- onReadySync: (child) => {
754
- startedChild = child
755
- return registerChild(this.registry, options.id, token, child, options.descriptor)
756
- },
757
- onStopSync: () => unregisterChild(this.registry, options.id, token),
758
- skipStoppedOutcome: true,
759
- parent,
760
- runtime: this.runtime,
761
- origin: { _tag: "Invoke", ownerPath: options.path, invokeId: options.duplicateId },
762
- ...(options.activityKind === undefined || this.runtime.inspection === undefined ||
763
- this.self.inspectionSubject === undefined
764
- ? undefined
765
- : {
766
- activity: {
767
- id: options.duplicateId,
768
- owner: this.self.inspectionSubject,
769
- ownerPath: options.path,
770
- kind: options.activityKind
771
- }
772
- })
773
- }
774
- const execution = logic.execution
775
- const synchronous = this.services !== undefined && options.onSnapshot === undefined &&
776
- execution?._tag === "Compiled" && execution.childless && execution.drain._tag === "Owned" &&
777
- execution.initialSync !== undefined
778
- const start = synchronous
779
- ? Effect.flatMap(
780
- this.runtime.nextSessionId,
781
- (sessionId) =>
782
- new CompiledProcess(
783
- logic,
784
- startOptions,
785
- this.scopedServices ??= Context.add(this.services!, Scope.Scope, scope),
786
- sessionId
787
- ).initializeCompiledSync()
788
- )
789
- : startLogicInternal(logic, startOptions)
790
- const guarded = start.pipe(
791
- Effect.onExit((exit) => {
792
- if (Exit.isSuccess(exit)) return Effect.void
793
- unregisterChild(this.registry, options.id, token)
794
- return startedChild === undefined ? Effect.void : startedChild.stop
795
- })
796
- )
797
- return (synchronous ? guarded : Scope.provide(guarded, scope)).pipe(Effect.asVoid)
798
- })
799
- }
800
-
801
- stopAll(): Effect.Effect<void> {
802
- return Effect.suspend(() => {
803
- const effects: Array<Effect.Effect<void>> = []
804
- for (const entry of this.registry.children.values()) {
805
- if (entry.ownerActive) effects.push(this.stopEntry(entry))
806
- }
807
- return effects.length === 0
808
- ? Effect.void
809
- : effects.length === 1
810
- ? effects[0]!
811
- : Effect.all(effects, { concurrency: "unbounded", discard: true })
812
- })
813
- }
814
-
815
- stopPaths(paths: ReadonlyArray<string>): Effect.Effect<void> | undefined {
816
- if (paths.length === 0) return undefined
817
- const pathSet = new Set(paths)
818
- const effects: Array<Effect.Effect<void>> = []
819
- for (const entry of this.registry.children.values()) {
820
- if (entry.ownerActive && entry.ownerPath !== undefined && pathSet.has(entry.ownerPath)) {
821
- effects.push(this.stopEntry(entry))
822
- }
823
- }
824
- return effects.length === 0
825
- ? undefined
826
- : effects.length === 1
827
- ? effects[0]!
828
- : Effect.all(effects, { concurrency: "unbounded", discard: true })
829
- }
830
- }
831
-
832
- const noChildChanges = Stream.succeed(Option.none()).pipe(Stream.concat(Stream.never))
833
- const noParentSend = (_event: unknown): Effect.Effect<void, StoppedError> => Effect.void
834
- const noInspectInitial = (_paths: ReadonlyArray<string>, _microsteps?: ReadonlyArray<unknown>): void => {}
835
- const noCausation = (): Inspection.Causation | undefined => undefined
836
- const EmissionsClosed: unique symbol = Symbol("effect/Machine/EmissionsClosed")
837
-
838
- type LazyEmissions = PubSub.PubSub<unknown> | typeof EmissionsClosed | undefined
839
-
840
- interface EmissionRuntime {
841
- readonly emit: (event: unknown) => Effect.Effect<void>
842
- readonly close: () => Effect.Effect<void>
843
- readonly stream: Stream.Stream<unknown>
844
- }
845
-
846
- const makeEmissionRuntime = (): EmissionRuntime => {
847
- let emissions: LazyEmissions
848
- const getOrCreate: Effect.Effect<PubSub.PubSub<unknown> | undefined> = Effect.suspend(() => {
849
- const observed = emissions
850
- if (observed === EmissionsClosed) return Effect.succeed(undefined)
851
- if (observed !== undefined) return Effect.succeed(observed)
852
- return PubSub.unbounded<unknown>().pipe(
853
- Effect.flatMap((candidate) =>
854
- Effect.sync(() => {
855
- const latest = emissions
856
- if (latest === EmissionsClosed) return [undefined, true] as const
857
- if (latest !== undefined) return [latest, true] as const
858
- emissions = candidate
859
- return [candidate, false] as const
860
- }).pipe(
861
- Effect.flatMap(([selected, discard]) =>
862
- discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)
863
- )
864
- )
865
- )
866
- )
867
- })
868
- return {
869
- emit: (event) =>
870
- Effect.suspend(() =>
871
- emissions === undefined || emissions === EmissionsClosed
872
- ? Effect.void
873
- : PubSub.publish(emissions, event).pipe(Effect.asVoid)
874
- ),
875
- close: () => {
876
- const observed = emissions
877
- emissions = EmissionsClosed
878
- return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed)
879
- },
880
- stream: Stream.unwrap(
881
- getOrCreate.pipe(
882
- Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))
883
- )
884
- )
885
- }
886
- }
887
-
888
- const childlessRuntime: ChildRuntime = {
889
- close: () => Effect.void,
890
- spawn: (() => Effect.die(new Error("Childless machine logic cannot spawn a process"))) as ProcessSpawn,
891
- get: () => Effect.succeed(Option.none()),
892
- changes: () => noChildChanges,
893
- sendTo: () => Effect.void,
894
- stop: () => Effect.void,
895
- owned: {
896
- spawn: () => Effect.die(new Error("Childless machine logic cannot spawn an owned process")),
897
- stopAll: () => Effect.void,
898
- stopPaths: () => undefined
899
- }
900
- }
901
-
902
- const makeChildRuntimeSync = (
903
- self: ProcessAddress<any>,
904
- runtime: ProcessRuntime,
905
- services?: Context.Context<any>,
906
- sendAcknowledged?: (
907
- event: unknown
908
- ) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
909
- ): ChildRuntime => {
910
- // Child-registry decisions are synchronous and every access below runs in
911
- // one Effect.sync / Effect.suspend step. Keep the unobserved representation
912
- // compact; selector-specific handoffs are installed only while
913
- // childChanges streams are running.
914
- const registry: ChildRegistry = {
915
- closed: false,
916
- children: new Map(),
917
- observers: undefined,
918
- scope: undefined
919
- }
920
-
921
- const close = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> =>
922
- Effect.suspend(() => {
923
- if (registry.closed) {
924
- return Effect.void
925
- }
926
- registry.closed = true
927
- if (registry.scope === undefined) {
928
- return Effect.void
929
- }
930
- const finalizers = Scope.closeUnsafe(registry.scope, exit)
931
- let first: Effect.Effect<void> | undefined
932
- let rest: Array<Effect.Effect<void>> | undefined
933
- for (const entry of registry.children.values()) {
934
- if (entry._tag !== "Started") {
935
- continue
936
- }
937
- if (first === undefined) {
938
- first = entry.ref.stop
939
- } else {
940
- rest ??= [first]
941
- rest.push(entry.ref.stop)
942
- }
943
- }
944
- if (finalizers !== undefined) {
945
- if (first === undefined) {
946
- first = finalizers
947
- } else {
948
- rest ??= [first]
949
- rest.push(finalizers)
950
- }
951
- }
952
- const cleanup = rest ?? first
953
- return cleanup === undefined
954
- ? Effect.void
955
- : Array.isArray(cleanup)
956
- ? Effect.all(cleanup, { concurrency: "unbounded", discard: true })
957
- : cleanup
958
- })
959
-
960
- const unregister = (
961
- key: ChildKey,
962
- token: symbol
963
- ): Effect.Effect<void> => Effect.sync(() => unregisterChild(registry, key, token))
964
-
965
- const register = (
966
- key: ChildKey,
967
- token: symbol,
968
- ref: MachineRef<any, any, any, any>,
969
- descriptor: ChildDescriptor | undefined
970
- ): Effect.Effect<boolean> => Effect.sync(() => registerChild(registry, key, token, ref, descriptor))
971
-
972
- const get: ChildRuntime["get"] = (child) => {
973
- const id = typeof child === "string" ? child : child.id
974
- return Effect.sync(() => {
975
- if (registry.closed) {
976
- return Option.none()
977
- }
978
- const entry = registry.children.get(id)
979
- return entry !== undefined && matchesChild(entry, child)
980
- ? Option.some(entry.ref)
981
- : Option.none()
982
- })
983
- }
984
-
985
- const changes: ChildRuntime["changes"] = (child) => {
986
- const id = typeof child === "string" ? child : child.id
987
- return Stream.fromChannel(
988
- Channel.fromTransform((_, streamScope) =>
989
- Effect.sync((): ChildObserver => ({ child, id, values: undefined, waiter: undefined })).pipe(
990
- Effect.flatMap((observer) => {
991
- const removeObserver = Effect.sync(() => {
992
- if (registry.observers !== undefined) {
993
- registry.observers.delete(observer)
994
- if (registry.observers.size === 0) {
995
- registry.observers = undefined
996
- }
997
- }
998
- observer.values = undefined
999
- observer.waiter = undefined
1000
- })
1001
- return Scope.addFinalizer(streamScope, removeObserver).pipe(
1002
- Effect.andThen(
1003
- Effect.sync(() => {
1004
- if (!registry.closed && streamScope.state._tag !== "Closed") {
1005
- registry.observers ??= new Set()
1006
- registry.observers.add(observer)
1007
- }
1008
- offerChildObservation(observer, selectRegistryChild(registry, id, child))
1009
- })
1010
- ),
1011
- Effect.as(takeChildObservations(observer))
1012
- )
1013
- })
1014
- )
1015
- )
1016
- )
1017
- }
1018
-
1019
- const sendTo = (
1020
- child: ChildSelector,
1021
- event: unknown,
1022
- source?: Inspection.Subject,
1023
- causedBy?: Inspection.Causation
1024
- ): Effect.Effect<void, StoppedError> => {
1025
- const id = typeof child === "string" ? child : child.id
1026
- return Effect.suspend(() => {
1027
- if (registry.closed) {
1028
- return Effect.void
1029
- }
1030
- const entry = registry.children.get(id)
1031
- return entry !== undefined && matchesChild(entry, child)
1032
- ? sendMachineTarget(entry.ref, event, source, causedBy)
1033
- : Effect.void
1034
- })
1035
- }
1036
-
1037
- const stop = (child: ChildSelector): Effect.Effect<void> => {
1038
- const id = typeof child === "string" ? child : child.id
1039
- return Effect.suspend(() => {
1040
- if (registry.closed) {
1041
- return Effect.void
1042
- }
1043
- const entry = registry.children.get(id)
1044
- return entry !== undefined && matchesChild(entry, child)
1045
- ? entry.ref.stop
1046
- : Effect.void
1047
- })
1048
- }
1049
-
1050
- function spawn<const Child extends ChildMachine.Any>(
1051
- child: Child & ChildMachine.Executable<Child> & ChildMachine.ParentCompatibility<Child, unknown>,
1052
- ...options: ChildMachine.SpawnArgs<Child>
1053
- ): Effect.Effect<
1054
- ChildMachine.Ref<Child>,
1055
- ChildAlreadyExistsError | ChildMachine.StartError<Child>,
1056
- ChildMachine.StartRequirements<Child>
1057
- >
1058
- function spawn<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
1059
- logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>
1060
- ): Effect.Effect<
1061
- MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
1062
- ChildInitialError,
1063
- Exclude<ChildRequirements, Scope.Scope>
1064
- >
1065
- function spawn<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(
1066
- logic: ProcessLogic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>,
1067
- spawnOptions: {
1068
- readonly id: string
1069
- readonly descriptor?: ChildDescriptor
1070
- readonly onOutcome?: (
1071
- outcome: RuntimeOutcome<ChildState, ChildError, ChildOutput>
1072
- ) => Effect.Effect<void>
1073
- readonly [activeSnapshotObserver]?: (
1074
- snapshot: Extract<RuntimeSnapshot<ChildState, ChildError, ChildOutput>, { readonly status: "active" }>
1075
- ) => Effect.Effect<void>
1076
- readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
1077
- }
1078
- ): Effect.Effect<
1079
- MachineRef<ChildState, ChildEvent, ChildError, ChildOutput>,
1080
- ChildAlreadyExistsError | ChildInitialError,
1081
- Exclude<ChildRequirements, Scope.Scope>
1082
- >
1083
- function spawn(
1084
- logicOrChild: ProcessLogic<any, any, any, any, any, any> | ChildMachine.Any,
1085
- options?: {
1086
- readonly id: string
1087
- readonly descriptor?: ChildDescriptor
1088
- readonly onOutcome?: (
1089
- outcome: RuntimeOutcome<any, any, any>
1090
- ) => Effect.Effect<void>
1091
- readonly [activeSnapshotObserver]?: (
1092
- snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
1093
- ) => Effect.Effect<void>
1094
- readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
1095
- } | { readonly input?: unknown }
1096
- ): Effect.Effect<MachineRef<any, any, any, any>, any, any> {
1097
- const descriptor = typeof logicOrChild === "object" && logicOrChild !== null &&
1098
- ChildMachineLogicTypeId in logicOrChild
1099
- ? logicOrChild as ChildMachine.Any
1100
- : undefined
1101
- const logic = descriptor === undefined
1102
- ? logicOrChild as ProcessLogic<any, any, any, any, any, any>
1103
- : descriptor[ChildMachineLogicTypeId](
1104
- (options as { readonly input?: unknown } | undefined)?.input
1105
- ) as unknown as ProcessLogic<any, any, any, any, any, any>
1106
- const spawnOptions = descriptor === undefined
1107
- ? options as {
1108
- readonly id: string
1109
- readonly descriptor?: ChildDescriptor
1110
- readonly onOutcome?: (outcome: RuntimeOutcome<any, any, any>) => Effect.Effect<void>
1111
- readonly [activeSnapshotObserver]?: (
1112
- snapshot: Extract<RuntimeSnapshot<any, any, any>, { readonly status: "active" }>
1113
- ) => Effect.Effect<void>
1114
- readonly [sendParentOverride]?: (event: unknown) => Effect.Effect<void, StoppedError>
1115
- } | undefined
1116
- : { id: descriptor.id, descriptor }
1117
- const token = Symbol()
1118
- const key = spawnOptions?.id ?? token
1119
- let startedChild: MachineRef<any, any, any, any> | undefined
1120
- return Effect.suspend(() => {
1121
- if (registry.closed) {
1122
- return Effect.interrupt
1123
- }
1124
- if (typeof key === "string" && registry.children.has(key)) {
1125
- return Effect.fail(new ChildAlreadyExistsError({ id: key }))
1126
- }
1127
- registry.scope ??= Scope.makeUnsafe("parallel")
1128
- registry.children.set(key, { _tag: "Starting", token })
1129
- return startLogicInternal(logic, {
1130
- detached: true,
1131
- ...(spawnOptions?.id === undefined ? undefined : { id: spawnOptions.id }),
1132
- ...(spawnOptions?.onOutcome === undefined ? undefined : { onOutcome: spawnOptions.onOutcome }),
1133
- ...(spawnOptions?.[activeSnapshotObserver] === undefined
1134
- ? undefined
1135
- : { onSnapshot: spawnOptions[activeSnapshotObserver] }),
1136
- ...(spawnOptions?.[sendParentOverride] === undefined
1137
- ? undefined
1138
- : { sendParent: spawnOptions[sendParentOverride] }),
1139
- onReady: (child, requestChildStop) =>
1140
- Effect.sync(() => {
1141
- startedChild = child
1142
- }).pipe(
1143
- Effect.andThen(register(key, token, child, spawnOptions?.descriptor)),
1144
- Effect.flatMap((registered) => registered ? Effect.void : requestChildStop)
1145
- ),
1146
- onStop: unregister(key, token),
1147
- parent: self,
1148
- runtime,
1149
- origin: { _tag: "Spawn", address: spawnOptions?.id }
1150
- }).pipe(
1151
- Effect.onExit((exit) =>
1152
- Exit.isFailure(exit)
1153
- ? unregister(key, token).pipe(
1154
- Effect.andThen(startedChild === undefined ? Effect.void : startedChild.stop)
1155
- )
1156
- : Effect.void
1157
- ),
1158
- Scope.provide(registry.scope)
1159
- )
1160
- })
1161
- }
1162
-
1163
- return {
1164
- close,
1165
- spawn,
1166
- get,
1167
- changes,
1168
- sendTo,
1169
- stop,
1170
- owned: new OwnedChildRuntimeImpl(registry, self, runtime, services, sendAcknowledged)
1171
- }
1172
- }
1173
-
1174
- const makeChildRuntime = (
1175
- self: ProcessAddress<any>,
1176
- runtime: ProcessRuntime,
1177
- services?: Context.Context<any>,
1178
- sendAcknowledged?: (
1179
- event: unknown
1180
- ) => Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError>
1181
- ): Effect.Effect<ChildRuntime> => Effect.sync(() => makeChildRuntimeSync(self, runtime, services, sendAcknowledged))
1182
-
1183
- // `Machine.logic` permits an arbitrary Effect program, including programs that
1184
- // suspend or supervise their own fibers. Keep its two-fiber worker/supervisor
1185
- // protocol as the general contract rather than weakening it for statecharts.
1186
- const startGenericInternal: <
1187
- State,
1188
- Event,
1189
- Error = never,
1190
- Requirements = never,
1191
- Output = never,
1192
- InitialError = never
1193
- >(
1194
- logic: ProcessLogic<State, Event, Error, Requirements, Output, InitialError>,
1195
- options: StartInternalOptions
1196
- ) => Effect.Effect<
1197
- MachineRef<State, Event, Error, Output>,
1198
- InitialError,
1199
- Requirements
1200
- > = Effect.fnUntraced(function*<State, Event, Error, Requirements, Output, InitialError>(
1201
- logic: ProcessLogic<State, Event, Error, Requirements, Output, InitialError>,
1202
- options: StartInternalOptions
1203
- ) {
1204
- const {
1205
- detached,
1206
- id: requestedId,
1207
- onOutcome,
1208
- onReady,
1209
- onReadySync,
1210
- onSnapshot,
1211
- onStop,
1212
- onStopSync,
1213
- parent,
1214
- runtime,
1215
- sendParent: overrideSendParent
1216
- } = options
1217
- type ProcessTermination =
1218
- | { readonly _tag: "Stopped" }
1219
- | { readonly _tag: "Done"; readonly output: Output }
1220
- | { readonly _tag: "Failure"; readonly cause: Cause.Cause<Error> }
1221
-
1222
- const sessionId = options.sessionId ?? (yield* runtime.nextSessionId)
1223
- const id = requestedId ?? sessionId
1224
- const inspector = runtime.inspection
1225
- const subject = inspector === undefined ? undefined : inspectionSubject(logic, id, sessionId)
1226
- const activity: Inspection.Activity | undefined = inspector === undefined || options.activity === undefined
1227
- ? undefined
1228
- : { ...options.activity, sessionId }
1229
- let initialEntryPaths: ReadonlyArray<string> | undefined
1230
- let initialMicrosteps: ReadonlyArray<unknown> | undefined
1231
- const queue = yield* Queue.unbounded<ProcessMessage<Event>>()
1232
- const emissions = options.emissions ?? makeEmissionRuntime()
1233
- const termination = yield* Deferred.make<ProcessTermination>()
1234
- const done = yield* Deferred.make<Output, Error | StoppedError>()
1235
- const awaitCompletion = Deferred.await(done).pipe(Effect.exit, Effect.asVoid)
1236
- let initializing = true
1237
- let inFlightMessage: ProcessMessage<Event> | undefined
1238
- const requestStop = Deferred.succeed(termination, { _tag: "Stopped" }).pipe(Effect.asVoid)
1239
- const offerDirect = (message: ProcessMessage<Event>): Effect.Effect<void, StoppedError> =>
1240
- Queue.offer(queue, message).pipe(
1241
- Effect.flatMap((accepted) => accepted ? Effect.void : Effect.fail(new StoppedError()))
1242
- )
1243
- const offerInspected: InspectedOffer<Event> | undefined = inspector === undefined ? undefined : (
1244
- event,
1245
- source,
1246
- causedBy,
1247
- deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
1248
- ) =>
1249
- Effect.suspend(() => {
1250
- const message: ProcessMessage<Event> = inspector.isActive()
1251
- ? makeInspectedMessage(inspector, subject!, event, source, causedBy, deferred)
1252
- : deferred === undefined
1253
- ? event
1254
- : { [AcknowledgedMessageTypeId]: true as const, event, deferred }
1255
- return offerDirect(message).pipe(
1256
- Effect.tap(() => Effect.sync(() => publishInspectedSent(inspector, subject!, message)))
1257
- )
1258
- })
1259
- const sendAcknowledged:
1260
- | ((event: Event) => Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>)
1261
- | undefined = logic.execution?._tag !== "Compiled"
1262
- ? undefined
1263
- : (event) =>
1264
- Effect.uninterruptibleMask((restore) =>
1265
- Deferred.make<AcknowledgedDelivery<unknown>, unknown>().pipe(
1266
- Effect.flatMap((deferred) => {
1267
- const offered = inspector === undefined
1268
- ? offerDirect({ [AcknowledgedMessageTypeId]: true as const, event, deferred })
1269
- : offerInspected!(event, undefined, undefined, deferred)
1270
- return offered.pipe(Effect.andThen(restore(Deferred.await(deferred))))
1271
- }),
1272
- Effect.map((delivery) => delivery as AcknowledgedDelivery<State>)
1273
- )
1274
- ) as Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>
1275
-
1276
- const self: ProcessAddress<Event> = {
1277
- id,
1278
- sessionId,
1279
- // Initialization must finish constructing a state before a stopped
1280
- // snapshot can be published. A stop requested there is therefore recorded
1281
- // and returns so initialization can finish. Once running, the requesting
1282
- // process waits forever and is interrupted by the supervisor after the
1283
- // stop request wins, so execution never continues after `self.stop`.
1284
- stop: Effect.suspend(() =>
1285
- initializing
1286
- ? requestStop
1287
- : requestStop.pipe(Effect.andThen(Effect.never))
1288
- ),
1289
- send: inspector === undefined
1290
- ? (event) => offerDirect(event)
1291
- : (event) => offerInspected!(event, undefined, undefined),
1292
- ...(inspector === undefined
1293
- ? undefined
1294
- : { inspectionSubject: subject!, sendInspected: offerInspected! })
1295
- }
1296
-
1297
- let {
1298
- changes: childChanges,
1299
- close: closeChildren,
1300
- get: getChild,
1301
- owned: ownedChildren,
1302
- sendTo,
1303
- spawn,
1304
- stop: stopChild
1305
- } = childlessRuntime
1306
- if (!executionIsChildless(logic.execution)) {
1307
- ;({
1308
- changes: childChanges,
1309
- close: closeChildren,
1310
- get: getChild,
1311
- owned: ownedChildren,
1312
- sendTo,
1313
- spawn,
1314
- stop: stopChild
1315
- } = yield* makeChildRuntime(
1316
- self,
1317
- runtime,
1318
- undefined,
1319
- sendAcknowledged === undefined ? undefined : (event) => sendAcknowledged(event as Event)
1320
- ))
1321
- }
1322
- const cleanupStartupFailure = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> => {
1323
- if (Exit.isSuccess(exit)) return Effect.void
1324
- if (inspector !== undefined) {
1325
- inspector.publishUnsafe(
1326
- activity === undefined
1327
- ? { _tag: "StartFailed", subject: subject!, cause: exit.cause }
1328
- : { _tag: "ActivityStopped", subject: activity.owner, activity, exit }
1329
- )
1330
- }
1331
- return closeChildren(exit).pipe(
1332
- Effect.andThen(emissions.close()),
1333
- Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void)
1334
- )
1335
- }
1336
- const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(onStopSync)
1337
- const currentCausation = inspector === undefined
1338
- ? noCausation
1339
- : (): Inspection.Causation | undefined => messageCausation(inFlightMessage, initializing)
1340
- const sendParent = overrideSendParent ?? (parent === undefined
1341
- ? noParentSend
1342
- : inspector === undefined
1343
- ? parent.send
1344
- : (event) => sendMachineTarget(parent, event, subject, currentCausation()))
1345
- const emit = inspector === undefined
1346
- ? emissions.emit
1347
- : (event: unknown) =>
1348
- emissions.emit(event).pipe(
1349
- Effect.tap(() =>
1350
- Effect.sync(() =>
1351
- inspector.publishUnsafe({
1352
- _tag: "Emitted",
1353
- subject: subject!,
1354
- emission: event,
1355
- causedBy: currentCausation()
1356
- })
1357
- )
1358
- )
1359
- )
1360
- const sendToTarget: ProcessScope<Event>["sendTo"] = inspector === undefined
1361
- ? ((target: unknown, event: unknown) =>
1362
- isMachineTarget(target) ? target.send(event) : sendTo(target as ChildSelector, event)) as ProcessScope<
1363
- Event
1364
- >["sendTo"]
1365
- : ((target: unknown, event: unknown) =>
1366
- isMachineTarget(target)
1367
- ? sendMachineTarget(target, event, subject, currentCausation())
1368
- : sendTo(target as ChildSelector, event, subject, currentCausation())) as ProcessScope<Event>["sendTo"]
1369
-
1370
- const scope: ProcessScope<Event> = {
1371
- self,
1372
- parent,
1373
- spawn,
1374
- sendParent,
1375
- emit,
1376
- sendTo: sendToTarget,
1377
- stopChild,
1378
- failCause: (cause) =>
1379
- Deferred.succeed(termination, {
1380
- _tag: "Failure",
1381
- cause: cause as Cause.Cause<Error>
1382
- }).pipe(Effect.asVoid),
1383
- inspectInitial: inspector === undefined
1384
- ? noInspectInitial
1385
- : (paths, microsteps = []) => {
1386
- initialEntryPaths = paths
1387
- initialMicrosteps = microsteps
1388
- }
1389
- }
1390
-
1391
- if (inspector !== undefined) {
1392
- inspector.publishUnsafe(
1393
- activity === undefined
1394
- ? {
1395
- _tag: "Created",
1396
- subject: subject!,
1397
- parent: parent?.inspectionSubject,
1398
- origin: options.origin ?? { _tag: "Root" },
1399
- definition: logic.inspection?.definition
1400
- }
1401
- : { _tag: "ActivityStarted", subject: activity.owner, activity }
1402
- )
1403
- }
1404
-
1405
- const initial = yield* logic.initial(scope).pipe(
1406
- Effect.onExit(cleanupStartupFailure),
1407
- Effect.ensuring(Effect.sync(() => {
1408
- initializing = false
1409
- }))
1410
- )
1411
- const current = yield* SynchronizedRef.make<VersionedSnapshot<State, Error, Output>>({
1412
- revision: 0,
1413
- terminalizing: false,
1414
- changes: undefined,
1415
- snapshot: {
1416
- status: "active",
1417
- state: initial
1418
- }
1419
- })
1420
- if (activity === undefined) {
1421
- inspector?.publishUnsafe({
1422
- _tag: "Initialized",
1423
- subject: subject!,
1424
- snapshot: { status: "active", state: initial },
1425
- initialEntryPaths: initialEntryPaths ?? [],
1426
- microsteps: InspectionRuntime.microsteps({ microsteps: initialMicrosteps ?? [] })
1427
- })
1428
- }
1429
- const publishSnapshot: (
1430
- snapshot: VersionedSnapshot<State, Error, Output>
1431
- ) => Effect.Effect<VersionedSnapshot<State, Error, Output>> = onSnapshot === undefined
1432
- ? (snapshot) =>
1433
- snapshot.changes === undefined
1434
- ? Effect.succeed(snapshot)
1435
- : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
1436
- : (snapshot) => {
1437
- const publish = snapshot.changes === undefined
1438
- ? Effect.succeed(snapshot)
1439
- : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
1440
- const runtimeSnapshot = snapshot.snapshot
1441
- return runtimeSnapshot.status !== "active"
1442
- ? publish
1443
- : publish.pipe(Effect.tap(() => notifyActiveSnapshot(onSnapshot, runtimeSnapshot)))
1444
- }
1445
-
1446
- const completeChanges = (
1447
- snapshot: VersionedSnapshot<State, Error, Output>
1448
- ): Effect.Effect<void> =>
1449
- snapshot.changes === undefined
1450
- ? Effect.void
1451
- : PubSub.publish(snapshot.changes, Exit.succeed<void>(undefined)).pipe(Effect.asVoid)
1452
-
1453
- const completeIfTerminal = (
1454
- snapshot: VersionedSnapshot<State, Error, Output>
1455
- ): Effect.Effect<VersionedSnapshot<State, Error, Output>> => {
1456
- if (snapshot.snapshot.status === "active") {
1457
- return Effect.succeed(snapshot)
1458
- }
1459
- return completeChanges(snapshot).pipe(Effect.as(snapshot))
1460
- }
1461
-
1462
- const publishIfCurrent = (
1463
- snapshot: VersionedSnapshot<State, Error, Output>
1464
- ): Effect.Effect<VersionedSnapshot<State, Error, Output> | undefined> =>
1465
- SynchronizedRef.get(current).pipe(
1466
- Effect.flatMap((
1467
- currentSnapshot
1468
- ): Effect.Effect<VersionedSnapshot<State, Error, Output> | undefined> =>
1469
- currentSnapshot.revision === snapshot.revision
1470
- ? publishSnapshot(snapshot).pipe(Effect.flatMap(completeIfTerminal))
1471
- : Effect.succeed(undefined)
1472
- )
1473
- )
1474
-
1475
- type SnapshotModification = readonly [
1476
- VersionedSnapshot<State, Error, Output> | undefined,
1477
- VersionedSnapshot<State, Error, Output>
1478
- ]
1479
-
1480
- const updateSnapshot = <E2, R2>(
1481
- f: (
1482
- snapshot: RuntimeSnapshot<State, Error, Output>
1483
- ) => Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined, E2, R2>
1484
- ): Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined, E2, R2> =>
1485
- SynchronizedRef.modifyEffect(
1486
- current,
1487
- (current) =>
1488
- current.terminalizing
1489
- ? Effect.succeed([undefined, current] as const)
1490
- : Effect.map(
1491
- f(current.snapshot),
1492
- (next) => {
1493
- if (next === undefined) {
1494
- return [undefined, current] as const
1495
- }
1496
- const versioned = {
1497
- revision: current.revision + 1,
1498
- snapshot: next,
1499
- terminalizing: false,
1500
- changes: current.changes
1501
- }
1502
- return [versioned, versioned] as const
1503
- }
1504
- )
1505
- ).pipe(
1506
- Effect.flatMap((versioned) => versioned === undefined ? Effect.succeed(undefined) : publishIfCurrent(versioned)),
1507
- Effect.map((published) => published?.snapshot)
1508
- )
1509
-
1510
- const reserveTerminalSnapshot = (
1511
- f: (
1512
- snapshot: Extract<RuntimeSnapshot<State, Error, Output>, { readonly status: "active" }>
1513
- ) => RuntimeSnapshot<State, Error, Output>
1514
- ): Effect.Effect<RuntimeSnapshot<State, Error, Output> | undefined> =>
1515
- SynchronizedRef.modify(
1516
- current,
1517
- (current): SnapshotModification => {
1518
- if (current.terminalizing || current.snapshot.status !== "active") {
1519
- return [undefined, current]
1520
- }
1521
- return [
1522
- {
1523
- revision: current.revision + 1,
1524
- snapshot: f(current.snapshot),
1525
- terminalizing: true,
1526
- changes: current.changes
1527
- },
1528
- { ...current, terminalizing: true }
1529
- ]
1530
- }
1531
- ).pipe(Effect.map((versioned) => versioned?.snapshot))
1532
-
1533
- const setAndPublishSnapshot = (
1534
- snapshot: RuntimeSnapshot<State, Error, Output>
1535
- ): Effect.Effect<void> =>
1536
- SynchronizedRef.updateAndGet(current, (current) => ({
1537
- revision: current.revision + 1,
1538
- snapshot,
1539
- terminalizing: true,
1540
- changes: current.changes
1541
- })).pipe(
1542
- Effect.flatMap(publishSnapshot),
1543
- Effect.flatMap(completeIfTerminal),
1544
- Effect.asVoid
1545
- )
1546
-
1547
- const setActiveStateDirect = (state: State) =>
1548
- updateSnapshot((snapshot) =>
1549
- Effect.succeed(
1550
- snapshot.status === "active"
1551
- ? {
1552
- status: "active",
1553
- state
1554
- }
1555
- : undefined
1556
- )
1557
- ).pipe(Effect.asVoid)
1558
-
1559
- const setActiveState = inspector === undefined ?
1560
- setActiveStateDirect :
1561
- (state: State) =>
1562
- SynchronizedRef.get(current).pipe(
1563
- Effect.flatMap((before) =>
1564
- updateSnapshot((snapshot) =>
1565
- Effect.succeed(
1566
- snapshot.status === "active"
1567
- ? {
1568
- status: "active",
1569
- state
1570
- }
1571
- : undefined
1572
- )
1573
- ).pipe(
1574
- Effect.tap((after) =>
1575
- Effect.sync(() => {
1576
- if (logic.inspection?.kind === "Machine" || after === undefined) return
1577
- inspector.publishUnsafe({
1578
- _tag: "StateChanged",
1579
- subject: subject!,
1580
- before: before.snapshot.state,
1581
- after: state,
1582
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
1583
- ? inFlightMessage.inspection?.deliveryId
1584
- : undefined
1585
- })
1586
- })
1587
- )
1588
- )
1589
- ),
1590
- Effect.asVoid
1591
- )
1592
-
1593
- const terminalizeWith = (
1594
- snapshot: RuntimeSnapshot<State, Error, Output>,
1595
- exit: Exit.Exit<unknown, unknown>,
1596
- completeDone: Effect.Effect<void>
1597
- ): Effect.Effect<void> => {
1598
- const notifyOutcome =
1599
- onOutcome === undefined || (snapshot.status === "stopped" && options.skipStoppedOutcome === true)
1600
- ? Effect.void
1601
- : Effect.suspend(() => onOutcome(classifyOutcome(snapshot)!)).pipe(
1602
- Effect.exit,
1603
- Effect.asVoid
1604
- )
1605
- const closeEmissionsAndInspect = inspector === undefined
1606
- ? emissions.close()
1607
- : emissions.close().pipe(
1608
- Effect.andThen(Effect.sync(() =>
1609
- inspector.publishUnsafe(
1610
- activity === undefined
1611
- ? { _tag: "Terminated", subject: subject!, snapshot }
1612
- : {
1613
- _tag: "ActivityStopped",
1614
- subject: activity.owner,
1615
- activity,
1616
- exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
1617
- }
1618
- )
1619
- ))
1620
- )
1621
- return Effect.uninterruptible(
1622
- Effect.sync(() => {
1623
- while (true) {
1624
- const pending = Queue.takeUnsafe(queue)
1625
- if (pending === undefined || Exit.isFailure(pending)) break
1626
- stopAcknowledgedMessage(pending.value)
1627
- }
1628
- }).pipe(
1629
- Effect.andThen(Queue.shutdown(queue)),
1630
- Effect.andThen(closeChildren(exit)),
1631
- Effect.andThen(setAndPublishSnapshot(snapshot)),
1632
- Effect.andThen(closeEmissionsAndInspect),
1633
- Effect.andThen(Effect.sync(() => {
1634
- if (Exit.isFailure(exit)) {
1635
- failAcknowledgedMessage(inFlightMessage, exit.cause)
1636
- } else {
1637
- stopAcknowledgedMessage(inFlightMessage)
1638
- }
1639
- inFlightMessage = undefined
1640
- })),
1641
- Effect.andThen(notifyOutcome),
1642
- Effect.andThen(cleanup),
1643
- Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void),
1644
- Effect.andThen(completeDone)
1645
- )
1646
- )
1647
- }
1648
-
1649
- const reserveStoppedSnapshot = reserveTerminalSnapshot((snapshot) => ({
1650
- status: "stopped",
1651
- state: snapshot.state
1652
- }))
1653
-
1654
- const reserveFailureSnapshot = (cause: Cause.Cause<Error>) =>
1655
- reserveTerminalSnapshot((snapshot) => ({
1656
- status: "error",
1657
- state: snapshot.state,
1658
- cause
1659
- }))
1660
-
1661
- const reserveSuccessSnapshot = (output: Output) =>
1662
- reserveTerminalSnapshot((snapshot) => ({
1663
- status: "done",
1664
- state: snapshot.state,
1665
- output
1666
- }))
1667
-
1668
- const terminalizeReservedStop = (
1669
- snapshot: RuntimeSnapshot<State, Error, Output>
1670
- ): Effect.Effect<void> => {
1671
- const exit = Exit.void
1672
- return terminalizeWith(
1673
- snapshot,
1674
- exit,
1675
- Deferred.fail(done, new StoppedError())
1676
- )
1677
- }
1678
-
1679
- const terminalizeReservedFailure = (
1680
- snapshot: RuntimeSnapshot<State, Error, Output>,
1681
- cause: Cause.Cause<Error>
1682
- ): Effect.Effect<void> => {
1683
- const exit = Exit.failCause(cause)
1684
- return terminalizeWith(snapshot, exit, Deferred.failCause(done, cause))
1685
- }
1686
-
1687
- const terminalizeReservedSuccess = (
1688
- snapshot: RuntimeSnapshot<State, Error, Output>,
1689
- output: Output
1690
- ): Effect.Effect<void> => {
1691
- const exit = Exit.succeed(output)
1692
- return terminalizeWith(snapshot, exit, Deferred.succeed(done, output))
1693
- }
1694
-
1695
- const stop: Effect.Effect<void> = Effect.uninterruptible(
1696
- requestStop.pipe(Effect.andThen(awaitCompletion))
1697
- )
1698
-
1699
- const acknowledgedContext:
1700
- | Pick<
1701
- ProcessContext<State, Event>,
1702
- "receiveMessage" | "pollMessage" | "completeMessage"
1703
- >
1704
- | undefined = logic.execution?._tag !== "Compiled" ? undefined : {
1705
- receiveMessage: Queue.take(queue).pipe(
1706
- Effect.tap((message) =>
1707
- Effect.sync(() => {
1708
- inFlightMessage = isAcknowledgedMessage(message) ? message : undefined
1709
- })
1710
- )
1711
- ),
1712
- pollMessage: Queue.poll(queue).pipe(
1713
- Effect.tap((message) =>
1714
- Effect.sync(() => {
1715
- if (Option.isSome(message)) {
1716
- inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined
1717
- }
1718
- })
1719
- )
1720
- ),
1721
- completeMessage: (delivery) => {
1722
- succeedAcknowledgedMessage(inFlightMessage, delivery)
1723
- inFlightMessage = undefined
1724
- }
1725
- }
1726
- const receive = inspector === undefined || logic.execution?._tag === "Compiled"
1727
- ? Queue.take(queue).pipe(Effect.map(messageEvent))
1728
- : Queue.take(queue).pipe(
1729
- Effect.tap((message) =>
1730
- Effect.sync(() => {
1731
- inFlightMessage = message
1732
- })
1733
- ),
1734
- Effect.map(messageEvent)
1735
- )
1736
- const poll = inspector === undefined || logic.execution?._tag === "Compiled"
1737
- ? Queue.poll(queue).pipe(Effect.map(Option.map(messageEvent)))
1738
- : Queue.poll(queue).pipe(
1739
- Effect.tap((message) =>
1740
- Effect.sync(() => {
1741
- if (Option.isSome(message)) inFlightMessage = message.value
1742
- })
1743
- ),
1744
- Effect.map(Option.map(messageEvent))
1745
- )
1746
- const updateStateDirect = <E2, R2>(f: (state: State) => Effect.Effect<State, E2, R2>) =>
1747
- updateSnapshot((snapshot) =>
1748
- snapshot.status === "active"
1749
- ? f(snapshot.state).pipe(
1750
- Effect.map((state) => ({
1751
- status: "active" as const,
1752
- state
1753
- }))
1754
- )
1755
- : Effect.succeed(undefined)
1756
- ).pipe(Effect.asVoid)
1757
- const updateState: ProcessContext<State, Event>["updateState"] = inspector === undefined
1758
- ? updateStateDirect
1759
- : (f) =>
1760
- SynchronizedRef.get(current).pipe(
1761
- Effect.flatMap((before) =>
1762
- updateSnapshot((snapshot) =>
1763
- snapshot.status === "active"
1764
- ? f(snapshot.state).pipe(
1765
- Effect.map((state) => ({
1766
- status: "active" as const,
1767
- state
1768
- }))
1769
- )
1770
- : Effect.succeed(undefined)
1771
- ).pipe(
1772
- Effect.tap((after) =>
1773
- Effect.sync(() => {
1774
- if (logic.inspection?.kind === "Machine" || after?.status !== "active") return
1775
- inspector.publishUnsafe({
1776
- _tag: "StateChanged",
1777
- subject: subject!,
1778
- before: before.snapshot.state,
1779
- after: after.state,
1780
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
1781
- ? inFlightMessage.inspection?.deliveryId
1782
- : undefined
1783
- })
1784
- })
1785
- )
1786
- )
1787
- ),
1788
- Effect.asVoid
1789
- )
1790
- const context: ProcessContext<State, Event> = {
1791
- ...scope,
1792
- ...(logic.execution?._tag === "Compiled" && !logic.execution.childless ? { ownedChildren } : undefined),
1793
- ...acknowledgedContext,
1794
- receive,
1795
- poll,
1796
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
1797
- setState: setActiveState,
1798
- updateState
1799
- }
1800
-
1801
- const getOrCreateChanges = SynchronizedRef.modifyEffect(
1802
- current,
1803
- (current) => {
1804
- if (current.snapshot.status !== "active") {
1805
- return Effect.succeed([undefined, current] as const)
1806
- }
1807
- if (current.changes !== undefined) {
1808
- return Effect.succeed([current.changes, current] as const)
1809
- }
1810
- return PubSub.unbounded<Take.Take<VersionedSnapshot<State, Error, Output>>>({ replay: 1 }).pipe(
1811
- Effect.map((changes) => [changes, { ...current, changes }] as const)
1812
- )
1813
- }
1814
- )
1815
-
1816
- const changesStream: Stream.Stream<RuntimeSnapshot<State, Error, Output>> = Stream.unwrap(
1817
- Effect.gen(function*() {
1818
- const changes = yield* getOrCreateChanges
1819
- if (changes === undefined) {
1820
- return Stream.succeed((yield* SynchronizedRef.get(current)).snapshot)
1821
- }
1822
- const subscription = yield* PubSub.subscribe(changes)
1823
- const captured = yield* SynchronizedRef.get(current)
1824
- if (captured.snapshot.status !== "active") {
1825
- return Stream.succeed(captured.snapshot)
1826
- }
1827
- return Stream.succeed(captured.snapshot).pipe(
1828
- Stream.concat(
1829
- Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(
1830
- Stream.filter((next) => next.revision > captured.revision),
1831
- Stream.map((next) => next.snapshot)
1832
- )
1833
- )
1834
- )
1835
- })
1836
- )
1837
-
1838
- const ref: MachineRef<State, Event, Error, Output> = {
1839
- id,
1840
- sessionId,
1841
- ...(inspector === undefined
1842
- ? undefined
1843
- : { inspectionSubject: subject!, sendInspected: offerInspected! }),
1844
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
1845
- snapshot: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot)),
1846
- changes: changesStream,
1847
- emissions: emissions.stream as Stream.Stream<never>,
1848
- join: Deferred.await(done),
1849
- stop,
1850
- send: self.send,
1851
- ...(sendAcknowledged === undefined ? undefined : { [acknowledgedSend]: sendAcknowledged }),
1852
- child: getChild,
1853
- childChanges
1854
- }
1855
-
1856
- if (onReadySync !== undefined && !onReadySync(ref)) {
1857
- yield* requestStop
1858
- } else if (onReady !== undefined) {
1859
- yield* onReady(ref, requestStop)
1860
- }
1861
- if (onSnapshot !== undefined) {
1862
- yield* notifyActiveSnapshot(onSnapshot, { status: "active", state: initial })
1863
- }
1864
-
1865
- const reserveTermination = (termination: ProcessTermination) => {
1866
- switch (termination._tag) {
1867
- case "Stopped":
1868
- return reserveStoppedSnapshot
1869
- case "Done":
1870
- return reserveSuccessSnapshot(termination.output)
1871
- case "Failure":
1872
- return reserveFailureSnapshot(termination.cause)
1873
- }
1874
- }
1875
-
1876
- const completeTermination = (
1877
- termination: ProcessTermination,
1878
- snapshot: RuntimeSnapshot<State, Error, Output>
1879
- ) => {
1880
- switch (termination._tag) {
1881
- case "Stopped":
1882
- return terminalizeReservedStop(snapshot)
1883
- case "Done":
1884
- return terminalizeReservedSuccess(snapshot, termination.output)
1885
- case "Failure":
1886
- return terminalizeReservedFailure(snapshot, termination.cause)
1887
- }
1888
- }
1889
-
1890
- const forkRuntime = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1891
- detached === true
1892
- ? Effect.forkDetach(effect)
1893
- : Effect.forkChild(effect)
1894
-
1895
- const pendingTermination = yield* Deferred.poll(termination)
1896
- const worker = Option.isNone(pendingTermination)
1897
- ? yield* Effect.uninterruptibleMask((restore) =>
1898
- restore(Effect.suspend(() => logic.run(context))).pipe(
1899
- Effect.exit,
1900
- Effect.flatMap((exit) =>
1901
- Deferred.succeed(
1902
- termination,
1903
- Exit.isFailure(exit)
1904
- ? { _tag: "Failure", cause: exit.cause }
1905
- : { _tag: "Done", output: exit.value }
1906
- )
1907
- )
1908
- )
1909
- ).pipe(forkRuntime)
1910
- : undefined
1911
-
1912
- // One Deferred arbitrates all terminal causes. The supervisor reserves the
1913
- // terminal snapshot before interrupting the worker, so worker finalizers
1914
- // cannot mutate the frozen state. It then waits for those finalizers before
1915
- // publishing and completing `join` / `stop`.
1916
- const runFiber: Effect.Effect<void, never, Requirements> = Effect.uninterruptibleMask((restore) =>
1917
- Effect.gen(function*() {
1918
- const requested = Option.isSome(pendingTermination)
1919
- ? yield* pendingTermination.value
1920
- : yield* restore(Deferred.await(termination))
1921
-
1922
- const snapshot = yield* reserveTermination(requested)
1923
- if (worker !== undefined) {
1924
- yield* Fiber.interrupt(worker)
1925
- }
1926
- if (snapshot === undefined) {
1927
- return yield* awaitCompletion
1928
- }
1929
- return yield* completeTermination(requested, snapshot)
1930
- })
1931
- )
1932
-
1933
- yield* forkRuntime(runFiber)
1934
- yield* Effect.yieldNow
1935
-
1936
- return ref
1937
- })
1938
-
1939
- type CompiledTermination =
1940
- | { readonly _tag: "Stopped" }
1941
- | { readonly _tag: "Done"; readonly output: unknown }
1942
- | { readonly _tag: "Failure"; readonly cause: Cause.Cause<unknown> }
1943
-
1944
- type CompiledInitialized = CompiledProcessInitial<unknown, unknown>
1945
-
1946
- // Stopping is commonly used only for resource cleanup. Keep that path free of
1947
- // Error stack capture and materialize the typed join failure only if observed.
1948
- const CompiledStoppedCompletion: unique symbol = Symbol("effect/Machine/CompiledStoppedCompletion")
1949
-
1950
- type CompiledCompletion =
1951
- | Effect.Effect<unknown, unknown>
1952
- | typeof CompiledStoppedCompletion
1953
-
1954
- type CompiledLifecycle = "Active" | "TerminationRequested" | "Completed"
1955
- type CompiledRunState = "Initializing" | "Idle" | "Draining"
1956
-
1957
- /**
1958
- * Compact runtime for compiled statecharts.
1959
- *
1960
- * All long-lived state is stored directly on this object. Operations are
1961
- * implemented by shared prototype methods, and public Effect / Stream values
1962
- * are materialized only when accessed. Arbitrary process logic continues to
1963
- * use the general runtime above.
1964
- */
1965
- class CompiledProcess implements MachineRef<any, any, any, any> {
1966
- readonly id: string
1967
- readonly sessionId: string
1968
- readonly inspectionSubject?: Inspection.Subject
1969
- readonly send: (event: unknown) => Effect.Effect<void, StoppedError>
1970
- sendInspected(
1971
- event: unknown,
1972
- source: Inspection.Subject | undefined,
1973
- causedBy: Inspection.Causation | undefined
1974
- ): Effect.Effect<void, StoppedError> {
1975
- return this.offerEvent(event, source, causedBy)
1976
- }
1977
- [acknowledgedSend](
1978
- event: unknown
1979
- ): Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError> {
1980
- return this.sendAcknowledgedEffect(event)
1981
- }
1982
-
1983
- private readonly mailbox: CompactProcessMailbox<unknown> = {
1984
- items: undefined,
1985
- index: 0,
1986
- closed: false
1987
- }
1988
- private readonly address: ProcessAddress<unknown>
1989
- private childRuntime: ChildRuntime = childlessRuntime
1990
- private processScope!: ProcessScope<unknown>
1991
- private processContext: ProcessContext<unknown, unknown> | undefined
1992
- private compiledContext: CompiledProcessContext<unknown, unknown> | undefined
1993
- private current!: VersionedSnapshot<unknown, unknown, unknown>
1994
- /**
1995
- * `Active` has no terminal payload, `TerminationRequested` owns
1996
- * `termination` and its optional reserved snapshot, and `Completed` owns
1997
- * `completion`. `runState` independently tracks worker activity.
1998
- */
1999
- private lifecycle: CompiledLifecycle = "Active"
2000
- private runState: CompiledRunState = "Initializing"
2001
- private completion: CompiledCompletion | undefined
2002
- private waiter: Deferred.Deferred<unknown, unknown> | undefined
2003
- private termination: CompiledTermination | undefined
2004
- private terminationSnapshot: RuntimeSnapshot<unknown, unknown, unknown> | undefined
2005
- private worker: Fiber.Fiber<any, never> | undefined
2006
- private interruptRequested = false
2007
- private offerRevision = 0
2008
- private inFlightMessage: ProcessMessage<unknown> | undefined
2009
- private readonly externalEmissions: EmissionRuntime | undefined
2010
- private emissionsPubSub: LazyEmissions
2011
- private readonly activity?: Inspection.Activity
2012
- private initialEntryPaths?: ReadonlyArray<string>
2013
- private initialMicrosteps?: ReadonlyArray<unknown>
2014
- private initializing?: boolean
2015
-
2016
- constructor(
2017
- private readonly logic: ProcessLogic<any, any, any, any, any, any>,
2018
- private readonly options: StartInternalOptions,
2019
- private readonly services: Context.Context<any>,
2020
- sessionId: string
2021
- ) {
2022
- this.sessionId = sessionId
2023
- this.id = options.id ?? sessionId
2024
- const inspector = options.runtime.inspection
2025
- if (inspector !== undefined) {
2026
- this.inspectionSubject = inspectionSubject(logic, this.id, sessionId)
2027
- this.initializing = true
2028
- if (options.activity !== undefined) this.activity = { ...options.activity, sessionId }
2029
- }
2030
- this.externalEmissions = options.emissions
2031
- this.send = inspector === undefined
2032
- ? (event) => this.offerMessage(event)
2033
- : (event) => this.offerEvent(event, undefined, undefined)
2034
- this.address = {
2035
- id: this.id,
2036
- sessionId,
2037
- stop: Effect.suspend(() => this.stopFromProcess()),
2038
- send: this.send,
2039
- ...(inspector === undefined
2040
- ? undefined
2041
- : {
2042
- inspectionSubject: this.inspectionSubject!,
2043
- sendInspected: (
2044
- event: unknown,
2045
- source: Inspection.Subject | undefined,
2046
- causedBy: Inspection.Causation | undefined
2047
- ) => this.offerEvent(event, source, causedBy)
2048
- })
2049
- }
2050
- }
2051
-
2052
- private get inspector(): InspectionRuntime.Runtime | undefined {
2053
- return this.options.runtime.inspection
2054
- }
2055
-
2056
- private causation(): Inspection.Causation | undefined {
2057
- return messageCausation(this.inFlightMessage, this.initializing === true)
2058
- }
2059
-
2060
- private publishCreated(): void {
2061
- const inspector = this.inspector
2062
- const subject = this.inspectionSubject
2063
- if (inspector === undefined || subject === undefined) return
2064
- inspector.publishUnsafe(
2065
- this.activity === undefined
2066
- ? {
2067
- _tag: "Created",
2068
- subject,
2069
- parent: this.options.parent?.inspectionSubject,
2070
- origin: this.options.origin ?? { _tag: "Root" },
2071
- definition: this.logic.inspection?.definition
2072
- }
2073
- : { _tag: "ActivityStarted", subject: this.activity.owner, activity: this.activity }
2074
- )
2075
- }
2076
-
2077
- private publishInitialized(state: unknown): void {
2078
- this.initializing = false
2079
- if (this.activity !== undefined) return
2080
- const inspector = this.inspector
2081
- const subject = this.inspectionSubject
2082
- if (inspector === undefined || subject === undefined) return
2083
- inspector.publishUnsafe({
2084
- _tag: "Initialized",
2085
- subject,
2086
- snapshot: { status: "active", state },
2087
- initialEntryPaths: this.initialEntryPaths ?? [],
2088
- microsteps: InspectionRuntime.microsteps({ microsteps: this.initialMicrosteps ?? [] })
2089
- })
2090
- }
2091
-
2092
- private publishStartFailed(cause: Cause.Cause<unknown>): void {
2093
- this.initializing = false
2094
- const inspector = this.inspector
2095
- const subject = this.inspectionSubject
2096
- if (inspector === undefined || subject === undefined) return
2097
- inspector.publishUnsafe(
2098
- this.activity === undefined
2099
- ? { _tag: "StartFailed", subject, cause }
2100
- : {
2101
- _tag: "ActivityStopped",
2102
- subject: this.activity.owner,
2103
- activity: this.activity,
2104
- exit: Exit.failCause(cause)
2105
- }
2106
- )
2107
- }
2108
-
2109
- private get execution(): CompiledProcessExecution<any, any, any, any, any, any> {
2110
- return this.logic.execution as CompiledProcessExecution<any, any, any, any, any, any>
2111
- }
2112
-
2113
- initializeCompiledSync(): Effect.Effect<MachineRef<any, any, any, any>, unknown> {
2114
- this.publishCreated()
2115
- if (!this.execution.childless) {
2116
- this.childRuntime = makeChildRuntimeSync(
2117
- this.address,
2118
- this.options.runtime,
2119
- this.services,
2120
- (event) => this.sendAcknowledgedEffect(event)
2121
- )
2122
- }
2123
- const parent = this.options.parent
2124
- const sendParent = this.options.sendParent ?? (parent === undefined
2125
- ? noParentSend
2126
- : this.inspector === undefined
2127
- ? parent.send
2128
- : (event: unknown) => sendMachineTarget(parent, event, this.inspectionSubject, this.causation()))
2129
- this.processScope = {
2130
- self: this.address,
2131
- parent,
2132
- spawn: this.childRuntime.spawn,
2133
- sendParent,
2134
- emit: (event) => this.emitEvent(event),
2135
- sendTo: ((target: unknown, event: unknown) =>
2136
- isMachineTarget(target)
2137
- ? this.inspector === undefined
2138
- ? target.send(event)
2139
- : sendMachineTarget(target, event, this.inspectionSubject, this.causation())
2140
- : this.childRuntime.sendTo(
2141
- target as ChildSelector,
2142
- event,
2143
- this.inspectionSubject,
2144
- this.causation()
2145
- )) as ProcessScope<unknown>["sendTo"],
2146
- stopChild: this.childRuntime.stop,
2147
- failCause: (cause: Cause.Cause<unknown>) => this.failCause(cause),
2148
- inspectInitial: this.inspector === undefined
2149
- ? noInspectInitial
2150
- : (paths, microsteps = []) => {
2151
- this.initialEntryPaths = paths
2152
- this.initialMicrosteps = microsteps
2153
- }
2154
- }
2155
- const compiledInitial = this.execution.initialSync!
2156
- let initialized: CompiledInitialized
2157
- try {
2158
- initialized = compiledInitial(this.processScope)
2159
- } catch (error) {
2160
- this.runState = "Idle"
2161
- this.publishStartFailed(Cause.fail(error))
2162
- return Effect.fail(error)
2163
- }
2164
- this.runState = "Idle"
2165
- this.current = {
2166
- revision: 0,
2167
- terminalizing: false,
2168
- changes: undefined,
2169
- snapshot: { status: "active", state: initialized.state }
2170
- }
2171
- this.publishInitialized(initialized.state)
2172
- this.compiledContext = new CompiledProcessContextImpl(this.processScope, this.childRuntime.owned, this)
2173
- if ("executionState" in initialized) {
2174
- this.compiledContext.executionState = initialized.executionState
2175
- }
2176
- if (this.options.onReadySync !== undefined && !this.options.onReadySync(this)) {
2177
- this.requestTerminationSync({ _tag: "Stopped" })
2178
- }
2179
- if (initialized.done === true && this.lifecycle === "Active") {
2180
- this.requestTerminationSync({ _tag: "Done", output: initialized.output })
2181
- }
2182
- if (
2183
- initialized.done === false && this.execution.childless &&
2184
- this.lifecycle === "Active" &&
2185
- this.mailbox.items === undefined
2186
- ) {
2187
- return Effect.succeed(this)
2188
- }
2189
- this.runState = "Draining"
2190
- return Effect.provideContext(this.drainRuntime(), this.services).pipe(Effect.as(this))
2191
- }
2192
-
2193
- initialize(): Effect.Effect<MachineRef<any, any, any, any>, unknown, any> {
2194
- const self = this
2195
- return Effect.gen(function*() {
2196
- self.publishCreated()
2197
- if (!self.execution.childless) {
2198
- self.childRuntime = yield* makeChildRuntime(
2199
- self.address,
2200
- self.options.runtime,
2201
- self.services,
2202
- (event) => self.sendAcknowledgedEffect(event)
2203
- )
2204
- }
2205
- const parent = self.options.parent
2206
- const sendParent = self.options.sendParent ?? (parent === undefined
2207
- ? noParentSend
2208
- : self.inspector === undefined
2209
- ? parent.send
2210
- : (event: unknown) => sendMachineTarget(parent, event, self.inspectionSubject, self.causation()))
2211
- self.processScope = {
2212
- self: self.address,
2213
- parent,
2214
- spawn: self.childRuntime.spawn,
2215
- sendParent,
2216
- emit: (event) => self.emitEvent(event),
2217
- sendTo: ((target: unknown, event: unknown) =>
2218
- isMachineTarget(target)
2219
- ? self.inspector === undefined
2220
- ? target.send(event)
2221
- : sendMachineTarget(target, event, self.inspectionSubject, self.causation())
2222
- : self.childRuntime.sendTo(
2223
- target as ChildSelector,
2224
- event,
2225
- self.inspectionSubject,
2226
- self.causation()
2227
- )) as ProcessScope<unknown>["sendTo"],
2228
- stopChild: self.childRuntime.stop,
2229
- failCause: (cause: Cause.Cause<unknown>) => self.failCause(cause),
2230
- inspectInitial: self.inspector === undefined
2231
- ? noInspectInitial
2232
- : (paths, microsteps = []) => {
2233
- self.initialEntryPaths = paths
2234
- self.initialMicrosteps = microsteps
2235
- }
2236
- }
2237
-
2238
- const cleanupStartupFailure = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> =>
2239
- Exit.isFailure(exit) ? self.childRuntime.close(exit) : Effect.void
2240
- const compiledInitial = self.execution.initial
2241
- const initializeEffect: Effect.Effect<
2242
- {
2243
- readonly state: unknown
2244
- readonly done: boolean | undefined
2245
- readonly output: unknown
2246
- },
2247
- unknown,
2248
- any
2249
- > = compiledInitial === undefined
2250
- ? self.logic.initial(self.processScope).pipe(
2251
- Effect.map((state) => ({ state, done: undefined, output: undefined } as const))
2252
- )
2253
- : compiledInitial(self.processScope)
2254
- const initialized = yield* initializeEffect.pipe(
2255
- Effect.onExit((exit) => {
2256
- if (Exit.isFailure(exit)) self.publishStartFailed(exit.cause)
2257
- return cleanupStartupFailure(exit)
2258
- }),
2259
- Effect.ensuring(Effect.sync(() => {
2260
- self.runState = "Idle"
2261
- }))
2262
- )
2263
- const initial = initialized.state
2264
- self.current = {
2265
- revision: 0,
2266
- terminalizing: false,
2267
- changes: undefined,
2268
- snapshot: { status: "active", state: initial }
2269
- }
2270
- self.publishInitialized(initial)
2271
- if (self.execution.drain._tag === "Process") {
2272
- self.processContext = {
2273
- ...self.processScope,
2274
- receive: Effect.never,
2275
- poll: Effect.sync(() => Option.map(pollCompactMailbox(self.mailbox), messageEvent)),
2276
- receiveMessage: Effect.never,
2277
- pollMessage: Effect.sync(() => self.pollCompiledMessage()),
2278
- completeMessage: (delivery) => self.completeCompiledMessage(delivery),
2279
- state: Effect.sync(() => self.current.snapshot.state),
2280
- setState: (state: unknown) => self.setActiveState(state),
2281
- updateState: (f) => self.updateState(f)
2282
- }
2283
- } else {
2284
- self.compiledContext = new CompiledProcessContextImpl(self.processScope, self.childRuntime.owned, self)
2285
- if ("executionState" in initialized) {
2286
- self.compiledContext.executionState = initialized.executionState
2287
- }
2288
- }
2289
-
2290
- if (self.options.onReadySync !== undefined && !self.options.onReadySync(self)) {
2291
- yield* self.requestTermination({ _tag: "Stopped" })
2292
- } else if (self.options.onReady !== undefined) {
2293
- yield* self.options.onReady(self, self.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid))
2294
- }
2295
- if (self.options.onSnapshot !== undefined) {
2296
- yield* notifyActiveSnapshot(self.options.onSnapshot, { status: "active", state: initial })
2297
- }
2298
- if (initialized.done === true && self.lifecycle === "Active") {
2299
- yield* self.requestTermination({ _tag: "Done", output: initialized.output })
2300
- }
2301
-
2302
- // A compiled machine startup plan has already settled entry actions,
2303
- // raised events, and eventless transitions. If it is known active and
2304
- // neither startup hooks nor emitted work queued an event, there is no
2305
- // first drain to perform. Future sends observe an idle run state and
2306
- // schedule the ordinary compiled worker.
2307
- if (
2308
- initialized.done === false && self.execution.childless &&
2309
- self.lifecycle === "Active" && self.mailbox.items === undefined
2310
- ) {
2311
- return self
2312
- }
2313
-
2314
- self.runState = "Draining"
2315
- yield* self.drainRuntime()
2316
- return self
2317
- })
2318
- }
2319
-
2320
- get state(): Effect.Effect<unknown> {
2321
- return Effect.sync(() => this.current.snapshot.state)
2322
- }
2323
-
2324
- get snapshot(): Effect.Effect<RuntimeSnapshot<unknown, unknown, unknown>> {
2325
- return Effect.sync(() => this.current.snapshot)
2326
- }
2327
-
2328
- get changes(): Stream.Stream<RuntimeSnapshot<unknown, unknown, unknown>> {
2329
- return this.changesStream()
2330
- }
2331
-
2332
- get emissions(): Stream.Stream<never> {
2333
- return (this.externalEmissions?.stream ?? this.emissionsStream()) as Stream.Stream<never>
2334
- }
2335
-
2336
- get join(): Effect.Effect<unknown, unknown> {
2337
- return Effect.suspend(() => {
2338
- if (this.lifecycle === "Completed") {
2339
- return this.resolveCompletion(this.completion!)
2340
- }
2341
- this.waiter ??= Deferred.makeUnsafe<unknown, unknown>()
2342
- return Deferred.await(this.waiter)
2343
- })
2344
- }
2345
-
2346
- get stop(): Effect.Effect<void> {
2347
- return Effect.uninterruptible(this.stopEffect())
2348
- }
2349
-
2350
- child(child: ChildSelector): Effect.Effect<Option.Option<any>> {
2351
- return this.childRuntime.get(child)
2352
- }
2353
-
2354
- childChanges(child: ChildSelector): Stream.Stream<Option.Option<any>> {
2355
- return this.childRuntime.changes(child)
2356
- }
2357
-
2358
- private requestTermination(requested: CompiledTermination): Effect.Effect<boolean> {
2359
- return Effect.sync(() => this.requestTerminationSync(requested))
2360
- }
2361
-
2362
- private hasTerminationRequest(): boolean {
2363
- return this.lifecycle === "TerminationRequested"
2364
- }
2365
-
2366
- private requestTerminationSync(requested: CompiledTermination): boolean {
2367
- if (this.lifecycle !== "Active") {
2368
- return false
2369
- }
2370
- this.lifecycle = "TerminationRequested"
2371
- this.termination = requested
2372
- this.terminationSnapshot = this.reserveTermination(requested)
2373
- return true
2374
- }
2375
-
2376
- private reserveTermination(
2377
- requested: CompiledTermination
2378
- ): RuntimeSnapshot<unknown, unknown, unknown> | undefined {
2379
- const latest = this.current
2380
- if (latest === undefined || latest.terminalizing || latest.snapshot.status !== "active") {
2381
- return undefined
2382
- }
2383
- const snapshot: RuntimeSnapshot<unknown, unknown, unknown> = requested._tag === "Stopped"
2384
- ? { status: "stopped", state: latest.snapshot.state }
2385
- : requested._tag === "Done"
2386
- ? { status: "done", state: latest.snapshot.state, output: requested.output }
2387
- : { status: "error", state: latest.snapshot.state, cause: requested.cause }
2388
- this.current = { ...latest, terminalizing: true }
2389
- return snapshot
2390
- }
2391
-
2392
- private stopFromProcess(): Effect.Effect<void> {
2393
- const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid)
2394
- return this.runState === "Initializing" ? request : request.pipe(Effect.andThen(Effect.interrupt))
2395
- }
2396
-
2397
- private failCause(cause: Cause.Cause<unknown>): Effect.Effect<void> {
2398
- const requested = { _tag: "Failure", cause } as const
2399
- return this.requestTermination(requested).pipe(
2400
- Effect.flatMap((accepted) =>
2401
- accepted
2402
- ? Effect.forkDetach(this.settleRequestedTermination()).pipe(Effect.asVoid)
2403
- : Effect.void
2404
- )
2405
- )
2406
- }
2407
-
2408
- private sendAcknowledgedEffect(
2409
- event: unknown
2410
- ): Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError> {
2411
- return Effect.uninterruptibleMask((restore) =>
2412
- Deferred.make<AcknowledgedDelivery<unknown>, unknown>().pipe(
2413
- Effect.flatMap((deferred) =>
2414
- this.offerEvent(event, undefined, undefined, deferred).pipe(
2415
- Effect.andThen(restore(Deferred.await(deferred)))
2416
- )
2417
- )
2418
- )
2419
- )
2420
- }
2421
-
2422
- private offerEvent(
2423
- event: unknown,
2424
- source: Inspection.Subject | undefined,
2425
- causedBy: Inspection.Causation | undefined,
2426
- deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
2427
- ): Effect.Effect<void, StoppedError> {
2428
- return Effect.suspend(() => {
2429
- const inspector = this.inspector
2430
- const subject = this.inspectionSubject
2431
- const message: ProcessMessage<unknown> = inspector?.isActive() === true && subject !== undefined
2432
- ? makeInspectedMessage(
2433
- inspector,
2434
- subject,
2435
- event,
2436
- source,
2437
- causedBy,
2438
- deferred
2439
- )
2440
- : deferred === undefined
2441
- ? event
2442
- : { [AcknowledgedMessageTypeId]: true as const, event, deferred }
2443
- return this.offerMessage(message)
2444
- })
2445
- }
2446
-
2447
- private offerMessage(message: ProcessMessage<unknown>): Effect.Effect<void, StoppedError> {
2448
- return Effect.uninterruptible(
2449
- Effect.suspend(() => {
2450
- if (this.mailbox.closed || this.lifecycle !== "Active") {
2451
- return Effect.fail(new StoppedError())
2452
- }
2453
- offerCompactMailbox(this.mailbox, message)
2454
- const inspector = this.inspector
2455
- const subject = this.inspectionSubject
2456
- if (inspector !== undefined && subject !== undefined) publishInspectedSent(inspector, subject, message)
2457
- this.offerRevision += 1
2458
- if (this.runState === "Draining") {
2459
- return Effect.void
2460
- }
2461
- this.runState = "Draining"
2462
- const scheduled = Effect.yieldNow.pipe(
2463
- Effect.andThen(Effect.provideContext(this.drainRuntime(), this.services))
2464
- )
2465
- const fork = this.options.detached === true
2466
- ? Effect.forkDetach(scheduled, { startImmediately: true })
2467
- : Effect.forkChild(scheduled, { startImmediately: true })
2468
- return fork.pipe(
2469
- Effect.flatMap((fiber) =>
2470
- Effect.sync(() => {
2471
- this.worker = fiber
2472
- if (!this.interruptRequested) {
2473
- return false
2474
- }
2475
- this.interruptRequested = false
2476
- return true
2477
- }).pipe(
2478
- Effect.flatMap((interrupt) => interrupt ? this.interruptAndFinish(fiber) : Effect.void)
2479
- )
2480
- ),
2481
- Effect.asVoid
2482
- )
2483
- })
2484
- )
2485
- }
2486
-
2487
- private stopEffect(): Effect.Effect<void> {
2488
- return Effect.suspend(() => {
2489
- if (this.lifecycle === "Completed") {
2490
- return Effect.void
2491
- }
2492
- if (this.finishIdleChildlessStop()) {
2493
- return Effect.void
2494
- }
2495
- const requested = { _tag: "Stopped" } as const
2496
- return this.requestTermination(requested).pipe(
2497
- Effect.flatMap((accepted) =>
2498
- accepted
2499
- ? this.settleRequestedTermination()
2500
- : this.awaitCompletion()
2501
- )
2502
- )
2503
- })
2504
- }
2505
-
2506
- private finishIdleChildlessStop(): boolean {
2507
- if (
2508
- !this.execution.childless || this.runState !== "Idle" || this.worker !== undefined ||
2509
- this.lifecycle !== "Active" ||
2510
- (this.options.onOutcome !== undefined && this.options.skipStoppedOutcome !== true) ||
2511
- this.options.onStop !== undefined ||
2512
- this.inspector !== undefined ||
2513
- this.current.changes !== undefined ||
2514
- this.current.terminalizing || this.current.snapshot.status !== "active"
2515
- ) {
2516
- return false
2517
- }
2518
- const snapshot = { status: "stopped" as const, state: this.current.snapshot.state }
2519
- this.lifecycle = "TerminationRequested"
2520
- this.termination = { _tag: "Stopped" }
2521
- this.terminationSnapshot = snapshot
2522
- closeCompactMailbox(this.mailbox)
2523
- this.current = {
2524
- revision: this.current.revision + 1,
2525
- terminalizing: true,
2526
- changes: undefined,
2527
- snapshot
2528
- }
2529
- stopAcknowledgedMessage(this.inFlightMessage)
2530
- this.inFlightMessage = undefined
2531
- this.interruptRequested = false
2532
- if (this.compiledContext !== undefined) {
2533
- this.compiledContext.executionState = undefined
2534
- }
2535
- this.options.onStopSync?.()
2536
- this.completion = CompiledStoppedCompletion
2537
- this.lifecycle = "Completed"
2538
- if (this.waiter !== undefined) {
2539
- Deferred.doneUnsafe(this.waiter, this.resolveCompletion(CompiledStoppedCompletion))
2540
- this.waiter = undefined
2541
- }
2542
- return true
2543
- }
2544
-
2545
- private settleRequestedTermination(): Effect.Effect<void> {
2546
- return Effect.suspend(() => {
2547
- if (this.runState !== "Draining") {
2548
- return this.finishRequestedTermination()
2549
- }
2550
- if (this.worker === undefined) {
2551
- this.interruptRequested = true
2552
- return this.awaitCompletion()
2553
- }
2554
- return this.interruptAndFinish(this.worker).pipe(
2555
- Effect.andThen(this.awaitCompletion())
2556
- )
2557
- })
2558
- }
2559
-
2560
- private interruptAndFinish(worker: Fiber.Fiber<any, never>): Effect.Effect<void> {
2561
- return Fiber.interrupt(worker).pipe(
2562
- Effect.andThen(
2563
- Effect.suspend(() =>
2564
- this.lifecycle !== "Completed"
2565
- ? this.finishRequestedTermination()
2566
- : Effect.void
2567
- )
2568
- )
2569
- )
2570
- }
2571
-
2572
- private awaitCompletion(): Effect.Effect<void> {
2573
- return this.lifecycle !== "Completed"
2574
- ? this.join.pipe(Effect.exit, Effect.asVoid)
2575
- : Effect.void
2576
- }
2577
-
2578
- private resolveCompletion(completion: CompiledCompletion): Effect.Effect<unknown, unknown> {
2579
- if (completion !== CompiledStoppedCompletion) {
2580
- return completion
2581
- }
2582
- const stopped = Effect.fail(new StoppedError())
2583
- this.completion = stopped
2584
- return stopped
2585
- }
2586
-
2587
- private drainRuntime(): Effect.Effect<void, never, any> {
2588
- const self = this
2589
- return Effect.uninterruptibleMask((restore) =>
2590
- Effect.gen(function*() {
2591
- let observedRevision = self.offerRevision
2592
- while (true) {
2593
- if (self.hasTerminationRequest()) {
2594
- return yield* self.finishRequestedTermination()
2595
- }
2596
-
2597
- const exit = yield* restore(
2598
- Effect.suspend(() => {
2599
- const drain = self.execution.drain
2600
- return drain._tag === "Process"
2601
- ? drain.run(self.processContext!)
2602
- : drain.run(self.compiledContext!)
2603
- })
2604
- ).pipe(Effect.exit)
2605
- self.flushPendingChanges()
2606
- if (Exit.isFailure(exit)) {
2607
- if (self.lifecycle === "Active") {
2608
- yield* self.requestTermination({ _tag: "Failure", cause: exit.cause })
2609
- }
2610
- return yield* self.finishRequestedTermination()
2611
- }
2612
- if (Option.isSome(exit.value)) {
2613
- yield* self.requestTermination({ _tag: "Done", output: exit.value.value })
2614
- return yield* self.finishRequestedTermination()
2615
- }
2616
- if (self.hasTerminationRequest()) {
2617
- return yield* self.finishRequestedTermination()
2618
- }
2619
-
2620
- if (self.offerRevision !== observedRevision) {
2621
- observedRevision = self.offerRevision
2622
- continue
2623
- }
2624
- self.runState = "Idle"
2625
- self.worker = undefined
2626
- return
2627
- }
2628
- })
2629
- )
2630
- }
2631
-
2632
- private finishRequestedTermination(): Effect.Effect<void> {
2633
- return Effect.suspend(() => {
2634
- if (this.lifecycle !== "TerminationRequested") {
2635
- return Effect.void
2636
- }
2637
- const requested = this.termination
2638
- if (requested === undefined) {
2639
- return Effect.void
2640
- }
2641
- const snapshot = this.terminationSnapshot ?? this.reserveTermination(requested)
2642
- if (snapshot === undefined) {
2643
- return this.awaitCompletion()
2644
- }
2645
- const exit = requested._tag === "Stopped"
2646
- ? Exit.void
2647
- : requested._tag === "Done"
2648
- ? Exit.succeed(requested.output)
2649
- : Exit.failCause(requested.cause)
2650
- const completion: CompiledCompletion = requested._tag === "Stopped"
2651
- ? CompiledStoppedCompletion
2652
- : requested._tag === "Done"
2653
- ? Effect.succeed(requested.output)
2654
- : Effect.failCause(requested.cause)
2655
- const notifyOutcome = this.options.onOutcome === undefined ||
2656
- (requested._tag === "Stopped" && this.options.skipStoppedOutcome === true)
2657
- ? Effect.void
2658
- : Effect.suspend(() => this.options.onOutcome!(classifyOutcome(snapshot)!)).pipe(
2659
- Effect.exit,
2660
- Effect.asVoid
2661
- )
2662
- const inspector = this.inspector
2663
- const subject = this.inspectionSubject
2664
- const closeEmissionsAndInspect = inspector === undefined || subject === undefined
2665
- ? this.closeEmissions()
2666
- : this.closeEmissions().pipe(
2667
- Effect.andThen(Effect.sync(() =>
2668
- inspector.publishUnsafe(
2669
- this.activity === undefined
2670
- ? { _tag: "Terminated", subject, snapshot }
2671
- : {
2672
- _tag: "ActivityStopped",
2673
- subject: this.activity.owner,
2674
- activity: this.activity,
2675
- exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
2676
- }
2677
- )
2678
- ))
2679
- )
2680
- return Effect.uninterruptible(
2681
- Effect.sync(() => {
2682
- closeCompactMailbox(this.mailbox)
2683
- }).pipe(
2684
- Effect.andThen(this.childRuntime.close(exit)),
2685
- Effect.andThen(this.setAndPublishSnapshot(snapshot)),
2686
- Effect.andThen(closeEmissionsAndInspect),
2687
- Effect.andThen(Effect.sync(() => {
2688
- if (requested._tag === "Failure") {
2689
- failAcknowledgedMessage(this.inFlightMessage, requested.cause)
2690
- } else {
2691
- stopAcknowledgedMessage(this.inFlightMessage)
2692
- }
2693
- this.inFlightMessage = undefined
2694
- })),
2695
- Effect.andThen(notifyOutcome),
2696
- Effect.andThen(this.options.onStop ?? Effect.void),
2697
- Effect.andThen(
2698
- this.options.inspectionRoot === true && this.inspector !== undefined
2699
- ? this.inspector.close
2700
- : Effect.void
2701
- ),
2702
- Effect.andThen(Effect.sync(() => {
2703
- this.options.onStopSync?.()
2704
- this.runState = "Idle"
2705
- this.worker = undefined
2706
- this.interruptRequested = false
2707
- if (this.compiledContext !== undefined) {
2708
- this.compiledContext.executionState = undefined
2709
- }
2710
- this.completion = completion
2711
- this.lifecycle = "Completed"
2712
- if (this.waiter !== undefined) {
2713
- Deferred.doneUnsafe(this.waiter, this.resolveCompletion(completion))
2714
- this.waiter = undefined
2715
- }
2716
- }))
2717
- )
2718
- )
2719
- })
2720
- }
2721
-
2722
- private publishSnapshot(
2723
- snapshot: VersionedSnapshot<unknown, unknown, unknown>
2724
- ): Effect.Effect<VersionedSnapshot<unknown, unknown, unknown>> {
2725
- const publish = snapshot.changes === undefined
2726
- ? Effect.succeed(snapshot)
2727
- : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
2728
- const current = snapshot.snapshot
2729
- return this.options.onSnapshot === undefined || current.status !== "active"
2730
- ? publish
2731
- : publish.pipe(Effect.tap(() => notifyActiveSnapshot(this.options.onSnapshot!, current)))
2732
- }
2733
-
2734
- private completeChanges(snapshot: VersionedSnapshot<unknown, unknown, unknown>): Effect.Effect<void> {
2735
- return snapshot.changes === undefined
2736
- ? Effect.void
2737
- : PubSub.publish(snapshot.changes, Exit.succeed<void>(undefined)).pipe(Effect.asVoid)
2738
- }
2739
-
2740
- private emitEvent(event: unknown): Effect.Effect<void> {
2741
- const publish = this.externalEmissions !== undefined ?
2742
- this.externalEmissions.emit(event) :
2743
- Effect.suspend(() =>
2744
- this.emissionsPubSub === undefined || this.emissionsPubSub === EmissionsClosed
2745
- ? Effect.void
2746
- : PubSub.publish(this.emissionsPubSub, event).pipe(Effect.asVoid)
2747
- )
2748
- const inspector = this.inspector
2749
- const subject = this.inspectionSubject
2750
- if (inspector === undefined || subject === undefined) return publish
2751
- return publish.pipe(Effect.tap(() =>
2752
- Effect.sync(() =>
2753
- inspector.publishUnsafe({
2754
- _tag: "Emitted",
2755
- subject,
2756
- emission: event,
2757
- causedBy: this.causation()
2758
- })
2759
- )
2760
- ))
2761
- }
2762
-
2763
- shutdownEmissions(): Effect.Effect<void> {
2764
- return this.closeEmissions()
2765
- }
2766
-
2767
- private closeEmissions(): Effect.Effect<void> {
2768
- if (this.externalEmissions !== undefined) return this.externalEmissions.close()
2769
- const observed = this.emissionsPubSub
2770
- this.emissionsPubSub = EmissionsClosed
2771
- return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed)
2772
- }
2773
-
2774
- private getOrCreateEmissions(): Effect.Effect<PubSub.PubSub<unknown> | undefined> {
2775
- return Effect.suspend(() => {
2776
- const observed = this.emissionsPubSub
2777
- if (observed === EmissionsClosed) return Effect.succeed(undefined)
2778
- if (observed !== undefined) return Effect.succeed(observed)
2779
- return PubSub.unbounded<unknown>().pipe(
2780
- Effect.flatMap((candidate) =>
2781
- Effect.sync(() => {
2782
- const latest = this.emissionsPubSub
2783
- if (latest === EmissionsClosed) return [undefined, true] as const
2784
- if (latest !== undefined) return [latest, true] as const
2785
- this.emissionsPubSub = candidate
2786
- return [candidate, false] as const
2787
- }).pipe(
2788
- Effect.flatMap(([selected, discard]) =>
2789
- discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)
2790
- )
2791
- )
2792
- )
2793
- )
2794
- })
2795
- }
2796
-
2797
- private emissionsStream(): Stream.Stream<unknown> {
2798
- return Stream.unwrap(
2799
- this.getOrCreateEmissions().pipe(
2800
- Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))
2801
- )
2802
- )
2803
- }
2804
-
2805
- private setAndPublishSnapshot(snapshot: RuntimeSnapshot<unknown, unknown, unknown>): Effect.Effect<void> {
2806
- return Effect.suspend(() => {
2807
- this.flushPendingChanges()
2808
- const versioned = {
2809
- revision: this.current.revision + 1,
2810
- snapshot,
2811
- terminalizing: true,
2812
- changes: this.current.changes
2813
- }
2814
- this.current = versioned
2815
- return this.publishSnapshot(versioned).pipe(
2816
- Effect.flatMap((published) => this.completeChanges(published)),
2817
- Effect.asVoid
2818
- )
2819
- })
2820
- }
2821
-
2822
- private setActiveState(state: unknown): Effect.Effect<void> {
2823
- return Effect.suspend(() => this.commitActiveState(state) ?? Effect.void)
2824
- }
2825
-
2826
- pollCompiledMessage(): Option.Option<ProcessMessage<unknown>> {
2827
- const message = pollCompactMailbox(this.mailbox)
2828
- if (Option.isSome(message)) {
2829
- this.inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined
2830
- }
2831
- return message
2832
- }
2833
-
2834
- completeCompiledMessage(delivery: AcknowledgedDelivery<unknown>): void {
2835
- succeedAcknowledgedMessage(this.inFlightMessage, delivery)
2836
- this.inFlightMessage = undefined
2837
- }
2838
-
2839
- compiledState(): unknown {
2840
- return this.current.snapshot.state
2841
- }
2842
-
2843
- commitCompiledState(state: unknown): Effect.Effect<void> | undefined {
2844
- return this.commitActiveState(state, true)
2845
- }
2846
-
2847
- private commitActiveState(state: unknown, batchChanges = false): Effect.Effect<void> | undefined {
2848
- const latest = this.current
2849
- if (latest.terminalizing || latest.snapshot.status !== "active") {
2850
- return undefined
2851
- }
2852
- const pendingChanges = latest.pendingChanges
2853
- if (pendingChanges !== undefined) {
2854
- latest.pendingChanges = undefined
2855
- }
2856
- const activeSnapshot = { status: "active" as const, state }
2857
- const versioned = {
2858
- revision: latest.revision + 1,
2859
- snapshot: activeSnapshot,
2860
- terminalizing: false,
2861
- changes: latest.changes
2862
- } as VersionedSnapshot<unknown, unknown, unknown>
2863
- this.current = versioned
2864
- if (versioned.changes !== undefined) {
2865
- if (pendingChanges === undefined) {
2866
- if (batchChanges) {
2867
- versioned.pendingChanges = [versioned]
2868
- } else {
2869
- PubSub.publishUnsafe(versioned.changes, [versioned] as const)
2870
- }
2871
- } else {
2872
- pendingChanges.push(versioned)
2873
- if (batchChanges) {
2874
- versioned.pendingChanges = pendingChanges
2875
- } else {
2876
- PubSub.publishUnsafe(versioned.changes, pendingChanges)
2877
- }
2878
- }
2879
- }
2880
- return this.options.onSnapshot === undefined
2881
- ? undefined
2882
- : notifyActiveSnapshot(this.options.onSnapshot, activeSnapshot)
2883
- }
2884
-
2885
- flushPendingChanges(): void {
2886
- const current = this.current
2887
- const pendingChanges = current?.pendingChanges
2888
- if (pendingChanges === undefined || current.changes === undefined) {
2889
- return
2890
- }
2891
- current.pendingChanges = undefined
2892
- PubSub.publishUnsafe(current.changes, pendingChanges)
2893
- }
2894
-
2895
- private updateState<E, R>(
2896
- f: (state: unknown) => Effect.Effect<unknown, E, R>
2897
- ): Effect.Effect<void, E, R> {
2898
- return Effect.suspend(() => {
2899
- const observed = this.current
2900
- if (observed.terminalizing || observed.snapshot.status !== "active") {
2901
- return Effect.void
2902
- }
2903
- return f(observed.snapshot.state).pipe(
2904
- Effect.flatMap((state) => {
2905
- const latest = this.current
2906
- return latest.terminalizing || latest.revision !== observed.revision
2907
- ? Effect.void
2908
- : this.setActiveState(state)
2909
- })
2910
- )
2911
- })
2912
- }
2913
-
2914
- private getOrCreateChanges(): Effect.Effect<
2915
- PubSub.PubSub<Take.Take<VersionedSnapshot<unknown, unknown, unknown>>> | undefined
2916
- > {
2917
- return Effect.suspend(() => {
2918
- const observed = this.current
2919
- if (observed.snapshot.status !== "active") {
2920
- return Effect.succeed(undefined)
2921
- }
2922
- if (observed.changes !== undefined) {
2923
- return Effect.succeed(observed.changes)
2924
- }
2925
- return PubSub.unbounded<Take.Take<VersionedSnapshot<unknown, unknown, unknown>>>({ replay: 1 }).pipe(
2926
- Effect.flatMap((candidate) =>
2927
- Effect.sync(() => {
2928
- const latest = this.current
2929
- if (latest.snapshot.status !== "active") {
2930
- return [undefined, true] as const
2931
- }
2932
- if (latest.changes !== undefined) {
2933
- return [latest.changes, true] as const
2934
- }
2935
- this.current = { ...latest, changes: candidate }
2936
- return [candidate, false] as const
2937
- }).pipe(
2938
- Effect.flatMap(([changes, discard]) =>
2939
- discard ? PubSub.shutdown(candidate).pipe(Effect.as(changes)) : Effect.succeed(changes)
2940
- )
2941
- )
2942
- )
2943
- )
2944
- })
2945
- }
2946
-
2947
- private changesStream(): Stream.Stream<RuntimeSnapshot<unknown, unknown, unknown>> {
2948
- const self = this
2949
- return Stream.unwrap(
2950
- Effect.gen(function*() {
2951
- const changes = yield* self.getOrCreateChanges()
2952
- if (changes === undefined) {
2953
- return Stream.succeed(self.current.snapshot)
2954
- }
2955
- const subscription = yield* PubSub.subscribe(changes)
2956
- const captured = self.current
2957
- if (captured.snapshot.status !== "active") {
2958
- return Stream.succeed(captured.snapshot)
2959
- }
2960
- return Stream.succeed(captured.snapshot).pipe(
2961
- Stream.concat(
2962
- Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(
2963
- Stream.filter((next) => next.revision > captured.revision),
2964
- Stream.map((next) => next.snapshot)
2965
- )
2966
- )
2967
- )
2968
- })
2969
- )
2970
- }
2971
- }
2972
-
2973
- class CompiledProcessContextImpl implements CompiledProcessContext<unknown, unknown> {
2974
- executionState: unknown
2975
-
2976
- constructor(
2977
- readonly scope: ProcessScope<unknown>,
2978
- readonly ownedChildren: OwnedChildRuntime,
2979
- private readonly process: CompiledProcess
2980
- ) {}
2981
-
2982
- poll(): Option.Option<unknown> {
2983
- return Option.map(this.process.pollCompiledMessage(), messageEvent)
2984
- }
2985
-
2986
- pollMessage(): Option.Option<ProcessMessage<unknown>> {
2987
- return this.process.pollCompiledMessage()
2988
- }
2989
-
2990
- state(): unknown {
2991
- return this.process.compiledState()
2992
- }
2993
-
2994
- completeMessage(delivery: AcknowledgedDelivery<unknown>): void {
2995
- this.process.completeCompiledMessage(delivery)
2996
- }
2997
-
2998
- commit(state: unknown): Effect.Effect<void> | undefined {
2999
- return this.process.commitCompiledState(state)
3000
- }
3001
-
3002
- runAfterChanges<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
3003
- this.process.flushPendingChanges()
3004
- return effect
3005
- }
3006
- }
3007
-
3008
- const startCompactCompiledInternal: typeof startGenericInternal = Effect.fnUntraced(function*(
3009
- logic: ProcessLogic<any, any, any, any, any, any>,
3010
- options: StartInternalOptions
3011
- ) {
3012
- const sessionId = options.sessionId ?? (yield* options.runtime.nextSessionId)
3013
- const services = yield* Effect.context<any>()
3014
- const execution = logic.execution as CompiledProcessExecution<any, any, any, any, any, any>
3015
- const process = new CompiledProcess(logic, options, services, sessionId)
3016
- // A compiled initializer is synchronous by construction. Only startup
3017
- // callbacks that themselves return Effects need the generic initialization
3018
- // program; the compiled drain is still provided the complete service context.
3019
- const initialize = execution.initialSync !== undefined &&
3020
- options.onReady === undefined && options.onSnapshot === undefined
3021
- ? process.initializeCompiledSync()
3022
- : process.initialize()
3023
- return yield* initialize.pipe(
3024
- Effect.onExit((exit) =>
3025
- Exit.isFailure(exit)
3026
- ? process.shutdownEmissions().pipe(
3027
- Effect.andThen(
3028
- options.inspectionRoot === true && options.runtime.inspection !== undefined
3029
- ? options.runtime.inspection.close
3030
- : Effect.void
3031
- )
3032
- )
3033
- : Effect.void
3034
- )
3035
- )
3036
- }) as typeof startGenericInternal
3037
-
3038
- const startLogicInternal: typeof startGenericInternal = ((
7
+ import { startCompactCompiledInternal, startCompiledSync } from "./runtimeCompiled.js"
8
+ import { startGenericInternal } from "./runtimeGeneric.js"
9
+ import {
10
+ type MachineRef,
11
+ makeEmissionRuntime,
12
+ makeProcessRuntime,
13
+ type PreparedProcess,
14
+ type ProcessLogic,
15
+ type StartInternalOptions,
16
+ type StartProcess
17
+ } from "./runtimeProtocol.js"
18
+
19
+ const startLogicInternal: StartProcess = ((
3039
20
  logic: ProcessLogic<any, any, any, any, any, any>,
3040
21
  options: StartInternalOptions
3041
22
  ) =>
3042
23
  logic.execution?._tag === "Compiled"
3043
24
  ? startCompactCompiledInternal(logic, options)
3044
- : startGenericInternal(logic, options)) as typeof startGenericInternal
25
+ : startGenericInternal(logic, options)) as StartProcess
26
+
27
+ const makeRuntime = makeProcessRuntime(startLogicInternal, startCompiledSync)
3045
28
 
3046
29
  export type ProcessRuntimeStrategy = "generic" | "compiled" | "auto"
3047
30
 
@@ -3052,7 +35,7 @@ const startProcessWithStrategy = Effect.fnUntraced(function*(
3052
35
  readonly id?: string
3053
36
  }
3054
37
  ) {
3055
- const runtime = yield* makeProcessRuntime
38
+ const runtime = yield* makeRuntime
3056
39
  const internalOptions: StartInternalOptions = options === undefined
3057
40
  ? {
3058
41
  detached: true,
@@ -3117,7 +100,7 @@ export const startProcess: <
3117
100
  readonly id?: string
3118
101
  }
3119
102
  ) {
3120
- const runtime = yield* makeProcessRuntime
103
+ const runtime = yield* makeRuntime
3121
104
  return yield* startLogicInternal(
3122
105
  logic,
3123
106
  options === undefined
@@ -3148,7 +131,7 @@ const prepareProcessWithStrategy = Effect.fnUntraced(function*<
3148
131
  readonly id?: string
3149
132
  }
3150
133
  ) {
3151
- const runtime = yield* makeProcessRuntime
134
+ const runtime = yield* makeRuntime
3152
135
  const sessionId = yield* runtime.nextSessionId
3153
136
  const inspection = yield* InspectionRuntime.make(sessionId)
3154
137
  runtime.inspection = inspection