@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
@@ -1,1866 +1,17 @@
1
- /**
2
- * Internal machine process runtime helpers.
3
- *
4
- * @since 0.4.0
5
- */
6
- import * as Cause from "effect/Cause";
7
- import * as Channel from "effect/Channel";
8
- import * as Context from "effect/Context";
1
+ /** Local process startup and execution strategy selection. */
9
2
  import * as Deferred from "effect/Deferred";
10
3
  import * as Effect from "effect/Effect";
11
- import * as Exit from "effect/Exit";
12
- import * as Fiber from "effect/Fiber";
13
- import * as Option from "effect/Option";
14
- import * as PubSub from "effect/PubSub";
15
- import * as Queue from "effect/Queue";
16
- import * as Scope from "effect/Scope";
17
4
  import * as Stream from "effect/Stream";
18
- import * as SynchronizedRef from "effect/SynchronizedRef";
19
- import { matchesChild, offerChildObservation, registerChild, selectRegistryChild, takeChildObservations, unregisterChild } from "./childRegistry.js";
20
- import { ChildAlreadyExistsError, StoppedError } from "./errors.js";
21
5
  import * as InspectionRuntime from "./inspectionRuntime.js";
22
- import { ChildMachineLogicTypeId } from "./symbols.js";
23
- /** @internal */
24
- export const activeSnapshotObserver = Symbol.for("effect/Machine/activeSnapshotObserver");
25
- /** @internal */
26
- export const sendParentOverride = Symbol.for("effect/Machine/sendParentOverride");
27
- /** @internal */
28
- export const acknowledgedSend = Symbol.for("effect/Machine/acknowledgedSend");
29
- const AcknowledgedMessageTypeId = Symbol("effect/Machine/AcknowledgedMessage");
30
- /** @internal */
31
- export const isAcknowledgedMessage = (message) => typeof message === "object" && message !== null && AcknowledgedMessageTypeId in message;
32
- /** @internal */
33
- export const messageEvent = (message) => isAcknowledgedMessage(message) ? message.event : message;
34
- const succeedAcknowledgedMessage = (message, delivery) => {
35
- if (message !== undefined && isAcknowledgedMessage(message)) {
36
- if (message.deferred !== undefined) {
37
- Deferred.doneUnsafe(message.deferred, Effect.succeed(delivery));
38
- }
39
- message.inspection?.complete(delivery);
40
- }
41
- };
42
- const failAcknowledgedMessage = (message, cause) => {
43
- if (message !== undefined && isAcknowledgedMessage(message)) {
44
- if (message.deferred !== undefined)
45
- Deferred.doneUnsafe(message.deferred, Effect.failCause(cause));
46
- }
47
- };
48
- const stopAcknowledgedMessage = (message) => {
49
- if (message !== undefined && isAcknowledgedMessage(message)) {
50
- if (message.deferred !== undefined)
51
- Deferred.doneUnsafe(message.deferred, Effect.fail(new StoppedError()));
52
- }
53
- };
54
- const isMachineTarget = (value) => typeof value === "object" && value !== null && "send" in value && typeof value.send === "function";
55
- const sendMachineTarget = (target, event, source, causedBy) => "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function"
56
- ? target.sendInspected(event, source, causedBy)
57
- : target.send(event);
58
- const executionIsChildless = (execution) => execution?._tag === "Childless" || execution?.childless === true;
59
- const offerCompactMailbox = (mailbox, event) => {
60
- const items = mailbox.items ?? [];
61
- mailbox.items = items;
62
- items.push(event);
63
- };
64
- const pollCompactMailbox = (mailbox) => {
65
- if (mailbox.items === undefined) {
66
- return Option.none();
67
- }
68
- const event = mailbox.items[mailbox.index];
69
- mailbox.index += 1;
70
- if (mailbox.index === mailbox.items.length) {
71
- mailbox.items = undefined;
72
- mailbox.index = 0;
73
- }
74
- return Option.some(event);
75
- };
76
- const closeCompactMailbox = (mailbox) => {
77
- if (mailbox.items !== undefined) {
78
- for (let index = mailbox.index; index < mailbox.items.length; index += 1) {
79
- stopAcknowledgedMessage(mailbox.items[index]);
80
- }
81
- }
82
- mailbox.closed = true;
83
- mailbox.items = undefined;
84
- mailbox.index = 0;
85
- };
86
- export class MachineRuntime extends Context.Service()("effect/Machine/MachineRuntime") {
87
- }
88
- export const provideMachineRuntime = (effect, scope) => Effect.provideService(effect, MachineRuntime, scope);
89
- const classifyOutcome = (snapshot) => {
90
- switch (snapshot.status) {
91
- case "active": {
92
- return undefined;
93
- }
94
- case "done": {
95
- return {
96
- _tag: "Done",
97
- output: snapshot.output,
98
- snapshot
99
- };
100
- }
101
- case "error": {
102
- const failure = snapshot.cause.reasons.find(Cause.isFailReason);
103
- if (failure !== undefined) {
104
- return {
105
- _tag: "Failure",
106
- error: failure.error,
107
- cause: snapshot.cause,
108
- snapshot
109
- };
110
- }
111
- const defect = snapshot.cause.reasons.find(Cause.isDieReason);
112
- if (defect !== undefined) {
113
- return {
114
- _tag: "Defect",
115
- defect: defect.defect,
116
- cause: snapshot.cause,
117
- snapshot
118
- };
119
- }
120
- const interrupted = snapshot.cause.reasons.find(Cause.isInterruptReason);
121
- if (interrupted !== undefined) {
122
- return {
123
- _tag: "Interrupted",
124
- cause: snapshot.cause,
125
- snapshot
126
- };
127
- }
128
- return {
129
- _tag: "Cause",
130
- cause: snapshot.cause,
131
- snapshot
132
- };
133
- }
134
- case "stopped": {
135
- return {
136
- _tag: "Stopped",
137
- snapshot
138
- };
139
- }
140
- }
141
- };
142
- const notifyActiveSnapshot = (onSnapshot, snapshot) => Effect.suspend(() => onSnapshot(snapshot)).pipe(Effect.exit, Effect.asVoid);
143
- export const watch = (ref) => ref.changes.pipe(Stream.filter((snapshot) => snapshot.status !== "active"), Stream.map((snapshot) => classifyOutcome(snapshot)), Stream.take(1));
144
- const makeProcessRuntime = Effect.sync(() => {
145
- let sessionIdCounter = 0;
146
- return {
147
- nextSessionId: Effect.sync(() => `machine:${sessionIdCounter++}`)
148
- };
149
- });
150
- const inspectionSubject = (logic, id, sessionId) => ({
151
- id,
152
- sessionId,
153
- kind: logic.inspection?.kind ?? "Logic"
154
- });
155
- const messageCausation = (message, initializing) => initializing
156
- ? { _tag: "Initialization" }
157
- : message !== undefined && isAcknowledgedMessage(message) && message.inspection !== undefined
158
- ? { _tag: "Macrostep", macrostepId: message.inspection.macrostepId }
159
- : undefined;
160
- const makeInspectedMessage = (inspection, subject, event, source, causedBy, deferred) => {
161
- const deliveryId = inspection.nextDeliveryId();
162
- const macrostepId = inspection.nextMacrostepId();
163
- const inspected = {
164
- deliveryId,
165
- macrostepId,
166
- source,
167
- event,
168
- causedBy,
169
- complete: (delivery) => {
170
- const microsteps = InspectionRuntime.microsteps(delivery.plan);
171
- inspection.publishUnsafe({
172
- _tag: "EventProcessed",
173
- subject,
174
- macrostepId,
175
- deliveryId,
176
- source,
177
- event,
178
- before: { status: "active", state: delivery.before },
179
- after: { status: "active", state: delivery.after },
180
- handled: microsteps.some((microstep) => microstep.transitions.length > 0),
181
- configurationChanged: microsteps.some((microstep) => microstep.changed),
182
- microsteps
183
- });
184
- }
185
- };
186
- return {
187
- [AcknowledgedMessageTypeId]: true,
188
- event,
189
- ...(deferred === undefined ? undefined : { deferred }),
190
- inspection: inspected
191
- };
192
- };
193
- const publishInspectedSent = (inspection, subject, message) => {
194
- if (!isAcknowledgedMessage(message) || message.inspection === undefined)
195
- return;
196
- const delivery = message.inspection;
197
- inspection.publishUnsafe({
198
- _tag: "EventSent",
199
- subject,
200
- deliveryId: delivery.deliveryId,
201
- source: delivery.source,
202
- target: InspectionRuntime.endpoint(subject),
203
- event: delivery.event,
204
- causedBy: delivery.causedBy
205
- });
206
- };
207
- class OwnedChildRuntimeImpl {
208
- registry;
209
- self;
210
- runtime;
211
- services;
212
- sendAcknowledged;
213
- scopedServices;
214
- constructor(registry, self, runtime, services, sendAcknowledged) {
215
- this.registry = registry;
216
- this.self = self;
217
- this.runtime = runtime;
218
- this.services = services;
219
- this.sendAcknowledged = sendAcknowledged;
220
- }
221
- has(key) {
222
- for (const entry of this.registry.children.values()) {
223
- if (entry.ownerActive && entry.ownerKey === key)
224
- return true;
225
- }
226
- return false;
227
- }
228
- stopEntry(entry) {
229
- entry.ownerActive = false;
230
- return entry._tag === "Started" ? entry.ref.stop : Effect.void;
231
- }
232
- spawn(makeLogic, options) {
233
- const token = Symbol();
234
- let startedChild;
235
- const isCurrent = () => {
236
- const entry = this.registry.children.get(options.id);
237
- return entry?.token === token && entry.ownerKey === options.key && entry.ownerActive === true;
238
- };
239
- return Effect.suspend(() => {
240
- if (this.registry.closed)
241
- return Effect.interrupt;
242
- if (this.has(options.key) || this.registry.children.has(options.id)) {
243
- return Effect.fail(new ChildAlreadyExistsError({ id: options.duplicateId }));
244
- }
245
- const logic = makeLogic();
246
- const scope = this.registry.scope ??= Scope.makeUnsafe("parallel");
247
- this.registry.children.set(options.id, {
248
- _tag: "Starting",
249
- token,
250
- ownerKey: options.key,
251
- ownerPath: options.path,
252
- ownerActive: true
253
- });
254
- const parent = {
255
- ...this.self,
256
- send: (event) => options.sendParent(isCurrent, event),
257
- sendInspected: (event, source, causedBy) => isCurrent() ? sendMachineTarget(this.self, event, source, causedBy) : Effect.void,
258
- ...(this.sendAcknowledged === undefined
259
- ? undefined
260
- : {
261
- [acknowledgedSend]: (event) => isCurrent()
262
- ? this.sendAcknowledged(event)
263
- : Effect.interrupt
264
- })
265
- };
266
- const startOptions = {
267
- detached: true,
268
- id: options.id,
269
- sendParent: (event) => options.sendParent(isCurrent, event),
270
- onOutcome: (outcome) => options.onOutcome(isCurrent, outcome, startedChild?.sessionId),
271
- ...(options.onSnapshot === undefined
272
- ? undefined
273
- : { onSnapshot: (snapshot) => options.onSnapshot(isCurrent, snapshot) }),
274
- onReadySync: (child) => {
275
- startedChild = child;
276
- return registerChild(this.registry, options.id, token, child, options.descriptor);
277
- },
278
- onStopSync: () => unregisterChild(this.registry, options.id, token),
279
- skipStoppedOutcome: true,
280
- parent,
281
- runtime: this.runtime,
282
- origin: { _tag: "Invoke", ownerPath: options.path, invokeId: options.duplicateId },
283
- ...(options.activityKind === undefined || this.runtime.inspection === undefined ||
284
- this.self.inspectionSubject === undefined
285
- ? undefined
286
- : {
287
- activity: {
288
- id: options.duplicateId,
289
- owner: this.self.inspectionSubject,
290
- ownerPath: options.path,
291
- kind: options.activityKind
292
- }
293
- })
294
- };
295
- const execution = logic.execution;
296
- const synchronous = this.services !== undefined && options.onSnapshot === undefined &&
297
- execution?._tag === "Compiled" && execution.childless && execution.drain._tag === "Owned" &&
298
- execution.initialSync !== undefined;
299
- const start = synchronous
300
- ? Effect.flatMap(this.runtime.nextSessionId, (sessionId) => new CompiledProcess(logic, startOptions, this.scopedServices ??= Context.add(this.services, Scope.Scope, scope), sessionId).initializeCompiledSync())
301
- : startLogicInternal(logic, startOptions);
302
- const guarded = start.pipe(Effect.onExit((exit) => {
303
- if (Exit.isSuccess(exit))
304
- return Effect.void;
305
- unregisterChild(this.registry, options.id, token);
306
- return startedChild === undefined ? Effect.void : startedChild.stop;
307
- }));
308
- return (synchronous ? guarded : Scope.provide(guarded, scope)).pipe(Effect.asVoid);
309
- });
310
- }
311
- stopAll() {
312
- return Effect.suspend(() => {
313
- const effects = [];
314
- for (const entry of this.registry.children.values()) {
315
- if (entry.ownerActive)
316
- effects.push(this.stopEntry(entry));
317
- }
318
- return effects.length === 0
319
- ? Effect.void
320
- : effects.length === 1
321
- ? effects[0]
322
- : Effect.all(effects, { concurrency: "unbounded", discard: true });
323
- });
324
- }
325
- stopPaths(paths) {
326
- if (paths.length === 0)
327
- return undefined;
328
- const pathSet = new Set(paths);
329
- const effects = [];
330
- for (const entry of this.registry.children.values()) {
331
- if (entry.ownerActive && entry.ownerPath !== undefined && pathSet.has(entry.ownerPath)) {
332
- effects.push(this.stopEntry(entry));
333
- }
334
- }
335
- return effects.length === 0
336
- ? undefined
337
- : effects.length === 1
338
- ? effects[0]
339
- : Effect.all(effects, { concurrency: "unbounded", discard: true });
340
- }
341
- }
342
- const noChildChanges = Stream.succeed(Option.none()).pipe(Stream.concat(Stream.never));
343
- const noParentSend = (_event) => Effect.void;
344
- const noInspectInitial = (_paths, _microsteps) => { };
345
- const noCausation = () => undefined;
346
- const EmissionsClosed = Symbol("effect/Machine/EmissionsClosed");
347
- const makeEmissionRuntime = () => {
348
- let emissions;
349
- const getOrCreate = Effect.suspend(() => {
350
- const observed = emissions;
351
- if (observed === EmissionsClosed)
352
- return Effect.succeed(undefined);
353
- if (observed !== undefined)
354
- return Effect.succeed(observed);
355
- return PubSub.unbounded().pipe(Effect.flatMap((candidate) => Effect.sync(() => {
356
- const latest = emissions;
357
- if (latest === EmissionsClosed)
358
- return [undefined, true];
359
- if (latest !== undefined)
360
- return [latest, true];
361
- emissions = candidate;
362
- return [candidate, false];
363
- }).pipe(Effect.flatMap(([selected, discard]) => discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)))));
364
- });
365
- return {
366
- emit: (event) => Effect.suspend(() => emissions === undefined || emissions === EmissionsClosed
367
- ? Effect.void
368
- : PubSub.publish(emissions, event).pipe(Effect.asVoid)),
369
- close: () => {
370
- const observed = emissions;
371
- emissions = EmissionsClosed;
372
- return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed);
373
- },
374
- stream: Stream.unwrap(getOrCreate.pipe(Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))))
375
- };
376
- };
377
- const childlessRuntime = {
378
- close: () => Effect.void,
379
- spawn: (() => Effect.die(new Error("Childless machine logic cannot spawn a process"))),
380
- get: () => Effect.succeed(Option.none()),
381
- changes: () => noChildChanges,
382
- sendTo: () => Effect.void,
383
- stop: () => Effect.void,
384
- owned: {
385
- spawn: () => Effect.die(new Error("Childless machine logic cannot spawn an owned process")),
386
- stopAll: () => Effect.void,
387
- stopPaths: () => undefined
388
- }
389
- };
390
- const makeChildRuntimeSync = (self, runtime, services, sendAcknowledged) => {
391
- // Child-registry decisions are synchronous and every access below runs in
392
- // one Effect.sync / Effect.suspend step. Keep the unobserved representation
393
- // compact; selector-specific handoffs are installed only while
394
- // childChanges streams are running.
395
- const registry = {
396
- closed: false,
397
- children: new Map(),
398
- observers: undefined,
399
- scope: undefined
400
- };
401
- const close = (exit) => Effect.suspend(() => {
402
- if (registry.closed) {
403
- return Effect.void;
404
- }
405
- registry.closed = true;
406
- if (registry.scope === undefined) {
407
- return Effect.void;
408
- }
409
- const finalizers = Scope.closeUnsafe(registry.scope, exit);
410
- let first;
411
- let rest;
412
- for (const entry of registry.children.values()) {
413
- if (entry._tag !== "Started") {
414
- continue;
415
- }
416
- if (first === undefined) {
417
- first = entry.ref.stop;
418
- }
419
- else {
420
- rest ??= [first];
421
- rest.push(entry.ref.stop);
422
- }
423
- }
424
- if (finalizers !== undefined) {
425
- if (first === undefined) {
426
- first = finalizers;
427
- }
428
- else {
429
- rest ??= [first];
430
- rest.push(finalizers);
431
- }
432
- }
433
- const cleanup = rest ?? first;
434
- return cleanup === undefined
435
- ? Effect.void
436
- : Array.isArray(cleanup)
437
- ? Effect.all(cleanup, { concurrency: "unbounded", discard: true })
438
- : cleanup;
439
- });
440
- const unregister = (key, token) => Effect.sync(() => unregisterChild(registry, key, token));
441
- const register = (key, token, ref, descriptor) => Effect.sync(() => registerChild(registry, key, token, ref, descriptor));
442
- const get = (child) => {
443
- const id = typeof child === "string" ? child : child.id;
444
- return Effect.sync(() => {
445
- if (registry.closed) {
446
- return Option.none();
447
- }
448
- const entry = registry.children.get(id);
449
- return entry !== undefined && matchesChild(entry, child)
450
- ? Option.some(entry.ref)
451
- : Option.none();
452
- });
453
- };
454
- const changes = (child) => {
455
- const id = typeof child === "string" ? child : child.id;
456
- return Stream.fromChannel(Channel.fromTransform((_, streamScope) => Effect.sync(() => ({ child, id, values: undefined, waiter: undefined })).pipe(Effect.flatMap((observer) => {
457
- const removeObserver = Effect.sync(() => {
458
- if (registry.observers !== undefined) {
459
- registry.observers.delete(observer);
460
- if (registry.observers.size === 0) {
461
- registry.observers = undefined;
462
- }
463
- }
464
- observer.values = undefined;
465
- observer.waiter = undefined;
466
- });
467
- return Scope.addFinalizer(streamScope, removeObserver).pipe(Effect.andThen(Effect.sync(() => {
468
- if (!registry.closed && streamScope.state._tag !== "Closed") {
469
- registry.observers ??= new Set();
470
- registry.observers.add(observer);
471
- }
472
- offerChildObservation(observer, selectRegistryChild(registry, id, child));
473
- })), Effect.as(takeChildObservations(observer)));
474
- }))));
475
- };
476
- const sendTo = (child, event, source, causedBy) => {
477
- const id = typeof child === "string" ? child : child.id;
478
- return Effect.suspend(() => {
479
- if (registry.closed) {
480
- return Effect.void;
481
- }
482
- const entry = registry.children.get(id);
483
- return entry !== undefined && matchesChild(entry, child)
484
- ? sendMachineTarget(entry.ref, event, source, causedBy)
485
- : Effect.void;
486
- });
487
- };
488
- const stop = (child) => {
489
- const id = typeof child === "string" ? child : child.id;
490
- return Effect.suspend(() => {
491
- if (registry.closed) {
492
- return Effect.void;
493
- }
494
- const entry = registry.children.get(id);
495
- return entry !== undefined && matchesChild(entry, child)
496
- ? entry.ref.stop
497
- : Effect.void;
498
- });
499
- };
500
- function spawn(logicOrChild, options) {
501
- const descriptor = typeof logicOrChild === "object" && logicOrChild !== null &&
502
- ChildMachineLogicTypeId in logicOrChild
503
- ? logicOrChild
504
- : undefined;
505
- const logic = descriptor === undefined
506
- ? logicOrChild
507
- : descriptor[ChildMachineLogicTypeId](options?.input);
508
- const spawnOptions = descriptor === undefined
509
- ? options
510
- : { id: descriptor.id, descriptor };
511
- const token = Symbol();
512
- const key = spawnOptions?.id ?? token;
513
- let startedChild;
514
- return Effect.suspend(() => {
515
- if (registry.closed) {
516
- return Effect.interrupt;
517
- }
518
- if (typeof key === "string" && registry.children.has(key)) {
519
- return Effect.fail(new ChildAlreadyExistsError({ id: key }));
520
- }
521
- registry.scope ??= Scope.makeUnsafe("parallel");
522
- registry.children.set(key, { _tag: "Starting", token });
523
- return startLogicInternal(logic, {
524
- detached: true,
525
- ...(spawnOptions?.id === undefined ? undefined : { id: spawnOptions.id }),
526
- ...(spawnOptions?.onOutcome === undefined ? undefined : { onOutcome: spawnOptions.onOutcome }),
527
- ...(spawnOptions?.[activeSnapshotObserver] === undefined
528
- ? undefined
529
- : { onSnapshot: spawnOptions[activeSnapshotObserver] }),
530
- ...(spawnOptions?.[sendParentOverride] === undefined
531
- ? undefined
532
- : { sendParent: spawnOptions[sendParentOverride] }),
533
- onReady: (child, requestChildStop) => Effect.sync(() => {
534
- startedChild = child;
535
- }).pipe(Effect.andThen(register(key, token, child, spawnOptions?.descriptor)), Effect.flatMap((registered) => registered ? Effect.void : requestChildStop)),
536
- onStop: unregister(key, token),
537
- parent: self,
538
- runtime,
539
- origin: { _tag: "Spawn", address: spawnOptions?.id }
540
- }).pipe(Effect.onExit((exit) => Exit.isFailure(exit)
541
- ? unregister(key, token).pipe(Effect.andThen(startedChild === undefined ? Effect.void : startedChild.stop))
542
- : Effect.void), Scope.provide(registry.scope));
543
- });
544
- }
545
- return {
546
- close,
547
- spawn,
548
- get,
549
- changes,
550
- sendTo,
551
- stop,
552
- owned: new OwnedChildRuntimeImpl(registry, self, runtime, services, sendAcknowledged)
553
- };
554
- };
555
- const makeChildRuntime = (self, runtime, services, sendAcknowledged) => Effect.sync(() => makeChildRuntimeSync(self, runtime, services, sendAcknowledged));
556
- // `Machine.logic` permits an arbitrary Effect program, including programs that
557
- // suspend or supervise their own fibers. Keep its two-fiber worker/supervisor
558
- // protocol as the general contract rather than weakening it for statecharts.
559
- const startGenericInternal = Effect.fnUntraced(function* (logic, options) {
560
- const { detached, id: requestedId, onOutcome, onReady, onReadySync, onSnapshot, onStop, onStopSync, parent, runtime, sendParent: overrideSendParent } = options;
561
- const sessionId = options.sessionId ?? (yield* runtime.nextSessionId);
562
- const id = requestedId ?? sessionId;
563
- const inspector = runtime.inspection;
564
- const subject = inspector === undefined ? undefined : inspectionSubject(logic, id, sessionId);
565
- const activity = inspector === undefined || options.activity === undefined
566
- ? undefined
567
- : { ...options.activity, sessionId };
568
- let initialEntryPaths;
569
- let initialMicrosteps;
570
- const queue = yield* Queue.unbounded();
571
- const emissions = options.emissions ?? makeEmissionRuntime();
572
- const termination = yield* Deferred.make();
573
- const done = yield* Deferred.make();
574
- const awaitCompletion = Deferred.await(done).pipe(Effect.exit, Effect.asVoid);
575
- let initializing = true;
576
- let inFlightMessage;
577
- const requestStop = Deferred.succeed(termination, { _tag: "Stopped" }).pipe(Effect.asVoid);
578
- const offerDirect = (message) => Queue.offer(queue, message).pipe(Effect.flatMap((accepted) => accepted ? Effect.void : Effect.fail(new StoppedError())));
579
- const offerInspected = inspector === undefined ? undefined : (event, source, causedBy, deferred) => Effect.suspend(() => {
580
- const message = inspector.isActive()
581
- ? makeInspectedMessage(inspector, subject, event, source, causedBy, deferred)
582
- : deferred === undefined
583
- ? event
584
- : { [AcknowledgedMessageTypeId]: true, event, deferred };
585
- return offerDirect(message).pipe(Effect.tap(() => Effect.sync(() => publishInspectedSent(inspector, subject, message))));
586
- });
587
- const sendAcknowledged = logic.execution?._tag !== "Compiled"
588
- ? undefined
589
- : (event) => Effect.uninterruptibleMask((restore) => Deferred.make().pipe(Effect.flatMap((deferred) => {
590
- const offered = inspector === undefined
591
- ? offerDirect({ [AcknowledgedMessageTypeId]: true, event, deferred })
592
- : offerInspected(event, undefined, undefined, deferred);
593
- return offered.pipe(Effect.andThen(restore(Deferred.await(deferred))));
594
- }), Effect.map((delivery) => delivery)));
595
- const self = {
596
- id,
597
- sessionId,
598
- // Initialization must finish constructing a state before a stopped
599
- // snapshot can be published. A stop requested there is therefore recorded
600
- // and returns so initialization can finish. Once running, the requesting
601
- // process waits forever and is interrupted by the supervisor after the
602
- // stop request wins, so execution never continues after `self.stop`.
603
- stop: Effect.suspend(() => initializing
604
- ? requestStop
605
- : requestStop.pipe(Effect.andThen(Effect.never))),
606
- send: inspector === undefined
607
- ? (event) => offerDirect(event)
608
- : (event) => offerInspected(event, undefined, undefined),
609
- ...(inspector === undefined
610
- ? undefined
611
- : { inspectionSubject: subject, sendInspected: offerInspected })
612
- };
613
- let { changes: childChanges, close: closeChildren, get: getChild, owned: ownedChildren, sendTo, spawn, stop: stopChild } = childlessRuntime;
614
- if (!executionIsChildless(logic.execution)) {
615
- ;
616
- ({
617
- changes: childChanges,
618
- close: closeChildren,
619
- get: getChild,
620
- owned: ownedChildren,
621
- sendTo,
622
- spawn,
623
- stop: stopChild
624
- } = yield* makeChildRuntime(self, runtime, undefined, sendAcknowledged === undefined ? undefined : (event) => sendAcknowledged(event)));
625
- }
626
- const cleanupStartupFailure = (exit) => {
627
- if (Exit.isSuccess(exit))
628
- return Effect.void;
629
- if (inspector !== undefined) {
630
- inspector.publishUnsafe(activity === undefined
631
- ? { _tag: "StartFailed", subject: subject, cause: exit.cause }
632
- : { _tag: "ActivityStopped", subject: activity.owner, activity, exit });
633
- }
634
- return closeChildren(exit).pipe(Effect.andThen(emissions.close()), Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void));
635
- };
636
- const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(onStopSync);
637
- const currentCausation = inspector === undefined
638
- ? noCausation
639
- : () => messageCausation(inFlightMessage, initializing);
640
- const sendParent = overrideSendParent ?? (parent === undefined
641
- ? noParentSend
642
- : inspector === undefined
643
- ? parent.send
644
- : (event) => sendMachineTarget(parent, event, subject, currentCausation()));
645
- const emit = inspector === undefined
646
- ? emissions.emit
647
- : (event) => emissions.emit(event).pipe(Effect.tap(() => Effect.sync(() => inspector.publishUnsafe({
648
- _tag: "Emitted",
649
- subject: subject,
650
- emission: event,
651
- causedBy: currentCausation()
652
- }))));
653
- const sendToTarget = inspector === undefined
654
- ? ((target, event) => isMachineTarget(target) ? target.send(event) : sendTo(target, event))
655
- : ((target, event) => isMachineTarget(target)
656
- ? sendMachineTarget(target, event, subject, currentCausation())
657
- : sendTo(target, event, subject, currentCausation()));
658
- const scope = {
659
- self,
660
- parent,
661
- spawn,
662
- sendParent,
663
- emit,
664
- sendTo: sendToTarget,
665
- stopChild,
666
- failCause: (cause) => Deferred.succeed(termination, {
667
- _tag: "Failure",
668
- cause: cause
669
- }).pipe(Effect.asVoid),
670
- inspectInitial: inspector === undefined
671
- ? noInspectInitial
672
- : (paths, microsteps = []) => {
673
- initialEntryPaths = paths;
674
- initialMicrosteps = microsteps;
675
- }
676
- };
677
- if (inspector !== undefined) {
678
- inspector.publishUnsafe(activity === undefined
679
- ? {
680
- _tag: "Created",
681
- subject: subject,
682
- parent: parent?.inspectionSubject,
683
- origin: options.origin ?? { _tag: "Root" },
684
- definition: logic.inspection?.definition
685
- }
686
- : { _tag: "ActivityStarted", subject: activity.owner, activity });
687
- }
688
- const initial = yield* logic.initial(scope).pipe(Effect.onExit(cleanupStartupFailure), Effect.ensuring(Effect.sync(() => {
689
- initializing = false;
690
- })));
691
- const current = yield* SynchronizedRef.make({
692
- revision: 0,
693
- terminalizing: false,
694
- changes: undefined,
695
- snapshot: {
696
- status: "active",
697
- state: initial
698
- }
699
- });
700
- if (activity === undefined) {
701
- inspector?.publishUnsafe({
702
- _tag: "Initialized",
703
- subject: subject,
704
- snapshot: { status: "active", state: initial },
705
- initialEntryPaths: initialEntryPaths ?? [],
706
- microsteps: InspectionRuntime.microsteps({ microsteps: initialMicrosteps ?? [] })
707
- });
708
- }
709
- const publishSnapshot = onSnapshot === undefined
710
- ? (snapshot) => snapshot.changes === undefined
711
- ? Effect.succeed(snapshot)
712
- : PubSub.publish(snapshot.changes, [snapshot]).pipe(Effect.as(snapshot))
713
- : (snapshot) => {
714
- const publish = snapshot.changes === undefined
715
- ? Effect.succeed(snapshot)
716
- : PubSub.publish(snapshot.changes, [snapshot]).pipe(Effect.as(snapshot));
717
- const runtimeSnapshot = snapshot.snapshot;
718
- return runtimeSnapshot.status !== "active"
719
- ? publish
720
- : publish.pipe(Effect.tap(() => notifyActiveSnapshot(onSnapshot, runtimeSnapshot)));
721
- };
722
- const completeChanges = (snapshot) => snapshot.changes === undefined
723
- ? Effect.void
724
- : PubSub.publish(snapshot.changes, Exit.succeed(undefined)).pipe(Effect.asVoid);
725
- const completeIfTerminal = (snapshot) => {
726
- if (snapshot.snapshot.status === "active") {
727
- return Effect.succeed(snapshot);
728
- }
729
- return completeChanges(snapshot).pipe(Effect.as(snapshot));
730
- };
731
- const publishIfCurrent = (snapshot) => SynchronizedRef.get(current).pipe(Effect.flatMap((currentSnapshot) => currentSnapshot.revision === snapshot.revision
732
- ? publishSnapshot(snapshot).pipe(Effect.flatMap(completeIfTerminal))
733
- : Effect.succeed(undefined)));
734
- const updateSnapshot = (f) => SynchronizedRef.modifyEffect(current, (current) => current.terminalizing
735
- ? Effect.succeed([undefined, current])
736
- : Effect.map(f(current.snapshot), (next) => {
737
- if (next === undefined) {
738
- return [undefined, current];
739
- }
740
- const versioned = {
741
- revision: current.revision + 1,
742
- snapshot: next,
743
- terminalizing: false,
744
- changes: current.changes
745
- };
746
- return [versioned, versioned];
747
- })).pipe(Effect.flatMap((versioned) => versioned === undefined ? Effect.succeed(undefined) : publishIfCurrent(versioned)), Effect.map((published) => published?.snapshot));
748
- const reserveTerminalSnapshot = (f) => SynchronizedRef.modify(current, (current) => {
749
- if (current.terminalizing || current.snapshot.status !== "active") {
750
- return [undefined, current];
751
- }
752
- return [
753
- {
754
- revision: current.revision + 1,
755
- snapshot: f(current.snapshot),
756
- terminalizing: true,
757
- changes: current.changes
758
- },
759
- { ...current, terminalizing: true }
760
- ];
761
- }).pipe(Effect.map((versioned) => versioned?.snapshot));
762
- const setAndPublishSnapshot = (snapshot) => SynchronizedRef.updateAndGet(current, (current) => ({
763
- revision: current.revision + 1,
764
- snapshot,
765
- terminalizing: true,
766
- changes: current.changes
767
- })).pipe(Effect.flatMap(publishSnapshot), Effect.flatMap(completeIfTerminal), Effect.asVoid);
768
- const setActiveStateDirect = (state) => updateSnapshot((snapshot) => Effect.succeed(snapshot.status === "active"
769
- ? {
770
- status: "active",
771
- state
772
- }
773
- : undefined)).pipe(Effect.asVoid);
774
- const setActiveState = inspector === undefined ?
775
- setActiveStateDirect :
776
- (state) => SynchronizedRef.get(current).pipe(Effect.flatMap((before) => updateSnapshot((snapshot) => Effect.succeed(snapshot.status === "active"
777
- ? {
778
- status: "active",
779
- state
780
- }
781
- : undefined)).pipe(Effect.tap((after) => Effect.sync(() => {
782
- if (logic.inspection?.kind === "Machine" || after === undefined)
783
- return;
784
- inspector.publishUnsafe({
785
- _tag: "StateChanged",
786
- subject: subject,
787
- before: before.snapshot.state,
788
- after: state,
789
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
790
- ? inFlightMessage.inspection?.deliveryId
791
- : undefined
792
- });
793
- })))), Effect.asVoid);
794
- const terminalizeWith = (snapshot, exit, completeDone) => {
795
- const notifyOutcome = onOutcome === undefined || (snapshot.status === "stopped" && options.skipStoppedOutcome === true)
796
- ? Effect.void
797
- : Effect.suspend(() => onOutcome(classifyOutcome(snapshot))).pipe(Effect.exit, Effect.asVoid);
798
- const closeEmissionsAndInspect = inspector === undefined
799
- ? emissions.close()
800
- : emissions.close().pipe(Effect.andThen(Effect.sync(() => inspector.publishUnsafe(activity === undefined
801
- ? { _tag: "Terminated", subject: subject, snapshot }
802
- : {
803
- _tag: "ActivityStopped",
804
- subject: activity.owner,
805
- activity,
806
- exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
807
- }))));
808
- return Effect.uninterruptible(Effect.sync(() => {
809
- while (true) {
810
- const pending = Queue.takeUnsafe(queue);
811
- if (pending === undefined || Exit.isFailure(pending))
812
- break;
813
- stopAcknowledgedMessage(pending.value);
814
- }
815
- }).pipe(Effect.andThen(Queue.shutdown(queue)), Effect.andThen(closeChildren(exit)), Effect.andThen(setAndPublishSnapshot(snapshot)), Effect.andThen(closeEmissionsAndInspect), Effect.andThen(Effect.sync(() => {
816
- if (Exit.isFailure(exit)) {
817
- failAcknowledgedMessage(inFlightMessage, exit.cause);
818
- }
819
- else {
820
- stopAcknowledgedMessage(inFlightMessage);
821
- }
822
- inFlightMessage = undefined;
823
- })), Effect.andThen(notifyOutcome), Effect.andThen(cleanup), Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void), Effect.andThen(completeDone)));
824
- };
825
- const reserveStoppedSnapshot = reserveTerminalSnapshot((snapshot) => ({
826
- status: "stopped",
827
- state: snapshot.state
828
- }));
829
- const reserveFailureSnapshot = (cause) => reserveTerminalSnapshot((snapshot) => ({
830
- status: "error",
831
- state: snapshot.state,
832
- cause
833
- }));
834
- const reserveSuccessSnapshot = (output) => reserveTerminalSnapshot((snapshot) => ({
835
- status: "done",
836
- state: snapshot.state,
837
- output
838
- }));
839
- const terminalizeReservedStop = (snapshot) => {
840
- const exit = Exit.void;
841
- return terminalizeWith(snapshot, exit, Deferred.fail(done, new StoppedError()));
842
- };
843
- const terminalizeReservedFailure = (snapshot, cause) => {
844
- const exit = Exit.failCause(cause);
845
- return terminalizeWith(snapshot, exit, Deferred.failCause(done, cause));
846
- };
847
- const terminalizeReservedSuccess = (snapshot, output) => {
848
- const exit = Exit.succeed(output);
849
- return terminalizeWith(snapshot, exit, Deferred.succeed(done, output));
850
- };
851
- const stop = Effect.uninterruptible(requestStop.pipe(Effect.andThen(awaitCompletion)));
852
- const acknowledgedContext = logic.execution?._tag !== "Compiled" ? undefined : {
853
- receiveMessage: Queue.take(queue).pipe(Effect.tap((message) => Effect.sync(() => {
854
- inFlightMessage = isAcknowledgedMessage(message) ? message : undefined;
855
- }))),
856
- pollMessage: Queue.poll(queue).pipe(Effect.tap((message) => Effect.sync(() => {
857
- if (Option.isSome(message)) {
858
- inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined;
859
- }
860
- }))),
861
- completeMessage: (delivery) => {
862
- succeedAcknowledgedMessage(inFlightMessage, delivery);
863
- inFlightMessage = undefined;
864
- }
865
- };
866
- const receive = inspector === undefined || logic.execution?._tag === "Compiled"
867
- ? Queue.take(queue).pipe(Effect.map(messageEvent))
868
- : Queue.take(queue).pipe(Effect.tap((message) => Effect.sync(() => {
869
- inFlightMessage = message;
870
- })), Effect.map(messageEvent));
871
- const poll = inspector === undefined || logic.execution?._tag === "Compiled"
872
- ? Queue.poll(queue).pipe(Effect.map(Option.map(messageEvent)))
873
- : Queue.poll(queue).pipe(Effect.tap((message) => Effect.sync(() => {
874
- if (Option.isSome(message))
875
- inFlightMessage = message.value;
876
- })), Effect.map(Option.map(messageEvent)));
877
- const updateStateDirect = (f) => updateSnapshot((snapshot) => snapshot.status === "active"
878
- ? f(snapshot.state).pipe(Effect.map((state) => ({
879
- status: "active",
880
- state
881
- })))
882
- : Effect.succeed(undefined)).pipe(Effect.asVoid);
883
- const updateState = inspector === undefined
884
- ? updateStateDirect
885
- : (f) => SynchronizedRef.get(current).pipe(Effect.flatMap((before) => updateSnapshot((snapshot) => snapshot.status === "active"
886
- ? f(snapshot.state).pipe(Effect.map((state) => ({
887
- status: "active",
888
- state
889
- })))
890
- : Effect.succeed(undefined)).pipe(Effect.tap((after) => Effect.sync(() => {
891
- if (logic.inspection?.kind === "Machine" || after?.status !== "active")
892
- return;
893
- inspector.publishUnsafe({
894
- _tag: "StateChanged",
895
- subject: subject,
896
- before: before.snapshot.state,
897
- after: after.state,
898
- causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage)
899
- ? inFlightMessage.inspection?.deliveryId
900
- : undefined
901
- });
902
- })))), Effect.asVoid);
903
- const context = {
904
- ...scope,
905
- ...(logic.execution?._tag === "Compiled" && !logic.execution.childless ? { ownedChildren } : undefined),
906
- ...acknowledgedContext,
907
- receive,
908
- poll,
909
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
910
- setState: setActiveState,
911
- updateState
912
- };
913
- const getOrCreateChanges = SynchronizedRef.modifyEffect(current, (current) => {
914
- if (current.snapshot.status !== "active") {
915
- return Effect.succeed([undefined, current]);
916
- }
917
- if (current.changes !== undefined) {
918
- return Effect.succeed([current.changes, current]);
919
- }
920
- return PubSub.unbounded({ replay: 1 }).pipe(Effect.map((changes) => [changes, { ...current, changes }]));
921
- });
922
- const changesStream = Stream.unwrap(Effect.gen(function* () {
923
- const changes = yield* getOrCreateChanges;
924
- if (changes === undefined) {
925
- return Stream.succeed((yield* SynchronizedRef.get(current)).snapshot);
926
- }
927
- const subscription = yield* PubSub.subscribe(changes);
928
- const captured = yield* SynchronizedRef.get(current);
929
- if (captured.snapshot.status !== "active") {
930
- return Stream.succeed(captured.snapshot);
931
- }
932
- return Stream.succeed(captured.snapshot).pipe(Stream.concat(Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(Stream.filter((next) => next.revision > captured.revision), Stream.map((next) => next.snapshot))));
933
- }));
934
- const ref = {
935
- id,
936
- sessionId,
937
- ...(inspector === undefined
938
- ? undefined
939
- : { inspectionSubject: subject, sendInspected: offerInspected }),
940
- state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)),
941
- snapshot: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot)),
942
- changes: changesStream,
943
- emissions: emissions.stream,
944
- join: Deferred.await(done),
945
- stop,
946
- send: self.send,
947
- ...(sendAcknowledged === undefined ? undefined : { [acknowledgedSend]: sendAcknowledged }),
948
- child: getChild,
949
- childChanges
950
- };
951
- if (onReadySync !== undefined && !onReadySync(ref)) {
952
- yield* requestStop;
953
- }
954
- else if (onReady !== undefined) {
955
- yield* onReady(ref, requestStop);
956
- }
957
- if (onSnapshot !== undefined) {
958
- yield* notifyActiveSnapshot(onSnapshot, { status: "active", state: initial });
959
- }
960
- const reserveTermination = (termination) => {
961
- switch (termination._tag) {
962
- case "Stopped":
963
- return reserveStoppedSnapshot;
964
- case "Done":
965
- return reserveSuccessSnapshot(termination.output);
966
- case "Failure":
967
- return reserveFailureSnapshot(termination.cause);
968
- }
969
- };
970
- const completeTermination = (termination, snapshot) => {
971
- switch (termination._tag) {
972
- case "Stopped":
973
- return terminalizeReservedStop(snapshot);
974
- case "Done":
975
- return terminalizeReservedSuccess(snapshot, termination.output);
976
- case "Failure":
977
- return terminalizeReservedFailure(snapshot, termination.cause);
978
- }
979
- };
980
- const forkRuntime = (effect) => detached === true
981
- ? Effect.forkDetach(effect)
982
- : Effect.forkChild(effect);
983
- const pendingTermination = yield* Deferred.poll(termination);
984
- const worker = Option.isNone(pendingTermination)
985
- ? yield* Effect.uninterruptibleMask((restore) => restore(Effect.suspend(() => logic.run(context))).pipe(Effect.exit, Effect.flatMap((exit) => Deferred.succeed(termination, Exit.isFailure(exit)
986
- ? { _tag: "Failure", cause: exit.cause }
987
- : { _tag: "Done", output: exit.value })))).pipe(forkRuntime)
988
- : undefined;
989
- // One Deferred arbitrates all terminal causes. The supervisor reserves the
990
- // terminal snapshot before interrupting the worker, so worker finalizers
991
- // cannot mutate the frozen state. It then waits for those finalizers before
992
- // publishing and completing `join` / `stop`.
993
- const runFiber = Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
994
- const requested = Option.isSome(pendingTermination)
995
- ? yield* pendingTermination.value
996
- : yield* restore(Deferred.await(termination));
997
- const snapshot = yield* reserveTermination(requested);
998
- if (worker !== undefined) {
999
- yield* Fiber.interrupt(worker);
1000
- }
1001
- if (snapshot === undefined) {
1002
- return yield* awaitCompletion;
1003
- }
1004
- return yield* completeTermination(requested, snapshot);
1005
- }));
1006
- yield* forkRuntime(runFiber);
1007
- yield* Effect.yieldNow;
1008
- return ref;
1009
- });
1010
- // Stopping is commonly used only for resource cleanup. Keep that path free of
1011
- // Error stack capture and materialize the typed join failure only if observed.
1012
- const CompiledStoppedCompletion = Symbol("effect/Machine/CompiledStoppedCompletion");
1013
- /**
1014
- * Compact runtime for compiled statecharts.
1015
- *
1016
- * All long-lived state is stored directly on this object. Operations are
1017
- * implemented by shared prototype methods, and public Effect / Stream values
1018
- * are materialized only when accessed. Arbitrary process logic continues to
1019
- * use the general runtime above.
1020
- */
1021
- class CompiledProcess {
1022
- logic;
1023
- options;
1024
- services;
1025
- id;
1026
- sessionId;
1027
- inspectionSubject;
1028
- send;
1029
- sendInspected(event, source, causedBy) {
1030
- return this.offerEvent(event, source, causedBy);
1031
- }
1032
- [acknowledgedSend](event) {
1033
- return this.sendAcknowledgedEffect(event);
1034
- }
1035
- mailbox = {
1036
- items: undefined,
1037
- index: 0,
1038
- closed: false
1039
- };
1040
- address;
1041
- childRuntime = childlessRuntime;
1042
- processScope;
1043
- processContext;
1044
- compiledContext;
1045
- current;
1046
- /**
1047
- * `Active` has no terminal payload, `TerminationRequested` owns
1048
- * `termination` and its optional reserved snapshot, and `Completed` owns
1049
- * `completion`. `runState` independently tracks worker activity.
1050
- */
1051
- lifecycle = "Active";
1052
- runState = "Initializing";
1053
- completion;
1054
- waiter;
1055
- termination;
1056
- terminationSnapshot;
1057
- worker;
1058
- interruptRequested = false;
1059
- offerRevision = 0;
1060
- inFlightMessage;
1061
- externalEmissions;
1062
- emissionsPubSub;
1063
- activity;
1064
- initialEntryPaths;
1065
- initialMicrosteps;
1066
- initializing;
1067
- constructor(logic, options, services, sessionId) {
1068
- this.logic = logic;
1069
- this.options = options;
1070
- this.services = services;
1071
- this.sessionId = sessionId;
1072
- this.id = options.id ?? sessionId;
1073
- const inspector = options.runtime.inspection;
1074
- if (inspector !== undefined) {
1075
- this.inspectionSubject = inspectionSubject(logic, this.id, sessionId);
1076
- this.initializing = true;
1077
- if (options.activity !== undefined)
1078
- this.activity = { ...options.activity, sessionId };
1079
- }
1080
- this.externalEmissions = options.emissions;
1081
- this.send = inspector === undefined
1082
- ? (event) => this.offerMessage(event)
1083
- : (event) => this.offerEvent(event, undefined, undefined);
1084
- this.address = {
1085
- id: this.id,
1086
- sessionId,
1087
- stop: Effect.suspend(() => this.stopFromProcess()),
1088
- send: this.send,
1089
- ...(inspector === undefined
1090
- ? undefined
1091
- : {
1092
- inspectionSubject: this.inspectionSubject,
1093
- sendInspected: (event, source, causedBy) => this.offerEvent(event, source, causedBy)
1094
- })
1095
- };
1096
- }
1097
- get inspector() {
1098
- return this.options.runtime.inspection;
1099
- }
1100
- causation() {
1101
- return messageCausation(this.inFlightMessage, this.initializing === true);
1102
- }
1103
- publishCreated() {
1104
- const inspector = this.inspector;
1105
- const subject = this.inspectionSubject;
1106
- if (inspector === undefined || subject === undefined)
1107
- return;
1108
- inspector.publishUnsafe(this.activity === undefined
1109
- ? {
1110
- _tag: "Created",
1111
- subject,
1112
- parent: this.options.parent?.inspectionSubject,
1113
- origin: this.options.origin ?? { _tag: "Root" },
1114
- definition: this.logic.inspection?.definition
1115
- }
1116
- : { _tag: "ActivityStarted", subject: this.activity.owner, activity: this.activity });
1117
- }
1118
- publishInitialized(state) {
1119
- this.initializing = false;
1120
- if (this.activity !== undefined)
1121
- return;
1122
- const inspector = this.inspector;
1123
- const subject = this.inspectionSubject;
1124
- if (inspector === undefined || subject === undefined)
1125
- return;
1126
- inspector.publishUnsafe({
1127
- _tag: "Initialized",
1128
- subject,
1129
- snapshot: { status: "active", state },
1130
- initialEntryPaths: this.initialEntryPaths ?? [],
1131
- microsteps: InspectionRuntime.microsteps({ microsteps: this.initialMicrosteps ?? [] })
1132
- });
1133
- }
1134
- publishStartFailed(cause) {
1135
- this.initializing = false;
1136
- const inspector = this.inspector;
1137
- const subject = this.inspectionSubject;
1138
- if (inspector === undefined || subject === undefined)
1139
- return;
1140
- inspector.publishUnsafe(this.activity === undefined
1141
- ? { _tag: "StartFailed", subject, cause }
1142
- : {
1143
- _tag: "ActivityStopped",
1144
- subject: this.activity.owner,
1145
- activity: this.activity,
1146
- exit: Exit.failCause(cause)
1147
- });
1148
- }
1149
- get execution() {
1150
- return this.logic.execution;
1151
- }
1152
- initializeCompiledSync() {
1153
- this.publishCreated();
1154
- if (!this.execution.childless) {
1155
- this.childRuntime = makeChildRuntimeSync(this.address, this.options.runtime, this.services, (event) => this.sendAcknowledgedEffect(event));
1156
- }
1157
- const parent = this.options.parent;
1158
- const sendParent = this.options.sendParent ?? (parent === undefined
1159
- ? noParentSend
1160
- : this.inspector === undefined
1161
- ? parent.send
1162
- : (event) => sendMachineTarget(parent, event, this.inspectionSubject, this.causation()));
1163
- this.processScope = {
1164
- self: this.address,
1165
- parent,
1166
- spawn: this.childRuntime.spawn,
1167
- sendParent,
1168
- emit: (event) => this.emitEvent(event),
1169
- sendTo: ((target, event) => isMachineTarget(target)
1170
- ? this.inspector === undefined
1171
- ? target.send(event)
1172
- : sendMachineTarget(target, event, this.inspectionSubject, this.causation())
1173
- : this.childRuntime.sendTo(target, event, this.inspectionSubject, this.causation())),
1174
- stopChild: this.childRuntime.stop,
1175
- failCause: (cause) => this.failCause(cause),
1176
- inspectInitial: this.inspector === undefined
1177
- ? noInspectInitial
1178
- : (paths, microsteps = []) => {
1179
- this.initialEntryPaths = paths;
1180
- this.initialMicrosteps = microsteps;
1181
- }
1182
- };
1183
- const compiledInitial = this.execution.initialSync;
1184
- let initialized;
1185
- try {
1186
- initialized = compiledInitial(this.processScope);
1187
- }
1188
- catch (error) {
1189
- this.runState = "Idle";
1190
- this.publishStartFailed(Cause.fail(error));
1191
- return Effect.fail(error);
1192
- }
1193
- this.runState = "Idle";
1194
- this.current = {
1195
- revision: 0,
1196
- terminalizing: false,
1197
- changes: undefined,
1198
- snapshot: { status: "active", state: initialized.state }
1199
- };
1200
- this.publishInitialized(initialized.state);
1201
- this.compiledContext = new CompiledProcessContextImpl(this.processScope, this.childRuntime.owned, this);
1202
- if ("executionState" in initialized) {
1203
- this.compiledContext.executionState = initialized.executionState;
1204
- }
1205
- if (this.options.onReadySync !== undefined && !this.options.onReadySync(this)) {
1206
- this.requestTerminationSync({ _tag: "Stopped" });
1207
- }
1208
- if (initialized.done === true && this.lifecycle === "Active") {
1209
- this.requestTerminationSync({ _tag: "Done", output: initialized.output });
1210
- }
1211
- if (initialized.done === false && this.execution.childless &&
1212
- this.lifecycle === "Active" &&
1213
- this.mailbox.items === undefined) {
1214
- return Effect.succeed(this);
1215
- }
1216
- this.runState = "Draining";
1217
- return Effect.provideContext(this.drainRuntime(), this.services).pipe(Effect.as(this));
1218
- }
1219
- initialize() {
1220
- const self = this;
1221
- return Effect.gen(function* () {
1222
- self.publishCreated();
1223
- if (!self.execution.childless) {
1224
- self.childRuntime = yield* makeChildRuntime(self.address, self.options.runtime, self.services, (event) => self.sendAcknowledgedEffect(event));
1225
- }
1226
- const parent = self.options.parent;
1227
- const sendParent = self.options.sendParent ?? (parent === undefined
1228
- ? noParentSend
1229
- : self.inspector === undefined
1230
- ? parent.send
1231
- : (event) => sendMachineTarget(parent, event, self.inspectionSubject, self.causation()));
1232
- self.processScope = {
1233
- self: self.address,
1234
- parent,
1235
- spawn: self.childRuntime.spawn,
1236
- sendParent,
1237
- emit: (event) => self.emitEvent(event),
1238
- sendTo: ((target, event) => isMachineTarget(target)
1239
- ? self.inspector === undefined
1240
- ? target.send(event)
1241
- : sendMachineTarget(target, event, self.inspectionSubject, self.causation())
1242
- : self.childRuntime.sendTo(target, event, self.inspectionSubject, self.causation())),
1243
- stopChild: self.childRuntime.stop,
1244
- failCause: (cause) => self.failCause(cause),
1245
- inspectInitial: self.inspector === undefined
1246
- ? noInspectInitial
1247
- : (paths, microsteps = []) => {
1248
- self.initialEntryPaths = paths;
1249
- self.initialMicrosteps = microsteps;
1250
- }
1251
- };
1252
- const cleanupStartupFailure = (exit) => Exit.isFailure(exit) ? self.childRuntime.close(exit) : Effect.void;
1253
- const compiledInitial = self.execution.initial;
1254
- const initializeEffect = compiledInitial === undefined
1255
- ? self.logic.initial(self.processScope).pipe(Effect.map((state) => ({ state, done: undefined, output: undefined })))
1256
- : compiledInitial(self.processScope);
1257
- const initialized = yield* initializeEffect.pipe(Effect.onExit((exit) => {
1258
- if (Exit.isFailure(exit))
1259
- self.publishStartFailed(exit.cause);
1260
- return cleanupStartupFailure(exit);
1261
- }), Effect.ensuring(Effect.sync(() => {
1262
- self.runState = "Idle";
1263
- })));
1264
- const initial = initialized.state;
1265
- self.current = {
1266
- revision: 0,
1267
- terminalizing: false,
1268
- changes: undefined,
1269
- snapshot: { status: "active", state: initial }
1270
- };
1271
- self.publishInitialized(initial);
1272
- if (self.execution.drain._tag === "Process") {
1273
- self.processContext = {
1274
- ...self.processScope,
1275
- receive: Effect.never,
1276
- poll: Effect.sync(() => Option.map(pollCompactMailbox(self.mailbox), messageEvent)),
1277
- receiveMessage: Effect.never,
1278
- pollMessage: Effect.sync(() => self.pollCompiledMessage()),
1279
- completeMessage: (delivery) => self.completeCompiledMessage(delivery),
1280
- state: Effect.sync(() => self.current.snapshot.state),
1281
- setState: (state) => self.setActiveState(state),
1282
- updateState: (f) => self.updateState(f)
1283
- };
1284
- }
1285
- else {
1286
- self.compiledContext = new CompiledProcessContextImpl(self.processScope, self.childRuntime.owned, self);
1287
- if ("executionState" in initialized) {
1288
- self.compiledContext.executionState = initialized.executionState;
1289
- }
1290
- }
1291
- if (self.options.onReadySync !== undefined && !self.options.onReadySync(self)) {
1292
- yield* self.requestTermination({ _tag: "Stopped" });
1293
- }
1294
- else if (self.options.onReady !== undefined) {
1295
- yield* self.options.onReady(self, self.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid));
1296
- }
1297
- if (self.options.onSnapshot !== undefined) {
1298
- yield* notifyActiveSnapshot(self.options.onSnapshot, { status: "active", state: initial });
1299
- }
1300
- if (initialized.done === true && self.lifecycle === "Active") {
1301
- yield* self.requestTermination({ _tag: "Done", output: initialized.output });
1302
- }
1303
- // A compiled machine startup plan has already settled entry actions,
1304
- // raised events, and eventless transitions. If it is known active and
1305
- // neither startup hooks nor emitted work queued an event, there is no
1306
- // first drain to perform. Future sends observe an idle run state and
1307
- // schedule the ordinary compiled worker.
1308
- if (initialized.done === false && self.execution.childless &&
1309
- self.lifecycle === "Active" && self.mailbox.items === undefined) {
1310
- return self;
1311
- }
1312
- self.runState = "Draining";
1313
- yield* self.drainRuntime();
1314
- return self;
1315
- });
1316
- }
1317
- get state() {
1318
- return Effect.sync(() => this.current.snapshot.state);
1319
- }
1320
- get snapshot() {
1321
- return Effect.sync(() => this.current.snapshot);
1322
- }
1323
- get changes() {
1324
- return this.changesStream();
1325
- }
1326
- get emissions() {
1327
- return (this.externalEmissions?.stream ?? this.emissionsStream());
1328
- }
1329
- get join() {
1330
- return Effect.suspend(() => {
1331
- if (this.lifecycle === "Completed") {
1332
- return this.resolveCompletion(this.completion);
1333
- }
1334
- this.waiter ??= Deferred.makeUnsafe();
1335
- return Deferred.await(this.waiter);
1336
- });
1337
- }
1338
- get stop() {
1339
- return Effect.uninterruptible(this.stopEffect());
1340
- }
1341
- child(child) {
1342
- return this.childRuntime.get(child);
1343
- }
1344
- childChanges(child) {
1345
- return this.childRuntime.changes(child);
1346
- }
1347
- requestTermination(requested) {
1348
- return Effect.sync(() => this.requestTerminationSync(requested));
1349
- }
1350
- hasTerminationRequest() {
1351
- return this.lifecycle === "TerminationRequested";
1352
- }
1353
- requestTerminationSync(requested) {
1354
- if (this.lifecycle !== "Active") {
1355
- return false;
1356
- }
1357
- this.lifecycle = "TerminationRequested";
1358
- this.termination = requested;
1359
- this.terminationSnapshot = this.reserveTermination(requested);
1360
- return true;
1361
- }
1362
- reserveTermination(requested) {
1363
- const latest = this.current;
1364
- if (latest === undefined || latest.terminalizing || latest.snapshot.status !== "active") {
1365
- return undefined;
1366
- }
1367
- const snapshot = requested._tag === "Stopped"
1368
- ? { status: "stopped", state: latest.snapshot.state }
1369
- : requested._tag === "Done"
1370
- ? { status: "done", state: latest.snapshot.state, output: requested.output }
1371
- : { status: "error", state: latest.snapshot.state, cause: requested.cause };
1372
- this.current = { ...latest, terminalizing: true };
1373
- return snapshot;
1374
- }
1375
- stopFromProcess() {
1376
- const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid);
1377
- return this.runState === "Initializing" ? request : request.pipe(Effect.andThen(Effect.interrupt));
1378
- }
1379
- failCause(cause) {
1380
- const requested = { _tag: "Failure", cause };
1381
- return this.requestTermination(requested).pipe(Effect.flatMap((accepted) => accepted
1382
- ? Effect.forkDetach(this.settleRequestedTermination()).pipe(Effect.asVoid)
1383
- : Effect.void));
1384
- }
1385
- sendAcknowledgedEffect(event) {
1386
- return Effect.uninterruptibleMask((restore) => Deferred.make().pipe(Effect.flatMap((deferred) => this.offerEvent(event, undefined, undefined, deferred).pipe(Effect.andThen(restore(Deferred.await(deferred)))))));
1387
- }
1388
- offerEvent(event, source, causedBy, deferred) {
1389
- return Effect.suspend(() => {
1390
- const inspector = this.inspector;
1391
- const subject = this.inspectionSubject;
1392
- const message = inspector?.isActive() === true && subject !== undefined
1393
- ? makeInspectedMessage(inspector, subject, event, source, causedBy, deferred)
1394
- : deferred === undefined
1395
- ? event
1396
- : { [AcknowledgedMessageTypeId]: true, event, deferred };
1397
- return this.offerMessage(message);
1398
- });
1399
- }
1400
- offerMessage(message) {
1401
- return Effect.uninterruptible(Effect.suspend(() => {
1402
- if (this.mailbox.closed || this.lifecycle !== "Active") {
1403
- return Effect.fail(new StoppedError());
1404
- }
1405
- offerCompactMailbox(this.mailbox, message);
1406
- const inspector = this.inspector;
1407
- const subject = this.inspectionSubject;
1408
- if (inspector !== undefined && subject !== undefined)
1409
- publishInspectedSent(inspector, subject, message);
1410
- this.offerRevision += 1;
1411
- if (this.runState === "Draining") {
1412
- return Effect.void;
1413
- }
1414
- this.runState = "Draining";
1415
- const scheduled = Effect.yieldNow.pipe(Effect.andThen(Effect.provideContext(this.drainRuntime(), this.services)));
1416
- const fork = this.options.detached === true
1417
- ? Effect.forkDetach(scheduled, { startImmediately: true })
1418
- : Effect.forkChild(scheduled, { startImmediately: true });
1419
- return fork.pipe(Effect.flatMap((fiber) => Effect.sync(() => {
1420
- this.worker = fiber;
1421
- if (!this.interruptRequested) {
1422
- return false;
1423
- }
1424
- this.interruptRequested = false;
1425
- return true;
1426
- }).pipe(Effect.flatMap((interrupt) => interrupt ? this.interruptAndFinish(fiber) : Effect.void))), Effect.asVoid);
1427
- }));
1428
- }
1429
- stopEffect() {
1430
- return Effect.suspend(() => {
1431
- if (this.lifecycle === "Completed") {
1432
- return Effect.void;
1433
- }
1434
- if (this.finishIdleChildlessStop()) {
1435
- return Effect.void;
1436
- }
1437
- const requested = { _tag: "Stopped" };
1438
- return this.requestTermination(requested).pipe(Effect.flatMap((accepted) => accepted
1439
- ? this.settleRequestedTermination()
1440
- : this.awaitCompletion()));
1441
- });
1442
- }
1443
- finishIdleChildlessStop() {
1444
- if (!this.execution.childless || this.runState !== "Idle" || this.worker !== undefined ||
1445
- this.lifecycle !== "Active" ||
1446
- (this.options.onOutcome !== undefined && this.options.skipStoppedOutcome !== true) ||
1447
- this.options.onStop !== undefined ||
1448
- this.inspector !== undefined ||
1449
- this.current.changes !== undefined ||
1450
- this.current.terminalizing || this.current.snapshot.status !== "active") {
1451
- return false;
1452
- }
1453
- const snapshot = { status: "stopped", state: this.current.snapshot.state };
1454
- this.lifecycle = "TerminationRequested";
1455
- this.termination = { _tag: "Stopped" };
1456
- this.terminationSnapshot = snapshot;
1457
- closeCompactMailbox(this.mailbox);
1458
- this.current = {
1459
- revision: this.current.revision + 1,
1460
- terminalizing: true,
1461
- changes: undefined,
1462
- snapshot
1463
- };
1464
- stopAcknowledgedMessage(this.inFlightMessage);
1465
- this.inFlightMessage = undefined;
1466
- this.interruptRequested = false;
1467
- if (this.compiledContext !== undefined) {
1468
- this.compiledContext.executionState = undefined;
1469
- }
1470
- this.options.onStopSync?.();
1471
- this.completion = CompiledStoppedCompletion;
1472
- this.lifecycle = "Completed";
1473
- if (this.waiter !== undefined) {
1474
- Deferred.doneUnsafe(this.waiter, this.resolveCompletion(CompiledStoppedCompletion));
1475
- this.waiter = undefined;
1476
- }
1477
- return true;
1478
- }
1479
- settleRequestedTermination() {
1480
- return Effect.suspend(() => {
1481
- if (this.runState !== "Draining") {
1482
- return this.finishRequestedTermination();
1483
- }
1484
- if (this.worker === undefined) {
1485
- this.interruptRequested = true;
1486
- return this.awaitCompletion();
1487
- }
1488
- return this.interruptAndFinish(this.worker).pipe(Effect.andThen(this.awaitCompletion()));
1489
- });
1490
- }
1491
- interruptAndFinish(worker) {
1492
- return Fiber.interrupt(worker).pipe(Effect.andThen(Effect.suspend(() => this.lifecycle !== "Completed"
1493
- ? this.finishRequestedTermination()
1494
- : Effect.void)));
1495
- }
1496
- awaitCompletion() {
1497
- return this.lifecycle !== "Completed"
1498
- ? this.join.pipe(Effect.exit, Effect.asVoid)
1499
- : Effect.void;
1500
- }
1501
- resolveCompletion(completion) {
1502
- if (completion !== CompiledStoppedCompletion) {
1503
- return completion;
1504
- }
1505
- const stopped = Effect.fail(new StoppedError());
1506
- this.completion = stopped;
1507
- return stopped;
1508
- }
1509
- drainRuntime() {
1510
- const self = this;
1511
- return Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1512
- let observedRevision = self.offerRevision;
1513
- while (true) {
1514
- if (self.hasTerminationRequest()) {
1515
- return yield* self.finishRequestedTermination();
1516
- }
1517
- const exit = yield* restore(Effect.suspend(() => {
1518
- const drain = self.execution.drain;
1519
- return drain._tag === "Process"
1520
- ? drain.run(self.processContext)
1521
- : drain.run(self.compiledContext);
1522
- })).pipe(Effect.exit);
1523
- self.flushPendingChanges();
1524
- if (Exit.isFailure(exit)) {
1525
- if (self.lifecycle === "Active") {
1526
- yield* self.requestTermination({ _tag: "Failure", cause: exit.cause });
1527
- }
1528
- return yield* self.finishRequestedTermination();
1529
- }
1530
- if (Option.isSome(exit.value)) {
1531
- yield* self.requestTermination({ _tag: "Done", output: exit.value.value });
1532
- return yield* self.finishRequestedTermination();
1533
- }
1534
- if (self.hasTerminationRequest()) {
1535
- return yield* self.finishRequestedTermination();
1536
- }
1537
- if (self.offerRevision !== observedRevision) {
1538
- observedRevision = self.offerRevision;
1539
- continue;
1540
- }
1541
- self.runState = "Idle";
1542
- self.worker = undefined;
1543
- return;
1544
- }
1545
- }));
1546
- }
1547
- finishRequestedTermination() {
1548
- return Effect.suspend(() => {
1549
- if (this.lifecycle !== "TerminationRequested") {
1550
- return Effect.void;
1551
- }
1552
- const requested = this.termination;
1553
- if (requested === undefined) {
1554
- return Effect.void;
1555
- }
1556
- const snapshot = this.terminationSnapshot ?? this.reserveTermination(requested);
1557
- if (snapshot === undefined) {
1558
- return this.awaitCompletion();
1559
- }
1560
- const exit = requested._tag === "Stopped"
1561
- ? Exit.void
1562
- : requested._tag === "Done"
1563
- ? Exit.succeed(requested.output)
1564
- : Exit.failCause(requested.cause);
1565
- const completion = requested._tag === "Stopped"
1566
- ? CompiledStoppedCompletion
1567
- : requested._tag === "Done"
1568
- ? Effect.succeed(requested.output)
1569
- : Effect.failCause(requested.cause);
1570
- const notifyOutcome = this.options.onOutcome === undefined ||
1571
- (requested._tag === "Stopped" && this.options.skipStoppedOutcome === true)
1572
- ? Effect.void
1573
- : Effect.suspend(() => this.options.onOutcome(classifyOutcome(snapshot))).pipe(Effect.exit, Effect.asVoid);
1574
- const inspector = this.inspector;
1575
- const subject = this.inspectionSubject;
1576
- const closeEmissionsAndInspect = inspector === undefined || subject === undefined
1577
- ? this.closeEmissions()
1578
- : this.closeEmissions().pipe(Effect.andThen(Effect.sync(() => inspector.publishUnsafe(this.activity === undefined
1579
- ? { _tag: "Terminated", subject, snapshot }
1580
- : {
1581
- _tag: "ActivityStopped",
1582
- subject: this.activity.owner,
1583
- activity: this.activity,
1584
- exit: snapshot.status === "stopped" ? Exit.interrupt() : exit
1585
- }))));
1586
- return Effect.uninterruptible(Effect.sync(() => {
1587
- closeCompactMailbox(this.mailbox);
1588
- }).pipe(Effect.andThen(this.childRuntime.close(exit)), Effect.andThen(this.setAndPublishSnapshot(snapshot)), Effect.andThen(closeEmissionsAndInspect), Effect.andThen(Effect.sync(() => {
1589
- if (requested._tag === "Failure") {
1590
- failAcknowledgedMessage(this.inFlightMessage, requested.cause);
1591
- }
1592
- else {
1593
- stopAcknowledgedMessage(this.inFlightMessage);
1594
- }
1595
- this.inFlightMessage = undefined;
1596
- })), Effect.andThen(notifyOutcome), Effect.andThen(this.options.onStop ?? Effect.void), Effect.andThen(this.options.inspectionRoot === true && this.inspector !== undefined
1597
- ? this.inspector.close
1598
- : Effect.void), Effect.andThen(Effect.sync(() => {
1599
- this.options.onStopSync?.();
1600
- this.runState = "Idle";
1601
- this.worker = undefined;
1602
- this.interruptRequested = false;
1603
- if (this.compiledContext !== undefined) {
1604
- this.compiledContext.executionState = undefined;
1605
- }
1606
- this.completion = completion;
1607
- this.lifecycle = "Completed";
1608
- if (this.waiter !== undefined) {
1609
- Deferred.doneUnsafe(this.waiter, this.resolveCompletion(completion));
1610
- this.waiter = undefined;
1611
- }
1612
- }))));
1613
- });
1614
- }
1615
- publishSnapshot(snapshot) {
1616
- const publish = snapshot.changes === undefined
1617
- ? Effect.succeed(snapshot)
1618
- : PubSub.publish(snapshot.changes, [snapshot]).pipe(Effect.as(snapshot));
1619
- const current = snapshot.snapshot;
1620
- return this.options.onSnapshot === undefined || current.status !== "active"
1621
- ? publish
1622
- : publish.pipe(Effect.tap(() => notifyActiveSnapshot(this.options.onSnapshot, current)));
1623
- }
1624
- completeChanges(snapshot) {
1625
- return snapshot.changes === undefined
1626
- ? Effect.void
1627
- : PubSub.publish(snapshot.changes, Exit.succeed(undefined)).pipe(Effect.asVoid);
1628
- }
1629
- emitEvent(event) {
1630
- const publish = this.externalEmissions !== undefined ?
1631
- this.externalEmissions.emit(event) :
1632
- Effect.suspend(() => this.emissionsPubSub === undefined || this.emissionsPubSub === EmissionsClosed
1633
- ? Effect.void
1634
- : PubSub.publish(this.emissionsPubSub, event).pipe(Effect.asVoid));
1635
- const inspector = this.inspector;
1636
- const subject = this.inspectionSubject;
1637
- if (inspector === undefined || subject === undefined)
1638
- return publish;
1639
- return publish.pipe(Effect.tap(() => Effect.sync(() => inspector.publishUnsafe({
1640
- _tag: "Emitted",
1641
- subject,
1642
- emission: event,
1643
- causedBy: this.causation()
1644
- }))));
1645
- }
1646
- shutdownEmissions() {
1647
- return this.closeEmissions();
1648
- }
1649
- closeEmissions() {
1650
- if (this.externalEmissions !== undefined)
1651
- return this.externalEmissions.close();
1652
- const observed = this.emissionsPubSub;
1653
- this.emissionsPubSub = EmissionsClosed;
1654
- return observed === undefined || observed === EmissionsClosed ? Effect.void : PubSub.shutdown(observed);
1655
- }
1656
- getOrCreateEmissions() {
1657
- return Effect.suspend(() => {
1658
- const observed = this.emissionsPubSub;
1659
- if (observed === EmissionsClosed)
1660
- return Effect.succeed(undefined);
1661
- if (observed !== undefined)
1662
- return Effect.succeed(observed);
1663
- return PubSub.unbounded().pipe(Effect.flatMap((candidate) => Effect.sync(() => {
1664
- const latest = this.emissionsPubSub;
1665
- if (latest === EmissionsClosed)
1666
- return [undefined, true];
1667
- if (latest !== undefined)
1668
- return [latest, true];
1669
- this.emissionsPubSub = candidate;
1670
- return [candidate, false];
1671
- }).pipe(Effect.flatMap(([selected, discard]) => discard ? PubSub.shutdown(candidate).pipe(Effect.as(selected)) : Effect.succeed(selected)))));
1672
- });
1673
- }
1674
- emissionsStream() {
1675
- return Stream.unwrap(this.getOrCreateEmissions().pipe(Effect.map((emissions) => emissions === undefined ? Stream.empty : Stream.fromPubSub(emissions))));
1676
- }
1677
- setAndPublishSnapshot(snapshot) {
1678
- return Effect.suspend(() => {
1679
- this.flushPendingChanges();
1680
- const versioned = {
1681
- revision: this.current.revision + 1,
1682
- snapshot,
1683
- terminalizing: true,
1684
- changes: this.current.changes
1685
- };
1686
- this.current = versioned;
1687
- return this.publishSnapshot(versioned).pipe(Effect.flatMap((published) => this.completeChanges(published)), Effect.asVoid);
1688
- });
1689
- }
1690
- setActiveState(state) {
1691
- return Effect.suspend(() => this.commitActiveState(state) ?? Effect.void);
1692
- }
1693
- pollCompiledMessage() {
1694
- const message = pollCompactMailbox(this.mailbox);
1695
- if (Option.isSome(message)) {
1696
- this.inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined;
1697
- }
1698
- return message;
1699
- }
1700
- completeCompiledMessage(delivery) {
1701
- succeedAcknowledgedMessage(this.inFlightMessage, delivery);
1702
- this.inFlightMessage = undefined;
1703
- }
1704
- compiledState() {
1705
- return this.current.snapshot.state;
1706
- }
1707
- commitCompiledState(state) {
1708
- return this.commitActiveState(state, true);
1709
- }
1710
- commitActiveState(state, batchChanges = false) {
1711
- const latest = this.current;
1712
- if (latest.terminalizing || latest.snapshot.status !== "active") {
1713
- return undefined;
1714
- }
1715
- const pendingChanges = latest.pendingChanges;
1716
- if (pendingChanges !== undefined) {
1717
- latest.pendingChanges = undefined;
1718
- }
1719
- const activeSnapshot = { status: "active", state };
1720
- const versioned = {
1721
- revision: latest.revision + 1,
1722
- snapshot: activeSnapshot,
1723
- terminalizing: false,
1724
- changes: latest.changes
1725
- };
1726
- this.current = versioned;
1727
- if (versioned.changes !== undefined) {
1728
- if (pendingChanges === undefined) {
1729
- if (batchChanges) {
1730
- versioned.pendingChanges = [versioned];
1731
- }
1732
- else {
1733
- PubSub.publishUnsafe(versioned.changes, [versioned]);
1734
- }
1735
- }
1736
- else {
1737
- pendingChanges.push(versioned);
1738
- if (batchChanges) {
1739
- versioned.pendingChanges = pendingChanges;
1740
- }
1741
- else {
1742
- PubSub.publishUnsafe(versioned.changes, pendingChanges);
1743
- }
1744
- }
1745
- }
1746
- return this.options.onSnapshot === undefined
1747
- ? undefined
1748
- : notifyActiveSnapshot(this.options.onSnapshot, activeSnapshot);
1749
- }
1750
- flushPendingChanges() {
1751
- const current = this.current;
1752
- const pendingChanges = current?.pendingChanges;
1753
- if (pendingChanges === undefined || current.changes === undefined) {
1754
- return;
1755
- }
1756
- current.pendingChanges = undefined;
1757
- PubSub.publishUnsafe(current.changes, pendingChanges);
1758
- }
1759
- updateState(f) {
1760
- return Effect.suspend(() => {
1761
- const observed = this.current;
1762
- if (observed.terminalizing || observed.snapshot.status !== "active") {
1763
- return Effect.void;
1764
- }
1765
- return f(observed.snapshot.state).pipe(Effect.flatMap((state) => {
1766
- const latest = this.current;
1767
- return latest.terminalizing || latest.revision !== observed.revision
1768
- ? Effect.void
1769
- : this.setActiveState(state);
1770
- }));
1771
- });
1772
- }
1773
- getOrCreateChanges() {
1774
- return Effect.suspend(() => {
1775
- const observed = this.current;
1776
- if (observed.snapshot.status !== "active") {
1777
- return Effect.succeed(undefined);
1778
- }
1779
- if (observed.changes !== undefined) {
1780
- return Effect.succeed(observed.changes);
1781
- }
1782
- return PubSub.unbounded({ replay: 1 }).pipe(Effect.flatMap((candidate) => Effect.sync(() => {
1783
- const latest = this.current;
1784
- if (latest.snapshot.status !== "active") {
1785
- return [undefined, true];
1786
- }
1787
- if (latest.changes !== undefined) {
1788
- return [latest.changes, true];
1789
- }
1790
- this.current = { ...latest, changes: candidate };
1791
- return [candidate, false];
1792
- }).pipe(Effect.flatMap(([changes, discard]) => discard ? PubSub.shutdown(candidate).pipe(Effect.as(changes)) : Effect.succeed(changes)))));
1793
- });
1794
- }
1795
- changesStream() {
1796
- const self = this;
1797
- return Stream.unwrap(Effect.gen(function* () {
1798
- const changes = yield* self.getOrCreateChanges();
1799
- if (changes === undefined) {
1800
- return Stream.succeed(self.current.snapshot);
1801
- }
1802
- const subscription = yield* PubSub.subscribe(changes);
1803
- const captured = self.current;
1804
- if (captured.snapshot.status !== "active") {
1805
- return Stream.succeed(captured.snapshot);
1806
- }
1807
- return Stream.succeed(captured.snapshot).pipe(Stream.concat(Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe(Stream.filter((next) => next.revision > captured.revision), Stream.map((next) => next.snapshot))));
1808
- }));
1809
- }
1810
- }
1811
- class CompiledProcessContextImpl {
1812
- scope;
1813
- ownedChildren;
1814
- process;
1815
- executionState;
1816
- constructor(scope, ownedChildren, process) {
1817
- this.scope = scope;
1818
- this.ownedChildren = ownedChildren;
1819
- this.process = process;
1820
- }
1821
- poll() {
1822
- return Option.map(this.process.pollCompiledMessage(), messageEvent);
1823
- }
1824
- pollMessage() {
1825
- return this.process.pollCompiledMessage();
1826
- }
1827
- state() {
1828
- return this.process.compiledState();
1829
- }
1830
- completeMessage(delivery) {
1831
- this.process.completeCompiledMessage(delivery);
1832
- }
1833
- commit(state) {
1834
- return this.process.commitCompiledState(state);
1835
- }
1836
- runAfterChanges(effect) {
1837
- this.process.flushPendingChanges();
1838
- return effect;
1839
- }
1840
- }
1841
- const startCompactCompiledInternal = Effect.fnUntraced(function* (logic, options) {
1842
- const sessionId = options.sessionId ?? (yield* options.runtime.nextSessionId);
1843
- const services = yield* Effect.context();
1844
- const execution = logic.execution;
1845
- const process = new CompiledProcess(logic, options, services, sessionId);
1846
- // A compiled initializer is synchronous by construction. Only startup
1847
- // callbacks that themselves return Effects need the generic initialization
1848
- // program; the compiled drain is still provided the complete service context.
1849
- const initialize = execution.initialSync !== undefined &&
1850
- options.onReady === undefined && options.onSnapshot === undefined
1851
- ? process.initializeCompiledSync()
1852
- : process.initialize();
1853
- return yield* initialize.pipe(Effect.onExit((exit) => Exit.isFailure(exit)
1854
- ? process.shutdownEmissions().pipe(Effect.andThen(options.inspectionRoot === true && options.runtime.inspection !== undefined
1855
- ? options.runtime.inspection.close
1856
- : Effect.void))
1857
- : Effect.void));
1858
- });
6
+ import { startCompactCompiledInternal, startCompiledSync } from "./runtimeCompiled.js";
7
+ import { startGenericInternal } from "./runtimeGeneric.js";
8
+ import { makeEmissionRuntime, makeProcessRuntime } from "./runtimeProtocol.js";
1859
9
  const startLogicInternal = ((logic, options) => logic.execution?._tag === "Compiled"
1860
10
  ? startCompactCompiledInternal(logic, options)
1861
11
  : startGenericInternal(logic, options));
12
+ const makeRuntime = makeProcessRuntime(startLogicInternal, startCompiledSync);
1862
13
  const startProcessWithStrategy = Effect.fnUntraced(function* (logic, strategy, options) {
1863
- const runtime = yield* makeProcessRuntime;
14
+ const runtime = yield* makeRuntime;
1864
15
  const internalOptions = options === undefined
1865
16
  ? {
1866
17
  detached: true,
@@ -1885,7 +36,7 @@ const startProcessWithStrategy = Effect.fnUntraced(function* (logic, strategy, o
1885
36
  /** @internal Test-only startup strategy selection. */
1886
37
  export const startProcessWithStrategyForTesting = (logic, strategy, options) => startProcessWithStrategy(logic, strategy, options);
1887
38
  export const startProcess = Effect.fnUntraced(function* (logic, options) {
1888
- const runtime = yield* makeProcessRuntime;
39
+ const runtime = yield* makeRuntime;
1889
40
  return yield* startLogicInternal(logic, options === undefined
1890
41
  ? {
1891
42
  detached: true,
@@ -1898,7 +49,7 @@ export const startProcess = Effect.fnUntraced(function* (logic, options) {
1898
49
  });
1899
50
  });
1900
51
  const prepareProcessWithStrategy = Effect.fnUntraced(function* (logic, strategy, options) {
1901
- const runtime = yield* makeProcessRuntime;
52
+ const runtime = yield* makeRuntime;
1902
53
  const sessionId = yield* runtime.nextSessionId;
1903
54
  const inspection = yield* InspectionRuntime.make(sessionId);
1904
55
  runtime.inspection = inspection;