@typeonce/effect-machine 0.44.0 → 0.45.1

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.
@@ -84,42 +84,104 @@ const hasInvokeCapability = (machine: Machine.Any): boolean => {
84
84
  return hasInvokes
85
85
  }
86
86
 
87
+ const noQueuedMessages = Effect.succeed(Option.none())
88
+
87
89
  const makeChildlessCompiledDrain = (
88
90
  machine: Machine.Any,
89
91
  checkInitialFinal: boolean
90
- ): (
91
- context: internalRuntimeProtocol.CompiledProcessContext<any, any>
92
- ) => Effect.Effect<Option.Option<any>, any, any> => {
92
+ ): Pick<internalRuntimeProtocol.OwnedCompiledProcessDrain<any, any, any, any, any>, "run" | "runSync"> => {
93
+ type Context = internalRuntimeProtocol.CompiledProcessContext<any, any>
93
94
  const executionPlan = ExecutionPlan.compileExecutionPlan(machine)
94
- return (context) => {
95
- let current = context.state()
96
- if (checkInitialFinal && internalPlanner.isFinalState(machine, current)) {
97
- return internalPlanner.getFinalOutputEffect(
98
- machine,
99
- current,
100
- internalPlanner.InitialEvent
101
- ).pipe(Effect.map(Option.some))
95
+ const liveRuntimes = new WeakMap<object, Runtime<unknown, unknown>>()
96
+ const liveRuntime = (context: Context): Runtime<unknown, unknown> => {
97
+ let runtime = liveRuntimes.get(context.scope)
98
+ if (runtime === undefined) {
99
+ runtime = CommandRuntime.makeLiveRuntime(machine, context.scope)
100
+ liveRuntimes.set(context.scope, runtime)
102
101
  }
102
+ return runtime
103
+ }
104
+ const initialOutput = (context: Context): Effect.Effect<Option.Option<any>, any, any> | undefined => {
105
+ if (!checkInitialFinal) return undefined
106
+ const current = context.state()
107
+ return internalPlanner.isFinalState(machine, current)
108
+ ? internalPlanner.getFinalOutputEffect(machine, current, internalPlanner.InitialEvent).pipe(
109
+ Effect.map(Option.some)
110
+ )
111
+ : undefined
112
+ }
113
+ const loop = (context: Context): Effect.Effect<Option.Option<any>, any, any> =>
114
+ Effect.suspend(() => drainSync(context) ?? noQueuedMessages)
115
+
116
+ // Runs the effectful work of one planned message, then continues the drain.
117
+ const continueEffectful = (
118
+ context: Context,
119
+ acknowledged: boolean,
120
+ before: unknown,
121
+ planned: ReturnType<typeof executionPlan.plan>,
122
+ next: unknown
123
+ ): Effect.Effect<Option.Option<any>, any, any> => {
124
+ const beforeCommit = planned.commands.length === 0
125
+ ? undefined
126
+ : CommandRuntime.runCommands(planned.commands, context.scope)
127
+ const afterCommit = planned.emittedEvents.length === 0
128
+ ? undefined
129
+ : CommandRuntime.runEmittedEvents(planned.emittedEvents, liveRuntime(context))
130
+ const continueAfterCommit = (): Effect.Effect<Option.Option<any>, any, any> => {
131
+ const continued = Effect.suspend(() => {
132
+ if (acknowledged) {
133
+ context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next })
134
+ }
135
+ return planned.done ? Effect.succeed(Option.some(planned.output)) : loop(context)
136
+ })
137
+ return afterCommit === undefined ? continued : afterCommit.pipe(Effect.andThen(continued))
138
+ }
139
+ const commitAndContinue = (): Effect.Effect<Option.Option<any>, any, any> => {
140
+ const notification = context.commit(next)
141
+ const continued = continueAfterCommit()
142
+ const effect = notification === undefined ? continued : notification.pipe(Effect.andThen(continued))
143
+ return notification === undefined && afterCommit === undefined
144
+ ? effect
145
+ : context.runAfterChanges(effect)
146
+ }
147
+ return beforeCommit === undefined
148
+ ? commitAndContinue()
149
+ : context.runAfterChanges(beforeCommit.pipe(Effect.andThen(Effect.suspend(commitAndContinue))))
150
+ }
103
151
 
104
- let configuration = context.executionState
105
- let liveRuntime: Runtime<unknown, unknown> | undefined
106
- let loop: Effect.Effect<Option.Option<any>, any, any>
107
- loop = Effect.suspend(() => {
108
- const pending = context.pollMessage()
109
- if (Option.isNone(pending)) {
110
- context.executionState = undefined
111
- return Effect.succeed(Option.none())
152
+ // Commits queued messages whose transitions need no effectful work. Returns
153
+ // the drain continuing from the first message that does, or `undefined`
154
+ // once the mailbox is empty. Only this drain commits a childless machine's
155
+ // state, so the compact execution state stays valid in the process context
156
+ // while the machine is idle and the next send does not re-derive it.
157
+ const drainSync = (
158
+ context: Context,
159
+ first?: internalRuntimeProtocol.ProcessMessage<any>
160
+ ): Effect.Effect<Option.Option<any>, any, any> | undefined => {
161
+ let delivered = first
162
+ while (true) {
163
+ let message: internalRuntimeProtocol.ProcessMessage<any>
164
+ if (delivered !== undefined) {
165
+ message = delivered
166
+ delivered = undefined
167
+ context.beginMessage(message)
168
+ } else {
169
+ const pending = context.pollMessage()
170
+ if (Option.isNone(pending)) {
171
+ return undefined
172
+ }
173
+ message = pending.value
112
174
  }
113
175
 
114
- const message = pending.value
115
176
  const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message)
116
177
  const event = acknowledged ? message.event : message
117
- const before = current
178
+ const before = context.state()
118
179
 
119
180
  let planned
120
181
  try {
121
182
  planned = executionPlan.plan(
122
- configuration ?? executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, current)),
183
+ context.executionState ??
184
+ executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, before)),
123
185
  event,
124
186
  acknowledged,
125
187
  context.scope
@@ -127,56 +189,48 @@ const makeChildlessCompiledDrain = (
127
189
  } catch (error) {
128
190
  return failPlanning(error)
129
191
  }
130
- configuration = planned.next
131
- context.executionState = configuration
192
+ context.executionState = planned.next
132
193
  if (planned.microsteps.length === 0) {
133
194
  if (acknowledged) {
134
- context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: current })
195
+ context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: before })
135
196
  }
136
- return loop
197
+ continue
137
198
  }
138
199
 
139
200
  const next = executionPlan.snapshot(planned.next)
140
- const beforeCommit = planned.commands.length === 0
141
- ? undefined
142
- : CommandRuntime.runCommands(planned.commands, context.scope)
143
- const afterCommit = planned.emittedEvents.length === 0
144
- ? undefined
145
- : CommandRuntime.runEmittedEvents(
146
- planned.emittedEvents,
147
- liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, context.scope)
148
- )
149
- const commit = (): Effect.Effect<void> | undefined => {
150
- const notification = context.commit(next)
151
- current = next
152
- return notification
201
+ if (planned.commands.length > 0 || planned.emittedEvents.length > 0 || planned.done) {
202
+ return continueEffectful(context, acknowledged, before, planned, next)
153
203
  }
154
- const continueAfterCommit = (): Effect.Effect<Option.Option<any>, any, any> => {
155
- const continued = Effect.suspend(() => {
204
+ const notification = context.commit(next)
205
+ if (notification !== undefined) {
206
+ return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => {
156
207
  if (acknowledged) {
157
208
  context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next })
158
209
  }
159
- return planned.done ? Effect.succeed(Option.some(planned.output)) : loop
160
- })
161
- return afterCommit === undefined ? continued : afterCommit.pipe(Effect.andThen(continued))
210
+ return loop(context)
211
+ }))))
162
212
  }
163
- const commitAndContinue = (): Effect.Effect<Option.Option<any>, any, any> => {
164
- const notification = commit()
165
- const continued = continueAfterCommit()
166
- const effect = notification === undefined ? continued : notification.pipe(Effect.andThen(continued))
167
- return notification === undefined && afterCommit === undefined
168
- ? effect
169
- : context.runAfterChanges(effect)
213
+ if (acknowledged) {
214
+ context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next })
170
215
  }
216
+ }
217
+ }
171
218
 
172
- if (beforeCommit === undefined) {
173
- return commitAndContinue()
219
+ return {
220
+ run: (context) =>
221
+ internalRuntimeProtocol.provideMachineRuntime(initialOutput(context) ?? loop(context), context.scope),
222
+ runSync: (context, message) => {
223
+ // A machine resumed in a final state reports its output instead; the
224
+ // message stays in flight, so termination settles it as stopped.
225
+ const output = initialOutput(context)
226
+ if (output !== undefined) {
227
+ context.beginMessage(message)
174
228
  }
175
- return context.runAfterChanges(
176
- beforeCommit.pipe(Effect.andThen(Effect.suspend(commitAndContinue)))
177
- )
178
- })
179
- return internalRuntimeProtocol.provideMachineRuntime(loop, context.scope)
229
+ const remaining = output ?? drainSync(context, message)
230
+ return remaining === undefined
231
+ ? undefined
232
+ : internalRuntimeProtocol.provideMachineRuntime(remaining, context.scope)
233
+ }
180
234
  }
181
235
  }
182
236
 
@@ -436,12 +490,9 @@ const makeProcessLogic = (
436
490
  childless: !hasInvokes,
437
491
  ...(entry._tag === "Initial" ? { initial: makeInitial } : {}),
438
492
  ...(makeCompiledInitial === undefined ? {} : { initialSync: makeCompiledInitial }),
439
- drain: {
440
- _tag: "Owned",
441
- run: hasInvokes
442
- ? makeInvokingCompiledDrain(machine, entry._tag === "Resume")
443
- : makeChildlessCompiledDrain(machine, entry._tag === "Resume")
444
- }
493
+ drain: hasInvokes
494
+ ? { _tag: "Owned", run: makeInvokingCompiledDrain(machine, entry._tag === "Resume") }
495
+ : { _tag: "Owned", ...makeChildlessCompiledDrain(machine, entry._tag === "Resume") }
445
496
  },
446
497
  initial: (scope) =>
447
498
  entry._tag === "Resume"
@@ -8,6 +8,7 @@ import * as Exit from "effect/Exit"
8
8
  import * as Fiber from "effect/Fiber"
9
9
  import * as Option from "effect/Option"
10
10
  import * as PubSub from "effect/PubSub"
11
+ import type { SchedulerDispatcher } from "effect/Scheduler"
11
12
  import * as Stream from "effect/Stream"
12
13
  import type * as Take from "effect/Take"
13
14
  import type { Inspection } from "../../Machine.js"
@@ -54,6 +55,7 @@ import {
54
55
  publishInspectedSent,
55
56
  type RuntimeSnapshot,
56
57
  sendMachineTarget,
58
+ snapshotObserver,
57
59
  type StartInternalOptions,
58
60
  type StartProcess,
59
61
  stopAcknowledgedMessage,
@@ -95,6 +97,13 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
95
97
  ): Effect.Effect<AcknowledgedDelivery<unknown>, unknown | StoppedError> {
96
98
  return this.sendAcknowledgedEffect(event)
97
99
  }
100
+ [snapshotObserver](observer: () => void): () => void {
101
+ const observers = this.snapshotObservers ??= new Set()
102
+ observers.add(observer)
103
+ return () => {
104
+ observers.delete(observer)
105
+ }
106
+ }
98
107
 
99
108
  private readonly mailbox: CompactProcessMailbox<unknown> = {
100
109
  items: undefined,
@@ -121,6 +130,8 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
121
130
  private worker: Fiber.Fiber<any, never> | undefined
122
131
  private interruptRequested = false
123
132
  private offerRevision = 0
133
+ private snapshotObservers: Set<() => void> | undefined
134
+ private changesFlushScheduled = false
124
135
  private inFlightMessage: ProcessMessage<unknown> | undefined
125
136
  private readonly externalEmissions: EmissionRuntime | undefined
126
137
  private emissionsPubSub: LazyEmissions
@@ -419,7 +430,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
419
430
  // raised events, and eventless transitions. If it is known active and
420
431
  // neither startup hooks nor emitted work queued an event, there is no
421
432
  // first drain to perform. Future sends observe an idle run state and
422
- // schedule the ordinary compiled worker.
433
+ // start the ordinary compiled worker.
423
434
  if (
424
435
  initialized.done === false && self.execution.childless &&
425
436
  self.lifecycle === "Active" && self.mailbox.items === undefined
@@ -562,44 +573,88 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
562
573
 
563
574
  private offerMessage(message: ProcessMessage<unknown>): Effect.Effect<void, StoppedError> {
564
575
  return Effect.uninterruptible(
565
- Effect.suspend(() => {
576
+ Effect.withFiber((fiber) => {
566
577
  if (this.mailbox.closed || this.lifecycle !== "Active") {
567
578
  return Effect.fail(new StoppedError())
568
579
  }
569
- offerCompactMailbox(this.mailbox, message)
570
580
  const inspector = this.inspector
571
581
  const subject = this.inspectionSubject
572
582
  if (inspector !== undefined && subject !== undefined) publishInspectedSent(inspector, subject, message)
573
583
  this.offerRevision += 1
574
- if (this.runState === "Draining") {
584
+ // Initialization drains whatever it queued once it finishes, and an
585
+ // idle machine has an empty mailbox, so it receives the message directly.
586
+ const drain = this.execution.drain
587
+ const context = this.compiledContext
588
+ const runSync = this.runState === "Idle" && context !== undefined && drain._tag === "Owned"
589
+ ? drain.runSync
590
+ : undefined
591
+ if (runSync === undefined) {
592
+ offerCompactMailbox(this.mailbox, message)
593
+ }
594
+ if (this.runState !== "Idle") {
575
595
  return Effect.void
576
596
  }
597
+ // An idle machine drains in the sender's turn, so a transition that
598
+ // completes synchronously is committed before `send` returns. Sends
599
+ // that arrive while draining only enqueue.
577
600
  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
- )
601
+ if (runSync !== undefined) {
602
+ let remaining: Effect.Effect<Option.Option<unknown>, unknown, unknown> | undefined
603
+ try {
604
+ remaining = runSync(context!, message)
605
+ } catch (error) {
606
+ remaining = Effect.die(error)
607
+ }
608
+ // Snapshot observers may stop the machine while it drains.
609
+ if (remaining !== undefined || this.hasTerminationRequest()) {
610
+ return this.startWorker(remaining)
611
+ }
612
+ this.runState = "Idle"
613
+ this.scheduleChangesFlush(fiber.currentDispatcher)
614
+ return Effect.void
615
+ }
616
+ return this.startWorker(undefined)
599
617
  })
600
618
  )
601
619
  }
602
620
 
621
+ /**
622
+ * Starts the worker immediately, so it runs in the sender's turn until its
623
+ * first asynchronous boundary. `first` replaces the first drain pass when the
624
+ * sender has already drained synchronously up to effectful work.
625
+ */
626
+ private startWorker(
627
+ first: Effect.Effect<Option.Option<unknown>, unknown, unknown> | undefined
628
+ ): Effect.Effect<void> {
629
+ const drain = Effect.provideContext(this.drainRuntime(first), this.services)
630
+ const fork = this.options.detached === true
631
+ ? Effect.forkDetach(drain, { startImmediately: true })
632
+ : Effect.forkChild(drain, { startImmediately: true })
633
+ return fork.pipe(
634
+ Effect.flatMap((fiber) =>
635
+ Effect.sync(() => {
636
+ // A drain that settled before the fork returned has already
637
+ // released its worker slot and must not be recorded as running.
638
+ if (fiber.pollUnsafe() === undefined) {
639
+ this.worker = fiber
640
+ }
641
+ if (!this.interruptRequested) {
642
+ return false
643
+ }
644
+ this.interruptRequested = false
645
+ return true
646
+ }).pipe(
647
+ // The worker started in the sender's turn and may be waiting for
648
+ // the sender to finish, such as an invocation its transition
649
+ // interrupts, so the sender must not wait for the interruption.
650
+ // Whoever requested the stop already awaits completion.
651
+ Effect.flatMap((interrupt) => interrupt ? Effect.forkDetach(this.interruptAndFinish(fiber)) : Effect.void)
652
+ )
653
+ ),
654
+ Effect.asVoid
655
+ )
656
+ }
657
+
603
658
  private stopEffect(): Effect.Effect<void> {
604
659
  return Effect.suspend(() => {
605
660
  if (this.lifecycle === "Completed") {
@@ -627,10 +682,14 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
627
682
  this.options.onStop !== undefined ||
628
683
  this.inspector !== undefined ||
629
684
  this.current.changes !== undefined ||
685
+ this.externalEmissions !== undefined ||
686
+ (this.emissionsPubSub !== undefined && this.emissionsPubSub !== EmissionsClosed) ||
630
687
  this.current.terminalizing || this.current.snapshot.status !== "active"
631
688
  ) {
632
689
  return false
633
690
  }
691
+ // No emission stream was ever observed, so closing needs no PubSub shutdown.
692
+ this.emissionsPubSub = EmissionsClosed
634
693
  const snapshot = { status: "stopped" as const, state: this.current.snapshot.state }
635
694
  this.lifecycle = "TerminationRequested"
636
695
  this.termination = { _tag: "Stopped" }
@@ -642,6 +701,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
642
701
  changes: undefined,
643
702
  snapshot
644
703
  }
704
+ this.notifySnapshotObservers()
645
705
  stopAcknowledgedMessage(this.inFlightMessage)
646
706
  this.inFlightMessage = undefined
647
707
  this.interruptRequested = false
@@ -700,11 +760,14 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
700
760
  return stopped
701
761
  }
702
762
 
703
- private drainRuntime(): Effect.Effect<void, never, any> {
763
+ private drainRuntime(
764
+ first?: Effect.Effect<Option.Option<unknown>, unknown, unknown>
765
+ ): Effect.Effect<void, never, any> {
704
766
  const self = this
705
767
  return Effect.uninterruptibleMask((restore) =>
706
768
  Effect.gen(function*() {
707
769
  let observedRevision = self.offerRevision
770
+ let pending = first
708
771
  while (true) {
709
772
  if (self.hasTerminationRequest()) {
710
773
  return yield* self.finishRequestedTermination()
@@ -712,6 +775,11 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
712
775
 
713
776
  const exit = yield* restore(
714
777
  Effect.suspend(() => {
778
+ if (pending !== undefined) {
779
+ const continued = pending
780
+ pending = undefined
781
+ return continued
782
+ }
715
783
  const drain = self.execution.drain
716
784
  return drain._tag === "Process"
717
785
  ? drain.run(self.processContext!)
@@ -928,6 +996,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
928
996
  changes: this.current.changes
929
997
  }
930
998
  this.current = versioned
999
+ this.notifySnapshotObservers()
931
1000
  return this.publishSnapshot(versioned).pipe(
932
1001
  Effect.flatMap((published) => this.completeChanges(published)),
933
1002
  Effect.asVoid
@@ -947,6 +1016,10 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
947
1016
  return message
948
1017
  }
949
1018
 
1019
+ beginCompiledMessage(message: ProcessMessage<unknown>): void {
1020
+ this.inFlightMessage = isAcknowledgedMessage(message) ? message : undefined
1021
+ }
1022
+
950
1023
  completeCompiledMessage(delivery: AcknowledgedDelivery<unknown>): void {
951
1024
  succeedAcknowledgedMessage(this.inFlightMessage, delivery)
952
1025
  this.inFlightMessage = undefined
@@ -993,11 +1066,36 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
993
1066
  }
994
1067
  }
995
1068
  }
1069
+ this.notifySnapshotObservers()
996
1070
  return this.options.onSnapshot === undefined
997
1071
  ? undefined
998
1072
  : notifyActiveSnapshot(this.options.onSnapshot, activeSnapshot)
999
1073
  }
1000
1074
 
1075
+ private notifySnapshotObservers(): void {
1076
+ if (this.snapshotObservers !== undefined) {
1077
+ for (const observer of this.snapshotObservers) {
1078
+ observer()
1079
+ }
1080
+ }
1081
+ }
1082
+
1083
+ /**
1084
+ * Publishes the changes committed by consecutive synchronous drains once the
1085
+ * sender yields, so a burst of sends reaches `changes` subscribers together,
1086
+ * as `Queue` releases its takers. Any earlier flush leaves nothing to publish.
1087
+ */
1088
+ private scheduleChangesFlush(dispatcher: SchedulerDispatcher): void {
1089
+ if (this.changesFlushScheduled || this.current.pendingChanges === undefined) {
1090
+ return
1091
+ }
1092
+ this.changesFlushScheduled = true
1093
+ dispatcher.scheduleTask(() => {
1094
+ this.changesFlushScheduled = false
1095
+ this.flushPendingChanges()
1096
+ }, 0)
1097
+ }
1098
+
1001
1099
  flushPendingChanges(): void {
1002
1100
  const current = this.current
1003
1101
  const pendingChanges = current?.pendingChanges
@@ -1103,6 +1201,10 @@ class CompiledProcessContextImpl implements CompiledProcessContext<unknown, unkn
1103
1201
  return this.process.pollCompiledMessage()
1104
1202
  }
1105
1203
 
1204
+ beginMessage(message: ProcessMessage<unknown>): void {
1205
+ this.process.beginCompiledMessage(message)
1206
+ }
1207
+
1106
1208
  state(): unknown {
1107
1209
  return this.process.compiledState()
1108
1210
  }
@@ -7,7 +7,6 @@ import * as Exit from "effect/Exit"
7
7
  import * as Fiber from "effect/Fiber"
8
8
  import * as Option from "effect/Option"
9
9
  import * as PubSub from "effect/PubSub"
10
- import * as Queue from "effect/Queue"
11
10
  import * as Stream from "effect/Stream"
12
11
  import * as SynchronizedRef from "effect/SynchronizedRef"
13
12
  import type * as Take from "effect/Take"
@@ -21,6 +20,7 @@ import {
21
20
  acknowledgedSend,
22
21
  childlessRuntime,
23
22
  classifyOutcome,
23
+ closeProcessMailbox,
24
24
  executionIsChildless,
25
25
  failAcknowledgedMessage,
26
26
  type InspectedOffer,
@@ -31,18 +31,22 @@ import {
31
31
  makeChildRuntime,
32
32
  makeEmissionRuntime,
33
33
  makeInspectedMessage,
34
+ makeProcessMailbox,
34
35
  messageCausation,
35
36
  messageEvent,
36
37
  noCausation,
37
38
  noInspectInitial,
38
39
  noParentSend,
39
40
  notifyActiveSnapshot,
41
+ offerProcessMailbox,
42
+ pollCompactMailbox,
40
43
  type ProcessAddress,
41
44
  type ProcessContext,
42
45
  type ProcessLogic,
43
46
  type ProcessMessage,
44
47
  type ProcessScope,
45
48
  publishInspectedSent,
49
+ receiveProcessMailbox,
46
50
  type RuntimeSnapshot,
47
51
  sendMachineTarget,
48
52
  type StartInternalOptions,
@@ -87,7 +91,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
87
91
  : { ...options.activity, sessionId }
88
92
  let initialEntryPaths: ReadonlyArray<string> | undefined
89
93
  let initialMicrosteps: ReadonlyArray<unknown> | undefined
90
- const queue = yield* Queue.unbounded<ProcessMessage<Event>>()
94
+ const mailbox = makeProcessMailbox<Event>()
91
95
  const emissions = options.emissions ?? makeEmissionRuntime()
92
96
  const termination = yield* Deferred.make<ProcessTermination>()
93
97
  const done = yield* Deferred.make<Output, Error | StoppedError>()
@@ -95,9 +99,12 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
95
99
  let initializing = true
96
100
  let inFlightMessage: ProcessMessage<Event> | undefined
97
101
  const requestStop = Deferred.succeed(termination, { _tag: "Stopped" }).pipe(Effect.asVoid)
98
- const offerDirect = (message: ProcessMessage<Event>): Effect.Effect<void, StoppedError> =>
99
- Queue.offer(queue, message).pipe(
100
- Effect.flatMap((accepted) => accepted ? Effect.void : Effect.fail(new StoppedError()))
102
+ const offerDirect = (
103
+ message: ProcessMessage<Event>,
104
+ onAccepted?: () => void
105
+ ): Effect.Effect<void, StoppedError> =>
106
+ Effect.suspend(() =>
107
+ offerProcessMailbox(mailbox, message, onAccepted) ? Effect.void : Effect.fail(new StoppedError())
101
108
  )
102
109
  const offerInspected: InspectedOffer<Event> | undefined = inspector === undefined ? undefined : (
103
110
  event,
@@ -111,9 +118,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
111
118
  : deferred === undefined
112
119
  ? event
113
120
  : { [AcknowledgedMessageTypeId]: true as const, event, deferred }
114
- return offerDirect(message).pipe(
115
- Effect.tap(() => Effect.sync(() => publishInspectedSent(inspector, subject!, message)))
116
- )
121
+ return offerDirect(message, () => publishInspectedSent(inspector, subject!, message))
117
122
  })
118
123
  const sendAcknowledged:
119
124
  | ((event: Event) => Effect.Effect<AcknowledgedDelivery<State>, Error | StoppedError>)
@@ -480,14 +485,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
480
485
  ))
481
486
  )
482
487
  return Effect.uninterruptible(
483
- Effect.sync(() => {
484
- while (true) {
485
- const pending = Queue.takeUnsafe(queue)
486
- if (pending === undefined || Exit.isFailure(pending)) break
487
- stopAcknowledgedMessage(pending.value)
488
- }
489
- }).pipe(
490
- Effect.andThen(Queue.shutdown(queue)),
488
+ Effect.sync(() => closeProcessMailbox(mailbox)).pipe(
491
489
  Effect.andThen(closeChildren(exit)),
492
490
  Effect.andThen(setAndPublishSnapshot(snapshot)),
493
491
  Effect.andThen(closeEmissionsAndInspect),
@@ -563,14 +561,14 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
563
561
  "receiveMessage" | "pollMessage" | "completeMessage"
564
562
  >
565
563
  | undefined = logic.execution?._tag !== "Compiled" ? undefined : {
566
- receiveMessage: Queue.take(queue).pipe(
564
+ receiveMessage: receiveProcessMailbox(mailbox).pipe(
567
565
  Effect.tap((message) =>
568
566
  Effect.sync(() => {
569
567
  inFlightMessage = isAcknowledgedMessage(message) ? message : undefined
570
568
  })
571
569
  )
572
570
  ),
573
- pollMessage: Queue.poll(queue).pipe(
571
+ pollMessage: Effect.sync(() => pollCompactMailbox(mailbox)).pipe(
574
572
  Effect.tap((message) =>
575
573
  Effect.sync(() => {
576
574
  if (Option.isSome(message)) {
@@ -585,8 +583,8 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
585
583
  }
586
584
  }
587
585
  const receive = inspector === undefined || logic.execution?._tag === "Compiled"
588
- ? Queue.take(queue).pipe(Effect.map(messageEvent))
589
- : Queue.take(queue).pipe(
586
+ ? receiveProcessMailbox(mailbox).pipe(Effect.map(messageEvent))
587
+ : receiveProcessMailbox(mailbox).pipe(
590
588
  Effect.tap((message) =>
591
589
  Effect.sync(() => {
592
590
  inFlightMessage = message
@@ -595,8 +593,8 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
595
593
  Effect.map(messageEvent)
596
594
  )
597
595
  const poll = inspector === undefined || logic.execution?._tag === "Compiled"
598
- ? Queue.poll(queue).pipe(Effect.map(Option.map(messageEvent)))
599
- : Queue.poll(queue).pipe(
596
+ ? Effect.sync(() => pollCompactMailbox(mailbox)).pipe(Effect.map(Option.map(messageEvent)))
597
+ : Effect.sync(() => pollCompactMailbox(mailbox)).pipe(
600
598
  Effect.tap((message) =>
601
599
  Effect.sync(() => {
602
600
  if (Option.isSome(message)) inFlightMessage = message.value