@typeonce/effect-machine 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +272 -628
  2. package/dist/Machine.d.ts +1076 -896
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +141 -90
  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 -2
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -64
  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 +15 -22
  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/initialDeclaration.d.ts +14 -0
  34. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
  35. package/dist/internal/machine/initialDeclaration.js +137 -0
  36. package/dist/internal/machine/initialDeclaration.js.map +1 -0
  37. package/dist/internal/machine/invocation.d.ts +1 -1
  38. package/dist/internal/machine/invocation.d.ts.map +1 -1
  39. package/dist/internal/machine/invocation.js +1 -1
  40. package/dist/internal/machine/invocation.js.map +1 -1
  41. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  42. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  43. package/dist/internal/machine/machine.d.ts +13 -4
  44. package/dist/internal/machine/machine.d.ts.map +1 -1
  45. package/dist/internal/machine/machine.js +169 -388
  46. package/dist/internal/machine/machine.js.map +1 -1
  47. package/dist/internal/machine/planner.d.ts +8 -0
  48. package/dist/internal/machine/planner.d.ts.map +1 -1
  49. package/dist/internal/machine/planner.js +37 -78
  50. package/dist/internal/machine/planner.js.map +1 -1
  51. package/dist/internal/machine/process.d.ts +8 -7
  52. package/dist/internal/machine/process.d.ts.map +1 -1
  53. package/dist/internal/machine/process.js +16 -12
  54. package/dist/internal/machine/process.js.map +1 -1
  55. package/dist/internal/machine/protocol.d.ts +1 -1
  56. package/dist/internal/machine/protocol.d.ts.map +1 -1
  57. package/dist/internal/machine/protocol.js.map +1 -1
  58. package/dist/internal/machine/runtime.d.ts +2 -230
  59. package/dist/internal/machine/runtime.d.ts.map +1 -1
  60. package/dist/internal/machine/runtime.js +8 -1857
  61. package/dist/internal/machine/runtime.js.map +1 -1
  62. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  63. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeCompiled.js +867 -0
  65. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  66. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  68. package/dist/internal/machine/runtimeGeneric.js +471 -0
  69. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  71. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  72. package/dist/internal/machine/runtimeProtocol.js +561 -0
  73. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  74. package/dist/internal/machine/stateDefinition.d.ts +1 -1
  75. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  76. package/dist/internal/machine/stateDefinition.js +1 -13
  77. package/dist/internal/machine/stateDefinition.js.map +1 -1
  78. package/dist/internal/machine/targetReference.d.ts +15 -0
  79. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  80. package/dist/internal/machine/targetReference.js +41 -0
  81. package/dist/internal/machine/targetReference.js.map +1 -0
  82. package/dist/internal/machine/topology.d.ts.map +1 -1
  83. package/dist/internal/machine/topology.js +5 -3
  84. package/dist/internal/machine/topology.js.map +1 -1
  85. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  86. package/dist/internal/testing/machine/finiteModel.js +53 -46
  87. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  88. package/dist/internal/testing/machine/probe.js +1 -1
  89. package/dist/internal/testing/machine/probe.js.map +1 -1
  90. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/verification.js +7 -1
  92. package/dist/internal/testing/machine/verification.js.map +1 -1
  93. package/dist/testing/MachineTest.d.ts +105 -73
  94. package/dist/testing/MachineTest.d.ts.map +1 -1
  95. package/dist/testing/MachineTest.js +105 -73
  96. package/dist/testing/MachineTest.js.map +1 -1
  97. package/dist/unstable/cluster/ClusterMachine.d.ts +18 -13
  98. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  99. package/dist/unstable/cluster/ClusterMachine.js +18 -25
  100. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  101. package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
  102. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  103. package/dist/unstable/reactivity/AtomMachine.js +41 -24
  104. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  105. package/docs/agent-guide.md +66 -91
  106. package/docs/machine-review.md +19 -49
  107. package/docs/root-api.md +62 -62
  108. package/package.json +1 -1
  109. package/src/Machine.ts +1836 -2907
  110. package/src/internal/machine/childRegistry.ts +1 -1
  111. package/src/internal/machine/cluster.ts +7 -73
  112. package/src/internal/machine/clusterProtocol.ts +56 -0
  113. package/src/internal/machine/commandRuntime.ts +1 -1
  114. package/src/internal/machine/configuration.ts +53 -65
  115. package/src/internal/machine/declaration.ts +140 -0
  116. package/src/internal/machine/executionPlan.ts +16 -22
  117. package/src/internal/machine/implementation.ts +41 -0
  118. package/src/internal/machine/initialDeclaration.ts +157 -0
  119. package/src/internal/machine/invocation.ts +3 -3
  120. package/src/internal/machine/invocationDefinition.ts +1 -1
  121. package/src/internal/machine/machine.ts +225 -576
  122. package/src/internal/machine/planner.ts +84 -118
  123. package/src/internal/machine/process.ts +40 -33
  124. package/src/internal/machine/protocol.ts +3 -3
  125. package/src/internal/machine/runtime.ts +20 -3037
  126. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  127. package/src/internal/machine/runtimeGeneric.ts +799 -0
  128. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  129. package/src/internal/machine/stateDefinition.ts +1 -15
  130. package/src/internal/machine/targetReference.ts +55 -0
  131. package/src/internal/machine/topology.ts +5 -3
  132. package/src/internal/testing/machine/finiteModel.ts +58 -53
  133. package/src/internal/testing/machine/probe.ts +1 -1
  134. package/src/internal/testing/machine/verification.ts +7 -1
  135. package/src/testing/MachineTest.ts +105 -73
  136. package/src/unstable/cluster/ClusterMachine.ts +22 -25
  137. package/src/unstable/reactivity/AtomMachine.ts +41 -24
@@ -0,0 +1,1166 @@
1
+ /** Compiled statechart execution strategy. */
2
+ import * as Cause from "effect/Cause"
3
+ import * as Channel from "effect/Channel"
4
+ import * as Context from "effect/Context"
5
+ import * as Deferred from "effect/Deferred"
6
+ import * as Effect from "effect/Effect"
7
+ import * as Exit from "effect/Exit"
8
+ import * as Fiber from "effect/Fiber"
9
+ import * as Option from "effect/Option"
10
+ import * as PubSub from "effect/PubSub"
11
+ import * as Stream from "effect/Stream"
12
+ import type * as Take from "effect/Take"
13
+ import type { Inspection } from "../../Machine.js"
14
+ import { type ChildSelector } from "./childRegistry.js"
15
+ import { StoppedError } from "./errors.js"
16
+ import * as InspectionRuntime from "./inspectionRuntime.js"
17
+ import {
18
+ type AcknowledgedDelivery,
19
+ AcknowledgedMessageTypeId,
20
+ acknowledgedSend,
21
+ childlessRuntime,
22
+ type ChildRuntime,
23
+ classifyOutcome,
24
+ closeCompactMailbox,
25
+ type CompactProcessMailbox,
26
+ type CompiledProcessContext,
27
+ type CompiledProcessExecution,
28
+ type CompiledProcessInitial,
29
+ type EmissionRuntime,
30
+ EmissionsClosed,
31
+ failAcknowledgedMessage,
32
+ inspectionSubject,
33
+ isAcknowledgedMessage,
34
+ isMachineTarget,
35
+ type LazyEmissions,
36
+ type MachineRef,
37
+ makeChildRuntime,
38
+ makeChildRuntimeSync,
39
+ makeInspectedMessage,
40
+ messageCausation,
41
+ messageEvent,
42
+ noInspectInitial,
43
+ noParentSend,
44
+ notifyActiveSnapshot,
45
+ offerCompactMailbox,
46
+ type OwnedChildRuntime,
47
+ pollCompactMailbox,
48
+ type ProcessAddress,
49
+ type ProcessContext,
50
+ type ProcessLogic,
51
+ type ProcessMessage,
52
+ type ProcessRuntime,
53
+ type ProcessScope,
54
+ publishInspectedSent,
55
+ type RuntimeSnapshot,
56
+ sendMachineTarget,
57
+ type StartInternalOptions,
58
+ type StartProcess,
59
+ stopAcknowledgedMessage,
60
+ succeedAcknowledgedMessage,
61
+ type VersionedSnapshot
62
+ } from "./runtimeProtocol.js"
63
+
64
+ const CompiledStoppedCompletion: unique symbol = Symbol("effect/Machine/CompiledStoppedCompletion")
65
+
66
+ type CompiledCompletion =
67
+ | Effect.Effect<unknown, unknown>
68
+ | typeof CompiledStoppedCompletion
69
+
70
+ type CompiledLifecycle = "Active" | "TerminationRequested" | "Completed"
71
+ type CompiledRunState = "Initializing" | "Idle" | "Draining"
72
+
73
+ /**
74
+ * Compact runtime for compiled statecharts.
75
+ *
76
+ * All long-lived state is stored directly on this object. Operations are
77
+ * implemented by shared prototype methods, and public Effect / Stream values
78
+ * are materialized only when accessed. Arbitrary process logic continues to
79
+ * use the general runtime above.
80
+ */
81
+ class CompiledProcess implements MachineRef<any, any, any, any> {
82
+ readonly id: string
83
+ readonly sessionId: string
84
+ readonly inspectionSubject?: Inspection.Subject
85
+ readonly send: (event: unknown) => Effect.Effect<void, StoppedError>
86
+ sendInspected(
87
+ event: unknown,
88
+ source: Inspection.Subject | undefined,
89
+ causedBy: Inspection.Causation | undefined
90
+ ): Effect.Effect<void, StoppedError> {
91
+ return this.offerEvent(event, source, causedBy)
92
+ }
93
+ [acknowledgedSend](
94
+ event: unknown
95
+ ): Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError> {
96
+ return this.sendAcknowledgedEffect(event)
97
+ }
98
+
99
+ private readonly mailbox: CompactProcessMailbox<unknown> = {
100
+ items: undefined,
101
+ index: 0,
102
+ closed: false
103
+ }
104
+ private readonly address: ProcessAddress<unknown>
105
+ private childRuntime: ChildRuntime = childlessRuntime
106
+ private processScope!: ProcessScope<unknown>
107
+ private processContext: ProcessContext<unknown, unknown> | undefined
108
+ private compiledContext: CompiledProcessContext<unknown, unknown> | undefined
109
+ private current!: VersionedSnapshot<unknown, unknown, unknown>
110
+ /**
111
+ * `Active` has no terminal payload, `TerminationRequested` owns
112
+ * `termination` and its optional reserved snapshot, and `Completed` owns
113
+ * `completion`. `runState` independently tracks worker activity.
114
+ */
115
+ private lifecycle: CompiledLifecycle = "Active"
116
+ private runState: CompiledRunState = "Initializing"
117
+ private completion: CompiledCompletion | undefined
118
+ private waiter: Deferred.Deferred<unknown, unknown> | undefined
119
+ private termination: CompiledTermination | undefined
120
+ private terminationSnapshot: RuntimeSnapshot<unknown, unknown, unknown> | undefined
121
+ private worker: Fiber.Fiber<any, never> | undefined
122
+ private interruptRequested = false
123
+ private offerRevision = 0
124
+ private inFlightMessage: ProcessMessage<unknown> | undefined
125
+ private readonly externalEmissions: EmissionRuntime | undefined
126
+ private emissionsPubSub: LazyEmissions
127
+ private readonly activity?: Inspection.Activity
128
+ private initialEntryPaths?: ReadonlyArray<string>
129
+ private initialMicrosteps?: ReadonlyArray<unknown>
130
+ private initializing?: boolean
131
+
132
+ constructor(
133
+ private readonly logic: ProcessLogic<any, any, any, any, any, any>,
134
+ private readonly options: StartInternalOptions,
135
+ private readonly services: Context.Context<any>,
136
+ sessionId: string
137
+ ) {
138
+ this.sessionId = sessionId
139
+ this.id = options.id ?? sessionId
140
+ const inspector = options.runtime.inspection
141
+ if (inspector !== undefined) {
142
+ this.inspectionSubject = inspectionSubject(logic, this.id, sessionId)
143
+ this.initializing = true
144
+ if (options.activity !== undefined) this.activity = { ...options.activity, sessionId }
145
+ }
146
+ this.externalEmissions = options.emissions
147
+ this.send = inspector === undefined
148
+ ? (event) => this.offerMessage(event)
149
+ : (event) => this.offerEvent(event, undefined, undefined)
150
+ this.address = {
151
+ id: this.id,
152
+ sessionId,
153
+ stop: Effect.suspend(() => this.stopFromProcess()),
154
+ send: this.send,
155
+ ...(inspector === undefined
156
+ ? undefined
157
+ : {
158
+ inspectionSubject: this.inspectionSubject!,
159
+ sendInspected: (
160
+ event: unknown,
161
+ source: Inspection.Subject | undefined,
162
+ causedBy: Inspection.Causation | undefined
163
+ ) => this.offerEvent(event, source, causedBy)
164
+ })
165
+ }
166
+ }
167
+
168
+ private get inspector(): InspectionRuntime.Runtime | undefined {
169
+ return this.options.runtime.inspection
170
+ }
171
+
172
+ private causation(): Inspection.Causation | undefined {
173
+ return messageCausation(this.inFlightMessage, this.initializing === true)
174
+ }
175
+
176
+ private publishCreated(): void {
177
+ const inspector = this.inspector
178
+ const subject = this.inspectionSubject
179
+ if (inspector === undefined || subject === undefined) return
180
+ inspector.publishUnsafe(
181
+ this.activity === undefined
182
+ ? {
183
+ _tag: "Created",
184
+ subject,
185
+ parent: this.options.parent?.inspectionSubject,
186
+ origin: this.options.origin ?? { _tag: "Root" },
187
+ definition: this.logic.inspection?.definition
188
+ }
189
+ : { _tag: "ActivityStarted", subject: this.activity.owner, activity: this.activity }
190
+ )
191
+ }
192
+
193
+ private publishInitialized(state: unknown): void {
194
+ this.initializing = false
195
+ if (this.activity !== undefined) return
196
+ const inspector = this.inspector
197
+ const subject = this.inspectionSubject
198
+ if (inspector === undefined || subject === undefined) return
199
+ inspector.publishUnsafe({
200
+ _tag: "Initialized",
201
+ subject,
202
+ snapshot: { status: "active", state },
203
+ initialEntryPaths: this.initialEntryPaths ?? [],
204
+ microsteps: InspectionRuntime.microsteps({ microsteps: this.initialMicrosteps ?? [] })
205
+ })
206
+ }
207
+
208
+ private publishStartFailed(cause: Cause.Cause<unknown>): void {
209
+ this.initializing = false
210
+ const inspector = this.inspector
211
+ const subject = this.inspectionSubject
212
+ if (inspector === undefined || subject === undefined) return
213
+ inspector.publishUnsafe(
214
+ this.activity === undefined
215
+ ? { _tag: "StartFailed", subject, cause }
216
+ : {
217
+ _tag: "ActivityStopped",
218
+ subject: this.activity.owner,
219
+ activity: this.activity,
220
+ exit: Exit.failCause(cause)
221
+ }
222
+ )
223
+ }
224
+
225
+ private get execution(): CompiledProcessExecution<any, any, any, any, any, any> {
226
+ return this.logic.execution as CompiledProcessExecution<any, any, any, any, any, any>
227
+ }
228
+
229
+ initializeCompiledSync(): Effect.Effect<MachineRef<any, any, any, any>, unknown> {
230
+ this.publishCreated()
231
+ if (!this.execution.childless) {
232
+ this.childRuntime = makeChildRuntimeSync(
233
+ this.address,
234
+ this.options.runtime,
235
+ this.services,
236
+ (event) => this.sendAcknowledgedEffect(event)
237
+ )
238
+ }
239
+ const parent = this.options.parent
240
+ const sendParent = this.options.sendParent ?? (parent === undefined
241
+ ? noParentSend
242
+ : this.inspector === undefined
243
+ ? parent.send
244
+ : (event: unknown) => sendMachineTarget(parent, event, this.inspectionSubject, this.causation()))
245
+ this.processScope = {
246
+ self: this.address,
247
+ parent,
248
+ spawn: this.childRuntime.spawn,
249
+ sendParent,
250
+ emit: (event) => this.emitEvent(event),
251
+ sendTo: ((target: unknown, event: unknown) =>
252
+ isMachineTarget(target)
253
+ ? this.inspector === undefined
254
+ ? target.send(event)
255
+ : sendMachineTarget(target, event, this.inspectionSubject, this.causation())
256
+ : this.childRuntime.sendTo(
257
+ target as ChildSelector,
258
+ event,
259
+ this.inspectionSubject,
260
+ this.causation()
261
+ )) as ProcessScope<unknown>["sendTo"],
262
+ stopChild: this.childRuntime.stop,
263
+ failCause: (cause: Cause.Cause<unknown>) => this.failCause(cause),
264
+ inspectInitial: this.inspector === undefined
265
+ ? noInspectInitial
266
+ : (paths, microsteps = []) => {
267
+ this.initialEntryPaths = paths
268
+ this.initialMicrosteps = microsteps
269
+ }
270
+ }
271
+ const compiledInitial = this.execution.initialSync!
272
+ let initialized: CompiledInitialized
273
+ try {
274
+ initialized = compiledInitial(this.processScope)
275
+ } catch (error) {
276
+ this.runState = "Idle"
277
+ this.publishStartFailed(Cause.fail(error))
278
+ return Effect.fail(error)
279
+ }
280
+ this.runState = "Idle"
281
+ this.current = {
282
+ revision: 0,
283
+ terminalizing: false,
284
+ changes: undefined,
285
+ snapshot: { status: "active", state: initialized.state }
286
+ }
287
+ this.publishInitialized(initialized.state)
288
+ this.compiledContext = new CompiledProcessContextImpl(this.processScope, this.childRuntime.owned, this)
289
+ if ("executionState" in initialized) {
290
+ this.compiledContext.executionState = initialized.executionState
291
+ }
292
+ if (this.options.onReadySync !== undefined && !this.options.onReadySync(this)) {
293
+ this.requestTerminationSync({ _tag: "Stopped" })
294
+ }
295
+ if (initialized.done === true && this.lifecycle === "Active") {
296
+ this.requestTerminationSync({ _tag: "Done", output: initialized.output })
297
+ }
298
+ if (
299
+ initialized.done === false && this.execution.childless &&
300
+ this.lifecycle === "Active" &&
301
+ this.mailbox.items === undefined
302
+ ) {
303
+ return Effect.succeed(this)
304
+ }
305
+ this.runState = "Draining"
306
+ return Effect.provideContext(this.drainRuntime(), this.services).pipe(Effect.as(this))
307
+ }
308
+
309
+ initialize(): Effect.Effect<MachineRef<any, any, any, any>, unknown, any> {
310
+ const self = this
311
+ return Effect.gen(function*() {
312
+ self.publishCreated()
313
+ if (!self.execution.childless) {
314
+ self.childRuntime = yield* makeChildRuntime(
315
+ self.address,
316
+ self.options.runtime,
317
+ self.services,
318
+ (event) => self.sendAcknowledgedEffect(event)
319
+ )
320
+ }
321
+ const parent = self.options.parent
322
+ const sendParent = self.options.sendParent ?? (parent === undefined
323
+ ? noParentSend
324
+ : self.inspector === undefined
325
+ ? parent.send
326
+ : (event: unknown) => sendMachineTarget(parent, event, self.inspectionSubject, self.causation()))
327
+ self.processScope = {
328
+ self: self.address,
329
+ parent,
330
+ spawn: self.childRuntime.spawn,
331
+ sendParent,
332
+ emit: (event) => self.emitEvent(event),
333
+ sendTo: ((target: unknown, event: unknown) =>
334
+ isMachineTarget(target)
335
+ ? self.inspector === undefined
336
+ ? target.send(event)
337
+ : sendMachineTarget(target, event, self.inspectionSubject, self.causation())
338
+ : self.childRuntime.sendTo(
339
+ target as ChildSelector,
340
+ event,
341
+ self.inspectionSubject,
342
+ self.causation()
343
+ )) as ProcessScope<unknown>["sendTo"],
344
+ stopChild: self.childRuntime.stop,
345
+ failCause: (cause: Cause.Cause<unknown>) => self.failCause(cause),
346
+ inspectInitial: self.inspector === undefined
347
+ ? noInspectInitial
348
+ : (paths, microsteps = []) => {
349
+ self.initialEntryPaths = paths
350
+ self.initialMicrosteps = microsteps
351
+ }
352
+ }
353
+
354
+ const cleanupStartupFailure = <A, E>(exit: Exit.Exit<A, E>): Effect.Effect<void> =>
355
+ Exit.isFailure(exit) ? self.childRuntime.close(exit) : Effect.void
356
+ const compiledInitial = self.execution.initial
357
+ const initializeEffect: Effect.Effect<
358
+ {
359
+ readonly state: unknown
360
+ readonly done: boolean | undefined
361
+ readonly output: unknown
362
+ },
363
+ unknown,
364
+ any
365
+ > = compiledInitial === undefined
366
+ ? self.logic.initial(self.processScope).pipe(
367
+ Effect.map((state) => ({ state, done: undefined, output: undefined } as const))
368
+ )
369
+ : compiledInitial(self.processScope)
370
+ const initialized = yield* initializeEffect.pipe(
371
+ Effect.onExit((exit) => {
372
+ if (Exit.isFailure(exit)) self.publishStartFailed(exit.cause)
373
+ return cleanupStartupFailure(exit)
374
+ }),
375
+ Effect.ensuring(Effect.sync(() => {
376
+ self.runState = "Idle"
377
+ }))
378
+ )
379
+ const initial = initialized.state
380
+ self.current = {
381
+ revision: 0,
382
+ terminalizing: false,
383
+ changes: undefined,
384
+ snapshot: { status: "active", state: initial }
385
+ }
386
+ self.publishInitialized(initial)
387
+ if (self.execution.drain._tag === "Process") {
388
+ self.processContext = {
389
+ ...self.processScope,
390
+ receive: Effect.never,
391
+ poll: Effect.sync(() => Option.map(pollCompactMailbox(self.mailbox), messageEvent)),
392
+ receiveMessage: Effect.never,
393
+ pollMessage: Effect.sync(() => self.pollCompiledMessage()),
394
+ completeMessage: (delivery) => self.completeCompiledMessage(delivery),
395
+ state: Effect.sync(() => self.current.snapshot.state),
396
+ setState: (state: unknown) => self.setActiveState(state),
397
+ updateState: (f) => self.updateState(f)
398
+ }
399
+ } else {
400
+ self.compiledContext = new CompiledProcessContextImpl(self.processScope, self.childRuntime.owned, self)
401
+ if ("executionState" in initialized) {
402
+ self.compiledContext.executionState = initialized.executionState
403
+ }
404
+ }
405
+
406
+ if (self.options.onReadySync !== undefined && !self.options.onReadySync(self)) {
407
+ yield* self.requestTermination({ _tag: "Stopped" })
408
+ } else if (self.options.onReady !== undefined) {
409
+ yield* self.options.onReady(self, self.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid))
410
+ }
411
+ if (self.options.onSnapshot !== undefined) {
412
+ yield* notifyActiveSnapshot(self.options.onSnapshot, { status: "active", state: initial })
413
+ }
414
+ if (initialized.done === true && self.lifecycle === "Active") {
415
+ yield* self.requestTermination({ _tag: "Done", output: initialized.output })
416
+ }
417
+
418
+ // A compiled machine startup plan has already settled entry actions,
419
+ // raised events, and eventless transitions. If it is known active and
420
+ // neither startup hooks nor emitted work queued an event, there is no
421
+ // first drain to perform. Future sends observe an idle run state and
422
+ // schedule the ordinary compiled worker.
423
+ if (
424
+ initialized.done === false && self.execution.childless &&
425
+ self.lifecycle === "Active" && self.mailbox.items === undefined
426
+ ) {
427
+ return self
428
+ }
429
+
430
+ self.runState = "Draining"
431
+ yield* self.drainRuntime()
432
+ return self
433
+ })
434
+ }
435
+
436
+ get state(): Effect.Effect<unknown> {
437
+ return Effect.sync(() => this.current.snapshot.state)
438
+ }
439
+
440
+ get snapshot(): Effect.Effect<RuntimeSnapshot<unknown, unknown, unknown>> {
441
+ return Effect.sync(() => this.current.snapshot)
442
+ }
443
+
444
+ get changes(): Stream.Stream<RuntimeSnapshot<unknown, unknown, unknown>> {
445
+ return this.changesStream()
446
+ }
447
+
448
+ get emissions(): Stream.Stream<never> {
449
+ return (this.externalEmissions?.stream ?? this.emissionsStream()) as Stream.Stream<never>
450
+ }
451
+
452
+ get join(): Effect.Effect<unknown, unknown> {
453
+ return Effect.suspend(() => {
454
+ if (this.lifecycle === "Completed") {
455
+ return this.resolveCompletion(this.completion!)
456
+ }
457
+ this.waiter ??= Deferred.makeUnsafe<unknown, unknown>()
458
+ return Deferred.await(this.waiter)
459
+ })
460
+ }
461
+
462
+ get stop(): Effect.Effect<void> {
463
+ return Effect.uninterruptible(this.stopEffect())
464
+ }
465
+
466
+ child(child: ChildSelector): Effect.Effect<Option.Option<any>> {
467
+ return this.childRuntime.get(child)
468
+ }
469
+
470
+ childChanges(child: ChildSelector): Stream.Stream<Option.Option<any>> {
471
+ return this.childRuntime.changes(child)
472
+ }
473
+
474
+ private requestTermination(requested: CompiledTermination): Effect.Effect<boolean> {
475
+ return Effect.sync(() => this.requestTerminationSync(requested))
476
+ }
477
+
478
+ private hasTerminationRequest(): boolean {
479
+ return this.lifecycle === "TerminationRequested"
480
+ }
481
+
482
+ private requestTerminationSync(requested: CompiledTermination): boolean {
483
+ if (this.lifecycle !== "Active") {
484
+ return false
485
+ }
486
+ this.lifecycle = "TerminationRequested"
487
+ this.termination = requested
488
+ this.terminationSnapshot = this.reserveTermination(requested)
489
+ return true
490
+ }
491
+
492
+ private reserveTermination(
493
+ requested: CompiledTermination
494
+ ): RuntimeSnapshot<unknown, unknown, unknown> | undefined {
495
+ const latest = this.current
496
+ if (latest === undefined || latest.terminalizing || latest.snapshot.status !== "active") {
497
+ return undefined
498
+ }
499
+ const snapshot: RuntimeSnapshot<unknown, unknown, unknown> = requested._tag === "Stopped"
500
+ ? { status: "stopped", state: latest.snapshot.state }
501
+ : requested._tag === "Done"
502
+ ? { status: "done", state: latest.snapshot.state, output: requested.output }
503
+ : { status: "error", state: latest.snapshot.state, cause: requested.cause }
504
+ this.current = { ...latest, terminalizing: true }
505
+ return snapshot
506
+ }
507
+
508
+ private stopFromProcess(): Effect.Effect<void> {
509
+ const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid)
510
+ return this.runState === "Initializing" ? request : request.pipe(Effect.andThen(Effect.interrupt))
511
+ }
512
+
513
+ private failCause(cause: Cause.Cause<unknown>): Effect.Effect<void> {
514
+ const requested = { _tag: "Failure", cause } as const
515
+ return this.requestTermination(requested).pipe(
516
+ Effect.flatMap((accepted) =>
517
+ accepted
518
+ ? Effect.forkDetach(this.settleRequestedTermination()).pipe(Effect.asVoid)
519
+ : Effect.void
520
+ )
521
+ )
522
+ }
523
+
524
+ private sendAcknowledgedEffect(
525
+ event: unknown
526
+ ): Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError> {
527
+ return Effect.uninterruptibleMask((restore) =>
528
+ Deferred.make<AcknowledgedDelivery<unknown>, unknown>().pipe(
529
+ Effect.flatMap((deferred) =>
530
+ this.offerEvent(event, undefined, undefined, deferred).pipe(
531
+ Effect.andThen(restore(Deferred.await(deferred)))
532
+ )
533
+ )
534
+ )
535
+ )
536
+ }
537
+
538
+ private offerEvent(
539
+ event: unknown,
540
+ source: Inspection.Subject | undefined,
541
+ causedBy: Inspection.Causation | undefined,
542
+ deferred?: Deferred.Deferred<AcknowledgedDelivery<unknown>, unknown>
543
+ ): Effect.Effect<void, StoppedError> {
544
+ return Effect.suspend(() => {
545
+ const inspector = this.inspector
546
+ const subject = this.inspectionSubject
547
+ const message: ProcessMessage<unknown> = inspector?.isActive() === true && subject !== undefined
548
+ ? makeInspectedMessage(
549
+ inspector,
550
+ subject,
551
+ event,
552
+ source,
553
+ causedBy,
554
+ deferred
555
+ )
556
+ : deferred === undefined
557
+ ? event
558
+ : { [AcknowledgedMessageTypeId]: true as const, event, deferred }
559
+ return this.offerMessage(message)
560
+ })
561
+ }
562
+
563
+ private offerMessage(message: ProcessMessage<unknown>): Effect.Effect<void, StoppedError> {
564
+ return Effect.uninterruptible(
565
+ Effect.suspend(() => {
566
+ if (this.mailbox.closed || this.lifecycle !== "Active") {
567
+ return Effect.fail(new StoppedError())
568
+ }
569
+ offerCompactMailbox(this.mailbox, message)
570
+ const inspector = this.inspector
571
+ const subject = this.inspectionSubject
572
+ if (inspector !== undefined && subject !== undefined) publishInspectedSent(inspector, subject, message)
573
+ this.offerRevision += 1
574
+ if (this.runState === "Draining") {
575
+ return Effect.void
576
+ }
577
+ this.runState = "Draining"
578
+ const scheduled = Effect.yieldNow.pipe(
579
+ Effect.andThen(Effect.provideContext(this.drainRuntime(), this.services))
580
+ )
581
+ const fork = this.options.detached === true
582
+ ? Effect.forkDetach(scheduled, { startImmediately: true })
583
+ : Effect.forkChild(scheduled, { startImmediately: true })
584
+ return fork.pipe(
585
+ Effect.flatMap((fiber) =>
586
+ Effect.sync(() => {
587
+ this.worker = fiber
588
+ if (!this.interruptRequested) {
589
+ return false
590
+ }
591
+ this.interruptRequested = false
592
+ return true
593
+ }).pipe(
594
+ Effect.flatMap((interrupt) => interrupt ? this.interruptAndFinish(fiber) : Effect.void)
595
+ )
596
+ ),
597
+ Effect.asVoid
598
+ )
599
+ })
600
+ )
601
+ }
602
+
603
+ private stopEffect(): Effect.Effect<void> {
604
+ return Effect.suspend(() => {
605
+ if (this.lifecycle === "Completed") {
606
+ return Effect.void
607
+ }
608
+ if (this.finishIdleChildlessStop()) {
609
+ return Effect.void
610
+ }
611
+ const requested = { _tag: "Stopped" } as const
612
+ return this.requestTermination(requested).pipe(
613
+ Effect.flatMap((accepted) =>
614
+ accepted
615
+ ? this.settleRequestedTermination()
616
+ : this.awaitCompletion()
617
+ )
618
+ )
619
+ })
620
+ }
621
+
622
+ private finishIdleChildlessStop(): boolean {
623
+ if (
624
+ !this.execution.childless || this.runState !== "Idle" || this.worker !== undefined ||
625
+ this.lifecycle !== "Active" ||
626
+ (this.options.onOutcome !== undefined && this.options.skipStoppedOutcome !== true) ||
627
+ this.options.onStop !== undefined ||
628
+ this.inspector !== undefined ||
629
+ this.current.changes !== undefined ||
630
+ this.current.terminalizing || this.current.snapshot.status !== "active"
631
+ ) {
632
+ return false
633
+ }
634
+ const snapshot = { status: "stopped" as const, state: this.current.snapshot.state }
635
+ this.lifecycle = "TerminationRequested"
636
+ this.termination = { _tag: "Stopped" }
637
+ this.terminationSnapshot = snapshot
638
+ closeCompactMailbox(this.mailbox)
639
+ this.current = {
640
+ revision: this.current.revision + 1,
641
+ terminalizing: true,
642
+ changes: undefined,
643
+ snapshot
644
+ }
645
+ stopAcknowledgedMessage(this.inFlightMessage)
646
+ this.inFlightMessage = undefined
647
+ this.interruptRequested = false
648
+ if (this.compiledContext !== undefined) {
649
+ this.compiledContext.executionState = undefined
650
+ }
651
+ this.options.onStopSync?.()
652
+ this.completion = CompiledStoppedCompletion
653
+ this.lifecycle = "Completed"
654
+ if (this.waiter !== undefined) {
655
+ Deferred.doneUnsafe(this.waiter, this.resolveCompletion(CompiledStoppedCompletion))
656
+ this.waiter = undefined
657
+ }
658
+ return true
659
+ }
660
+
661
+ private settleRequestedTermination(): Effect.Effect<void> {
662
+ return Effect.suspend(() => {
663
+ if (this.runState !== "Draining") {
664
+ return this.finishRequestedTermination()
665
+ }
666
+ if (this.worker === undefined) {
667
+ this.interruptRequested = true
668
+ return this.awaitCompletion()
669
+ }
670
+ return this.interruptAndFinish(this.worker).pipe(
671
+ Effect.andThen(this.awaitCompletion())
672
+ )
673
+ })
674
+ }
675
+
676
+ private interruptAndFinish(worker: Fiber.Fiber<any, never>): Effect.Effect<void> {
677
+ return Fiber.interrupt(worker).pipe(
678
+ Effect.andThen(
679
+ Effect.suspend(() =>
680
+ this.lifecycle !== "Completed"
681
+ ? this.finishRequestedTermination()
682
+ : Effect.void
683
+ )
684
+ )
685
+ )
686
+ }
687
+
688
+ private awaitCompletion(): Effect.Effect<void> {
689
+ return this.lifecycle !== "Completed"
690
+ ? this.join.pipe(Effect.exit, Effect.asVoid)
691
+ : Effect.void
692
+ }
693
+
694
+ private resolveCompletion(completion: CompiledCompletion): Effect.Effect<unknown, unknown> {
695
+ if (completion !== CompiledStoppedCompletion) {
696
+ return completion
697
+ }
698
+ const stopped = Effect.fail(new StoppedError())
699
+ this.completion = stopped
700
+ return stopped
701
+ }
702
+
703
+ private drainRuntime(): Effect.Effect<void, never, any> {
704
+ const self = this
705
+ return Effect.uninterruptibleMask((restore) =>
706
+ Effect.gen(function*() {
707
+ let observedRevision = self.offerRevision
708
+ while (true) {
709
+ if (self.hasTerminationRequest()) {
710
+ return yield* self.finishRequestedTermination()
711
+ }
712
+
713
+ const exit = yield* restore(
714
+ Effect.suspend(() => {
715
+ const drain = self.execution.drain
716
+ return drain._tag === "Process"
717
+ ? drain.run(self.processContext!)
718
+ : drain.run(self.compiledContext!)
719
+ })
720
+ ).pipe(Effect.exit)
721
+ self.flushPendingChanges()
722
+ if (Exit.isFailure(exit)) {
723
+ if (self.lifecycle === "Active") {
724
+ yield* self.requestTermination({ _tag: "Failure", cause: exit.cause })
725
+ }
726
+ return yield* self.finishRequestedTermination()
727
+ }
728
+ if (Option.isSome(exit.value)) {
729
+ yield* self.requestTermination({ _tag: "Done", output: exit.value.value })
730
+ return yield* self.finishRequestedTermination()
731
+ }
732
+ if (self.hasTerminationRequest()) {
733
+ return yield* self.finishRequestedTermination()
734
+ }
735
+
736
+ if (self.offerRevision !== observedRevision) {
737
+ observedRevision = self.offerRevision
738
+ continue
739
+ }
740
+ self.runState = "Idle"
741
+ self.worker = undefined
742
+ return
743
+ }
744
+ })
745
+ )
746
+ }
747
+
748
+ private finishRequestedTermination(): Effect.Effect<void> {
749
+ return Effect.suspend(() => {
750
+ if (this.lifecycle !== "TerminationRequested") {
751
+ return Effect.void
752
+ }
753
+ const requested = this.termination
754
+ if (requested === undefined) {
755
+ return Effect.void
756
+ }
757
+ const snapshot = this.terminationSnapshot ?? this.reserveTermination(requested)
758
+ if (snapshot === undefined) {
759
+ return this.awaitCompletion()
760
+ }
761
+ const exit = requested._tag === "Stopped"
762
+ ? Exit.void
763
+ : requested._tag === "Done"
764
+ ? Exit.succeed(requested.output)
765
+ : Exit.failCause(requested.cause)
766
+ const completion: CompiledCompletion = requested._tag === "Stopped"
767
+ ? CompiledStoppedCompletion
768
+ : requested._tag === "Done"
769
+ ? Effect.succeed(requested.output)
770
+ : Effect.failCause(requested.cause)
771
+ const notifyOutcome = this.options.onOutcome === undefined ||
772
+ (requested._tag === "Stopped" && this.options.skipStoppedOutcome === true)
773
+ ? Effect.void
774
+ : Effect.suspend(() => this.options.onOutcome!(classifyOutcome(snapshot)!)).pipe(
775
+ Effect.exit,
776
+ Effect.asVoid
777
+ )
778
+ const inspector = this.inspector
779
+ const subject = this.inspectionSubject
780
+ const closeEmissionsAndInspect = inspector === undefined || subject === undefined
781
+ ? this.closeEmissions()
782
+ : this.closeEmissions().pipe(
783
+ Effect.andThen(Effect.sync(() =>
784
+ inspector.publishUnsafe(
785
+ this.activity === undefined
786
+ ? { _tag: "Terminated", subject, snapshot }
787
+ : {
788
+ _tag: "ActivityStopped",
789
+ subject: this.activity.owner,
790
+ activity: this.activity,
791
+ exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
792
+ }
793
+ )
794
+ ))
795
+ )
796
+ return Effect.uninterruptible(
797
+ Effect.sync(() => {
798
+ closeCompactMailbox(this.mailbox)
799
+ }).pipe(
800
+ Effect.andThen(this.childRuntime.close(exit)),
801
+ Effect.andThen(this.setAndPublishSnapshot(snapshot)),
802
+ Effect.andThen(closeEmissionsAndInspect),
803
+ Effect.andThen(Effect.sync(() => {
804
+ if (requested._tag === "Failure") {
805
+ failAcknowledgedMessage(this.inFlightMessage, requested.cause)
806
+ } else {
807
+ stopAcknowledgedMessage(this.inFlightMessage)
808
+ }
809
+ this.inFlightMessage = undefined
810
+ })),
811
+ Effect.andThen(notifyOutcome),
812
+ Effect.andThen(this.options.onStop ?? Effect.void),
813
+ Effect.andThen(
814
+ this.options.inspectionRoot === true && this.inspector !== undefined
815
+ ? this.inspector.close
816
+ : Effect.void
817
+ ),
818
+ Effect.andThen(Effect.sync(() => {
819
+ this.options.onStopSync?.()
820
+ this.runState = "Idle"
821
+ this.worker = undefined
822
+ this.interruptRequested = false
823
+ if (this.compiledContext !== undefined) {
824
+ this.compiledContext.executionState = undefined
825
+ }
826
+ this.completion = completion
827
+ this.lifecycle = "Completed"
828
+ if (this.waiter !== undefined) {
829
+ Deferred.doneUnsafe(this.waiter, this.resolveCompletion(completion))
830
+ this.waiter = undefined
831
+ }
832
+ }))
833
+ )
834
+ )
835
+ })
836
+ }
837
+
838
+ private publishSnapshot(
839
+ snapshot: VersionedSnapshot<unknown, unknown, unknown>
840
+ ): Effect.Effect<VersionedSnapshot<unknown, unknown, unknown>> {
841
+ const publish = snapshot.changes === undefined
842
+ ? Effect.succeed(snapshot)
843
+ : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot))
844
+ const current = snapshot.snapshot
845
+ return this.options.onSnapshot === undefined || current.status !== "active"
846
+ ? publish
847
+ : publish.pipe(Effect.tap(() => notifyActiveSnapshot(this.options.onSnapshot!, current)))
848
+ }
849
+
850
+ private completeChanges(snapshot: VersionedSnapshot<unknown, unknown, unknown>): Effect.Effect<void> {
851
+ return snapshot.changes === undefined
852
+ ? Effect.void
853
+ : PubSub.publish(snapshot.changes, Exit.succeed<void>(undefined)).pipe(Effect.asVoid)
854
+ }
855
+
856
+ private emitEvent(event: unknown): Effect.Effect<void> {
857
+ const publish = this.externalEmissions !== undefined ?
858
+ this.externalEmissions.emit(event) :
859
+ Effect.suspend(() =>
860
+ this.emissionsPubSub === undefined || this.emissionsPubSub === EmissionsClosed
861
+ ? Effect.void
862
+ : PubSub.publish(this.emissionsPubSub, event).pipe(Effect.asVoid)
863
+ )
864
+ const inspector = this.inspector
865
+ const subject = this.inspectionSubject
866
+ if (inspector === undefined || subject === undefined) return publish
867
+ return publish.pipe(Effect.tap(() =>
868
+ Effect.sync(() =>
869
+ inspector.publishUnsafe({
870
+ _tag: "Emitted",
871
+ subject,
872
+ emission: event,
873
+ causedBy: this.causation()
874
+ })
875
+ )
876
+ ))
877
+ }
878
+
879
+ shutdownEmissions(): Effect.Effect<void> {
880
+ return this.closeEmissions()
881
+ }
882
+
883
+ private closeEmissions(): Effect.Effect<void> {
884
+ if (this.externalEmissions !== undefined) return this.externalEmissions.close()
885
+ const observed = this.emissionsPubSub
886
+ this.emissionsPubSub = EmissionsClosed
887
+ return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed)
888
+ }
889
+
890
+ private getOrCreateEmissions(): Effect.Effect<PubSub.PubSub<unknown> | undefined> {
891
+ return Effect.suspend(() => {
892
+ const observed = this.emissionsPubSub
893
+ if (observed === EmissionsClosed) return Effect.succeed(undefined)
894
+ if (observed !== undefined) return Effect.succeed(observed)
895
+ return PubSub.unbounded<unknown>().pipe(
896
+ Effect.flatMap((candidate) =>
897
+ Effect.sync(() => {
898
+ const latest = this.emissionsPubSub
899
+ if (latest === EmissionsClosed) return [undefined, true] as const
900
+ if (latest !== undefined) return [latest, true] as const
901
+ this.emissionsPubSub = candidate
902
+ return [candidate, false] as const
903
+ }).pipe(
904
+ Effect.flatMap(([selected, discard]) =>
905
+ discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)
906
+ )
907
+ )
908
+ )
909
+ )
910
+ })
911
+ }
912
+
913
+ private emissionsStream(): Stream.Stream<unknown> {
914
+ return Stream.unwrap(
915
+ this.getOrCreateEmissions().pipe(
916
+ Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))
917
+ )
918
+ )
919
+ }
920
+
921
+ private setAndPublishSnapshot(snapshot: RuntimeSnapshot<unknown, unknown, unknown>): Effect.Effect<void> {
922
+ return Effect.suspend(() => {
923
+ this.flushPendingChanges()
924
+ const versioned = {
925
+ revision: this.current.revision + 1,
926
+ snapshot,
927
+ terminalizing: true,
928
+ changes: this.current.changes
929
+ }
930
+ this.current = versioned
931
+ return this.publishSnapshot(versioned).pipe(
932
+ Effect.flatMap((published) => this.completeChanges(published)),
933
+ Effect.asVoid
934
+ )
935
+ })
936
+ }
937
+
938
+ private setActiveState(state: unknown): Effect.Effect<void> {
939
+ return Effect.suspend(() => this.commitActiveState(state) ?? Effect.void)
940
+ }
941
+
942
+ pollCompiledMessage(): Option.Option<ProcessMessage<unknown>> {
943
+ const message = pollCompactMailbox(this.mailbox)
944
+ if (Option.isSome(message)) {
945
+ this.inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined
946
+ }
947
+ return message
948
+ }
949
+
950
+ completeCompiledMessage(delivery: AcknowledgedDelivery<unknown>): void {
951
+ succeedAcknowledgedMessage(this.inFlightMessage, delivery)
952
+ this.inFlightMessage = undefined
953
+ }
954
+
955
+ compiledState(): unknown {
956
+ return this.current.snapshot.state
957
+ }
958
+
959
+ commitCompiledState(state: unknown): Effect.Effect<void> | undefined {
960
+ return this.commitActiveState(state, true)
961
+ }
962
+
963
+ private commitActiveState(state: unknown, batchChanges = false): Effect.Effect<void> | undefined {
964
+ const latest = this.current
965
+ if (latest.terminalizing || latest.snapshot.status !== "active") {
966
+ return undefined
967
+ }
968
+ const pendingChanges = latest.pendingChanges
969
+ if (pendingChanges !== undefined) {
970
+ latest.pendingChanges = undefined
971
+ }
972
+ const activeSnapshot = { status: "active" as const, state }
973
+ const versioned = {
974
+ revision: latest.revision + 1,
975
+ snapshot: activeSnapshot,
976
+ terminalizing: false,
977
+ changes: latest.changes
978
+ } as VersionedSnapshot<unknown, unknown, unknown>
979
+ this.current = versioned
980
+ if (versioned.changes !== undefined) {
981
+ if (pendingChanges === undefined) {
982
+ if (batchChanges) {
983
+ versioned.pendingChanges = [versioned]
984
+ } else {
985
+ PubSub.publishUnsafe(versioned.changes, [versioned] as const)
986
+ }
987
+ } else {
988
+ pendingChanges.push(versioned)
989
+ if (batchChanges) {
990
+ versioned.pendingChanges = pendingChanges
991
+ } else {
992
+ PubSub.publishUnsafe(versioned.changes, pendingChanges)
993
+ }
994
+ }
995
+ }
996
+ return this.options.onSnapshot === undefined
997
+ ? undefined
998
+ : notifyActiveSnapshot(this.options.onSnapshot, activeSnapshot)
999
+ }
1000
+
1001
+ flushPendingChanges(): void {
1002
+ const current = this.current
1003
+ const pendingChanges = current?.pendingChanges
1004
+ if (pendingChanges === undefined || current.changes === undefined) {
1005
+ return
1006
+ }
1007
+ current.pendingChanges = undefined
1008
+ PubSub.publishUnsafe(current.changes, pendingChanges)
1009
+ }
1010
+
1011
+ private updateState<E, R>(
1012
+ f: (state: unknown) => Effect.Effect<unknown, E, R>
1013
+ ): Effect.Effect<void, E, R> {
1014
+ return Effect.suspend(() => {
1015
+ const observed = this.current
1016
+ if (observed.terminalizing || observed.snapshot.status !== "active") {
1017
+ return Effect.void
1018
+ }
1019
+ return f(observed.snapshot.state).pipe(
1020
+ Effect.flatMap((state) => {
1021
+ const latest = this.current
1022
+ return latest.terminalizing || latest.revision !== observed.revision
1023
+ ? Effect.void
1024
+ : this.setActiveState(state)
1025
+ })
1026
+ )
1027
+ })
1028
+ }
1029
+
1030
+ private getOrCreateChanges(): Effect.Effect<
1031
+ PubSub.PubSub<Take.Take<VersionedSnapshot<unknown, unknown, unknown>>> | undefined
1032
+ > {
1033
+ return Effect.suspend(() => {
1034
+ const observed = this.current
1035
+ if (observed.snapshot.status !== "active") {
1036
+ return Effect.succeed(undefined)
1037
+ }
1038
+ if (observed.changes !== undefined) {
1039
+ return Effect.succeed(observed.changes)
1040
+ }
1041
+ return PubSub.unbounded<Take.Take<VersionedSnapshot<unknown, unknown, unknown>>>({ replay: 1 }).pipe(
1042
+ Effect.flatMap((candidate) =>
1043
+ Effect.sync(() => {
1044
+ const latest = this.current
1045
+ if (latest.snapshot.status !== "active") {
1046
+ return [undefined, true] as const
1047
+ }
1048
+ if (latest.changes !== undefined) {
1049
+ return [latest.changes, true] as const
1050
+ }
1051
+ this.current = { ...latest, changes: candidate }
1052
+ return [candidate, false] as const
1053
+ }).pipe(
1054
+ Effect.flatMap(([changes, discard]) =>
1055
+ discard ? PubSub.shutdown(candidate).pipe(Effect.as(changes)) : Effect.succeed(changes)
1056
+ )
1057
+ )
1058
+ )
1059
+ )
1060
+ })
1061
+ }
1062
+
1063
+ private changesStream(): Stream.Stream<RuntimeSnapshot<unknown, unknown, unknown>> {
1064
+ const self = this
1065
+ return Stream.unwrap(
1066
+ Effect.gen(function*() {
1067
+ const changes = yield* self.getOrCreateChanges()
1068
+ if (changes === undefined) {
1069
+ return Stream.succeed(self.current.snapshot)
1070
+ }
1071
+ const subscription = yield* PubSub.subscribe(changes)
1072
+ const captured = self.current
1073
+ if (captured.snapshot.status !== "active") {
1074
+ return Stream.succeed(captured.snapshot)
1075
+ }
1076
+ return Stream.succeed(captured.snapshot).pipe(
1077
+ Stream.concat(
1078
+ Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(
1079
+ Stream.filter((next) => next.revision > captured.revision),
1080
+ Stream.map((next) => next.snapshot)
1081
+ )
1082
+ )
1083
+ )
1084
+ })
1085
+ )
1086
+ }
1087
+ }
1088
+
1089
+ class CompiledProcessContextImpl implements CompiledProcessContext<unknown, unknown> {
1090
+ executionState: unknown
1091
+
1092
+ constructor(
1093
+ readonly scope: ProcessScope<unknown>,
1094
+ readonly ownedChildren: OwnedChildRuntime,
1095
+ private readonly process: CompiledProcess
1096
+ ) {}
1097
+
1098
+ poll(): Option.Option<unknown> {
1099
+ return Option.map(this.process.pollCompiledMessage(), messageEvent)
1100
+ }
1101
+
1102
+ pollMessage(): Option.Option<ProcessMessage<unknown>> {
1103
+ return this.process.pollCompiledMessage()
1104
+ }
1105
+
1106
+ state(): unknown {
1107
+ return this.process.compiledState()
1108
+ }
1109
+
1110
+ completeMessage(delivery: AcknowledgedDelivery<unknown>): void {
1111
+ this.process.completeCompiledMessage(delivery)
1112
+ }
1113
+
1114
+ commit(state: unknown): Effect.Effect<void> | undefined {
1115
+ return this.process.commitCompiledState(state)
1116
+ }
1117
+
1118
+ runAfterChanges<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
1119
+ this.process.flushPendingChanges()
1120
+ return effect
1121
+ }
1122
+ }
1123
+
1124
+ export const startCompactCompiledInternal: StartProcess = Effect.fnUntraced(function*(
1125
+ logic: ProcessLogic<any, any, any, any, any, any>,
1126
+ options: StartInternalOptions
1127
+ ) {
1128
+ const sessionId = options.sessionId ?? (yield* options.runtime.nextSessionId)
1129
+ const services = yield* Effect.context<any>()
1130
+ const execution = logic.execution as CompiledProcessExecution<any, any, any, any, any, any>
1131
+ const process = new CompiledProcess(logic, options, services, sessionId)
1132
+ // A compiled initializer is synchronous by construction. Only startup
1133
+ // callbacks that themselves return Effects need the generic initialization
1134
+ // program; the compiled drain is still provided the complete service context.
1135
+ const initialize = execution.initialSync !== undefined &&
1136
+ options.onReady === undefined && options.onSnapshot === undefined
1137
+ ? process.initializeCompiledSync()
1138
+ : process.initialize()
1139
+ return yield* initialize.pipe(
1140
+ Effect.onExit((exit) =>
1141
+ Exit.isFailure(exit)
1142
+ ? process.shutdownEmissions().pipe(
1143
+ Effect.andThen(
1144
+ options.inspectionRoot === true && options.runtime.inspection !== undefined
1145
+ ? options.runtime.inspection.close
1146
+ : Effect.void
1147
+ )
1148
+ )
1149
+ : Effect.void
1150
+ )
1151
+ )
1152
+ }) as StartProcess
1153
+
1154
+ /** Preserves synchronous startup for owned compiled children. */
1155
+ export const startCompiledSync: ProcessRuntime["startCompiledSync"] = (logic, options, services, sessionId) =>
1156
+ new CompiledProcess(logic, options, services, sessionId).initializeCompiledSync()
1157
+
1158
+ type CompiledTermination =
1159
+ | { readonly _tag: "Stopped" }
1160
+ | { readonly _tag: "Done"; readonly output: unknown }
1161
+ | { readonly _tag: "Failure"; readonly cause: Cause.Cause<unknown> }
1162
+
1163
+ type CompiledInitialized = CompiledProcessInitial<unknown, unknown>
1164
+
1165
+ // Stopping is commonly used only for resource cleanup. Keep that path free of
1166
+ // Error stack capture and materialize the typed join failure only if observed.