@systemfsoftware/effect-daemon-spec 5.0.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Array, Cause, Clock, Context, Deferred, Duration, Effect, Exit, Fiber, HashMap, Layer, Match, Number as Number$1, Option, Predicate, PubSub, Queue, Ref, Result, Schema, Scope } from "effect";
3
2
  import { Handle, Sandwich, Workflow } from "@systemfsoftware/effect-cell-types";
4
- import { dual } from "effect/Function";
3
+ import { Array, Cause, Clock, Context, Deferred, Duration, Effect, Exit, Fiber, HashMap, Layer, Match, Number as Number$1, Option, Predicate, PubSub, Queue, Ref, Result, Schema, Scope } from "effect";
4
+ import * as Result$1 from "effect/Result";
5
+ import { absurd, dual } from "effect/Function";
5
6
  import * as Stream from "effect/Stream";
6
7
  import { Prototype } from "effect/Pipeable";
7
8
  //#region src/kernel/SupervisionLimits.schema.ts
@@ -54,6 +55,99 @@ const ChildId = Schema.String;
54
55
  const RequestId = Schema.String;
55
56
  Schema.decodeResult(Ceiling);
56
57
  //#endregion
58
+ //#region src/kernel/TerminationReport.schema.ts
59
+ /**
60
+ * What a medium can say about why a child died (R16): a fiber supplies a cause, a process
61
+ * supplies an exit status and signal, and a remote runner's death is inferred. No event
62
+ * claims a level its medium cannot supply — the medium declares which one it reports, and
63
+ * the kernel assumes nothing beyond that declaration.
64
+ */
65
+ const CauseReport = Schema.TaggedStruct("CauseReport", { cause: Schema.String });
66
+ const ExitReport = Schema.TaggedStruct("ExitReport", {
67
+ code: Schema.Int,
68
+ signal: Schema.String
69
+ });
70
+ const InferredReport = Schema.TaggedStruct("InferredReport", { failedProbes: ProbeThreshold });
71
+ const DeadlineMissedReport = Schema.TaggedStruct("DeadlineMissed", { waitedMillis: Schema.Int });
72
+ const FailureReport = Schema.Union([
73
+ CauseReport,
74
+ ExitReport,
75
+ InferredReport,
76
+ DeadlineMissedReport
77
+ ]);
78
+ const NormalTermination = Schema.TaggedStruct("Normal", {});
79
+ const ShutdownTermination = Schema.TaggedStruct("Shutdown", {});
80
+ const AbnormalTermination = Schema.TaggedStruct("Abnormal", { report: FailureReport });
81
+ const TerminationReason = Schema.Union([
82
+ NormalTermination,
83
+ ShutdownTermination,
84
+ AbnormalTermination
85
+ ]);
86
+ /**
87
+ * Why the supervisor itself is terminating: a shutdown something asked of it, or a
88
+ * give-up after its children terminated more often than its intensity allows. The
89
+ * decision and command data carry this, so the shell never infers which one it is.
90
+ * A give-up names the child incarnation whose termination exhausted the intensity.
91
+ */
92
+ const RequestedExit = Schema.TaggedStruct("RequestedExit", {});
93
+ const IntensityExceededExit = Schema.TaggedStruct("IntensityExceededExit", {
94
+ childId: ChildId,
95
+ generation: Generation
96
+ });
97
+ const SupervisorExit = Schema.Union([RequestedExit, IntensityExceededExit]);
98
+ const abnormalReasonOfCause = (cause) => ({
99
+ _tag: "Abnormal",
100
+ report: {
101
+ _tag: "CauseReport",
102
+ cause: Cause.pretty(cause)
103
+ }
104
+ });
105
+ const terminationReasonOfCause = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => abnormalReasonOfCause(cause));
106
+ //#endregion
107
+ //#region src/Supervisor/ChildExitDecision.schema.ts
108
+ const ChildExitTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/ChildExitDecision");
109
+ /** The child ended on its own success. */
110
+ var NormalExit = class extends Schema.TaggedClass()("Normal", {}) {
111
+ [ChildExitTypeId] = ChildExitTypeId;
112
+ };
113
+ /** The child was interrupted — an owned shutdown, or one it raised itself. */
114
+ var ShutdownExit = class extends Schema.TaggedClass()("Shutdown", {}) {
115
+ [ChildExitTypeId] = ChildExitTypeId;
116
+ };
117
+ /** The child failed with something other than an interruption. */
118
+ var AbnormalExit = class extends Schema.TaggedClass()("Abnormal", {}) {
119
+ [ChildExitTypeId] = ChildExitTypeId;
120
+ };
121
+ const ChildExitDecision = Schema.Union([
122
+ NormalExit,
123
+ ShutdownExit,
124
+ AbnormalExit
125
+ ]);
126
+ const NORMAL = { _tag: "Normal" };
127
+ const SHUTDOWN = { _tag: "Shutdown" };
128
+ const causeOf = (exit) => exit.pipe(Exit.getCause, Option.getOrElse(() => Cause.empty));
129
+ const terminationReasonOf = (bearing) => Match.value(bearing.decision).pipe(Match.tag("Normal", () => NORMAL), Match.tag("Shutdown", () => SHUTDOWN), Match.tag("Abnormal", () => bearing.exit.pipe(causeOf, abnormalReasonOfCause)), Match.exhaustive);
130
+ //#endregion
131
+ //#region src/Supervisor/classify-child-exit.workflow.ts
132
+ var ClassifyChildExit = class extends Schema.TaggedClass()("ClassifyChildExit", {
133
+ stopping: Schema.Boolean,
134
+ exit: Schema.Exit(Schema.Void, Schema.Unknown, Schema.Unknown)
135
+ }) {
136
+ static [Workflow.InstrumentationBrand] = {};
137
+ };
138
+ const failureOf = (cause) => Match.value(Cause.hasInterruptsOnly(cause)).pipe(Match.when(true, () => ShutdownExit.make()), Match.when(false, () => AbnormalExit.make()), Match.exhaustive);
139
+ const endedOf = (exit) => Exit.match(exit, {
140
+ onSuccess: () => NormalExit.make(),
141
+ onFailure: failureOf
142
+ });
143
+ const decisionOf$1 = (command) => Match.value(command.stopping).pipe(Match.when(true, () => ShutdownExit.make()), Match.when(false, () => endedOf(command.exit)), Match.exhaustive);
144
+ const classifyChildExit = Workflow.make({
145
+ command: ClassifyChildExit,
146
+ decision: ChildExitDecision,
147
+ error: Schema.Never,
148
+ decide: (command) => Result$1.succeed(decisionOf$1(command))
149
+ });
150
+ //#endregion
57
151
  //#region src/kernel/SupervisorPolicy.schema.ts
58
152
  const RestartStrategy = Schema.Literals([
59
153
  "one_for_one",
@@ -149,47 +243,26 @@ Schema.Struct({
149
243
  childSeeds: Schema.Array(ChildSeed)
150
244
  });
151
245
  const SupervisionPolicy = Schema.Struct(policyFields).check(Schema.makeFilter(policyIsDecodable, { message: POLICY_REFUSAL_MESSAGE }));
152
- //#endregion
153
- //#region src/kernel/TerminationReport.schema.ts
154
- /**
155
- * What a medium can say about why a child died (R16): a fiber supplies a cause, a process
156
- * supplies an exit status and signal, and a remote runner's death is inferred. No event
157
- * claims a level its medium cannot supply — the medium declares which one it reports, and
158
- * the kernel assumes nothing beyond that declaration.
159
- */
160
- const CauseReport = Schema.TaggedStruct("CauseReport", { cause: Schema.String });
161
- const ExitReport = Schema.TaggedStruct("ExitReport", {
162
- code: Schema.Int,
163
- signal: Schema.String
164
- });
165
- const InferredReport = Schema.TaggedStruct("InferredReport", { failedProbes: ProbeThreshold });
166
- const DeadlineMissedReport = Schema.TaggedStruct("DeadlineMissed", { waitedMillis: Schema.Int });
167
- const FailureReport = Schema.Union([
168
- CauseReport,
169
- ExitReport,
170
- InferredReport,
171
- DeadlineMissedReport
172
- ]);
173
- const NormalTermination = Schema.TaggedStruct("Normal", {});
174
- const ShutdownTermination = Schema.TaggedStruct("Shutdown", {});
175
- const AbnormalTermination = Schema.TaggedStruct("Abnormal", { report: FailureReport });
176
- const TerminationReason = Schema.Union([
177
- NormalTermination,
178
- ShutdownTermination,
179
- AbnormalTermination
180
- ]);
181
- /**
182
- * Why the supervisor itself is terminating: a shutdown something asked of it, or a
183
- * give-up after its children terminated more often than its intensity allows. The
184
- * decision and command data carry this, so the shell never infers which one it is.
185
- * A give-up names the child incarnation whose termination exhausted the intensity.
186
- */
187
- const RequestedExit = Schema.TaggedStruct("RequestedExit", {});
188
- const IntensityExceededExit = Schema.TaggedStruct("IntensityExceededExit", {
189
- childId: ChildId,
190
- generation: Generation
246
+ const supervisionPolicyOf = (parts) => ({
247
+ strategy: parts.strategy,
248
+ intensity: parts.intensity,
249
+ periodMillis: parts.periodMillis,
250
+ autoShutdown: parts.autoShutdown,
251
+ coolDown: Match.value(parts.coolDownMillis).pipe(Match.when(void 0, () => ({ _tag: "NoCoolDown" })), Match.orElse((millis) => ({
252
+ _tag: "CoolDownAfter",
253
+ millis
254
+ }))),
255
+ backoff: parts.backoff,
256
+ dynamic: parts.dynamic,
257
+ livenessTickMillis: parts.livenessTickMillis,
258
+ childDeclarations: parts.declarations
191
259
  });
192
- const SupervisorExit = Schema.Union([RequestedExit, IntensityExceededExit]);
260
+ const workerShutdown = {
261
+ _tag: "Graceful",
262
+ millis: 5e3
263
+ };
264
+ const supervisorShutdown = { _tag: "Infinity" };
265
+ const childShutdownOf = (nested) => Match.value(nested).pipe(Match.when(true, () => supervisorShutdown), Match.when(false, () => workerShutdown), Match.exhaustive);
193
266
  //#endregion
194
267
  //#region src/Supervisor/MediumDeclaration.schema.ts
195
268
  /**
@@ -277,37 +350,29 @@ var FiberMedium_exports = /* @__PURE__ */ __exportAll({
277
350
  const readyOnStart = (program) => (ready) => Effect.andThen(ready, program);
278
351
  const fiberPort = MediumPort("FiberMedium");
279
352
  const FiberStartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/FiberMedium/Started");
280
- const fiberStarted = (fiber, scope, ready) => ({
353
+ const fiberStarted = (fiber, ready) => ({
281
354
  [StartedTypeId]: StartedTypeId,
282
355
  [FiberStartedTypeId]: FiberStartedTypeId,
283
356
  fiber,
284
- ready,
285
- scope
357
+ ready
286
358
  });
287
359
  const isFiberStarted = (evidence) => FiberStartedTypeId in evidence;
288
360
  const fiberOf = (evidence) => Option.liftPredicate(evidence, isFiberStarted);
289
- const normalTermination = { _tag: "Normal" };
290
361
  const shutdownTermination = { _tag: "Shutdown" };
291
- const abnormalOf = (cause) => ({
292
- _tag: "Abnormal",
293
- report: {
294
- _tag: "CauseReport",
295
- cause: Cause.pretty(cause)
296
- }
362
+ const decisionOf = (exit) => Result.match(classifyChildExit(new ClassifyChildExit({
363
+ stopping: false,
364
+ exit
365
+ })), {
366
+ onFailure: (error) => absurd(error),
367
+ onSuccess: (decision) => decision
297
368
  });
298
- const terminationOf$1 = (exit) => Exit.match(exit, {
299
- onSuccess: () => normalTermination,
300
- onFailure: (cause) => Cause.hasInterruptsOnly(cause) ? shutdownTermination : abnormalOf(cause)
369
+ const terminationOf$1 = (exit) => terminationReasonOf({
370
+ decision: decisionOf(exit),
371
+ exit
301
372
  });
302
- const closedChild = (self) => Scope.close(self.scope, Exit.void);
303
373
  const forcedChild = (self) => Fiber.interrupt(self.fiber);
304
- /**
305
- * OTP's timed shutdown: the signal (interruption) goes out at once, and the window
306
- * bounds only how long the stop waits for the child's finalizers before closing its
307
- * scope.
308
- */
309
- const signalledWithin = (self, millis) => Effect.andThen(Effect.timeoutOption(forcedChild(self), Duration.millis(millis)), closedChild(self));
310
- const stopOf = (self, mode) => Match.value(mode).pipe(Match.tag("Brutal", () => Effect.andThen(forcedChild(self), closedChild(self))), Match.tag("Graceful", (graceful) => signalledWithin(self, graceful.millis)), Match.tag("Infinity", () => Effect.andThen(forcedChild(self), closedChild(self))), Match.exhaustive);
374
+ const signalledWithin = (self, millis) => Effect.asVoid(Effect.timeoutOption(forcedChild(self), Duration.millis(millis)));
375
+ const stopOf = (self, mode) => Match.value(mode).pipe(Match.tag("Brutal", () => forcedChild(self)), Match.tag("Graceful", (graceful) => signalledWithin(self, graceful.millis)), Match.tag("Infinity", () => forcedChild(self)), Match.exhaustive);
311
376
  const failureCauseOf = (evidence) => Option.map(fiberOf(evidence), (self) => Effect.map(Fiber.await(self.fiber), Exit.getCause));
312
377
  const mediumFor = () => make$1({
313
378
  declaration: {
@@ -318,7 +383,7 @@ const mediumFor = () => make$1({
318
383
  const scope = yield* Effect.scope;
319
384
  const signalled = yield* Deferred.make();
320
385
  const fiber = yield* Effect.forkIn(program(Deferred.succeed(signalled, void 0)), scope);
321
- return fiberStarted(fiber, scope, Deferred.await(signalled));
386
+ return fiberStarted(fiber, Deferred.await(signalled));
322
387
  }),
323
388
  report: (evidence) => Option.match(fiberOf(evidence), {
324
389
  onNone: () => Effect.succeed(shutdownTermination),
@@ -336,44 +401,47 @@ const mediumFor = () => make$1({
336
401
  const medium = mediumFor();
337
402
  //#endregion
338
403
  //#region src/Supervisor/bound-child.ts
339
- const rendered = (failure) => ({
340
- _tag: "Abnormal",
341
- report: {
342
- _tag: "CauseReport",
343
- cause: Cause.pretty(Cause.fail(failure))
344
- }
345
- });
346
- const reasonOf = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => ({
347
- _tag: "Abnormal",
348
- report: {
349
- _tag: "CauseReport",
350
- cause: Cause.pretty(cause)
351
- }
352
- }));
404
+ const rendered = (failure) => abnormalReasonOfCause(Cause.fail(failure));
353
405
  const startOf = (program, medium, context) => Effect.gen(function* () {
354
406
  const parent = yield* Effect.scope;
355
407
  const child = yield* Scope.fork(parent);
356
408
  const scoped = Context.add(context, Scope.Scope, child);
357
409
  const outcome = yield* Effect.exit(Effect.setContext(Effect.mapError(medium.start(program), rendered), scoped));
358
410
  return yield* Exit.match(outcome, {
359
- onSuccess: (evidence) => Effect.succeed(evidence),
360
- onFailure: (cause) => Effect.andThen(Scope.close(child, Exit.void), Effect.fail(reasonOf(cause)))
411
+ onSuccess: (evidence) => Effect.succeed({
412
+ evidence,
413
+ scope: child
414
+ }),
415
+ onFailure: (cause) => Effect.andThen(Scope.close(child, Exit.void), Effect.fail(terminationReasonOfCause(cause)))
361
416
  });
362
417
  });
363
418
  const bind = (program, medium, context) => ({
364
419
  start: startOf(program, medium, context),
365
- report: (evidence) => Effect.setContext(medium.report(evidence), context),
366
- probe: (evidence) => Effect.setContext(medium.probe(evidence), context),
367
- stop: (evidence, mode) => Effect.setContext(medium.stop(evidence, mode), context)
420
+ report: (incarnation) => Effect.setContext(medium.report(incarnation.evidence), context),
421
+ probe: (incarnation) => Effect.setContext(medium.probe(incarnation.evidence), context),
422
+ stop: (incarnation, mode) => Effect.ensuring(Effect.setContext(medium.stop(incarnation.evidence, mode), context), Scope.close(incarnation.scope, Exit.void))
368
423
  });
369
- /**
370
- * Binds a program to the medium that interprets it, capturing the services
371
- * resolved at acquisition: the medium's own requirements are read from
372
- * `context` once, and `start` forks a fresh child scope so closing that scope
373
- * owns the child's shutdown (KTD9).
374
- */
375
424
  const Binder = { bind };
376
425
  //#endregion
426
+ //#region src/Supervisor/DynamicOutcome.schema.ts
427
+ const DynamicStartAccepted = Schema.Struct({
428
+ outcome: Schema.Literal("accepted"),
429
+ childId: ChildId,
430
+ generation: Generation
431
+ });
432
+ const DynamicStartRefused = Schema.Struct({ outcome: Schema.Literal("refused") });
433
+ const DynamicStartOutcome = Schema.Union([DynamicStartAccepted, DynamicStartRefused]);
434
+ const DynamicStopDone = Schema.Struct({ outcome: Schema.Literal("stopped") });
435
+ const DynamicStopMissed = Schema.Struct({ outcome: Schema.Literal("missed") });
436
+ const DynamicStopOutcome = Schema.Union([DynamicStopDone, DynamicStopMissed]);
437
+ Schema.Union([DynamicStartOutcome, DynamicStopOutcome]);
438
+ const outcomeOf = (reply) => Match.value(reply).pipe(Match.tag("ReplyStartAccepted", (accepted) => ({
439
+ outcome: "accepted",
440
+ childId: accepted.childId,
441
+ generation: accepted.generation
442
+ })), Match.tag("ReplyStartRefused", () => ({ outcome: "refused" })), Match.tag("ReplyStopped", () => ({ outcome: "stopped" })), Match.exhaustive);
443
+ const staleOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, () => ({ outcome: "refused" })), Match.orElse(() => ({ outcome: "missed" })));
444
+ //#endregion
377
445
  //#region src/Supervisor/running-supervisor.handle.ts
378
446
  /** Brands a running supervisor handle. */
379
447
  const TypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/RunningSupervisor");
@@ -460,13 +528,67 @@ const resolveWaiting = (replies, requestId, outcome) => Effect.flatMap(Ref.modif
460
528
  onNone: () => Effect.void,
461
529
  onSome: (waiter) => Effect.asVoid(Deferred.succeed(waiter, outcome))
462
530
  }));
463
- const staleOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, () => ({ outcome: "refused" })), Match.orElse(() => ({ outcome: "missed" })));
464
531
  const Ops = {
465
532
  resolveWaiting,
466
533
  staleOf
467
534
  };
468
535
  //#endregion
469
- //#region src/kernel/initial-supervisor-state.ts
536
+ //#region src/kernel/SupervisorState.schema.ts
537
+ const StateTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisorState");
538
+ const ChildStatus = Schema.Literals([
539
+ "starting",
540
+ "ready",
541
+ "stopping"
542
+ ]);
543
+ const ChildInstance = Schema.Struct({
544
+ childId: ChildId,
545
+ generation: Generation,
546
+ status: ChildStatus,
547
+ consecutiveRestarts: RestartCount,
548
+ probeFailures: ProbeFailures
549
+ });
550
+ const SupervisorCore = Schema.Struct({
551
+ policy: SupervisionPolicy,
552
+ children: Schema.Array(ChildInstance),
553
+ restartStamps: Schema.Array(EventTime),
554
+ nextOrdinal: Ordinal
555
+ });
556
+ const ChildStart = Schema.Struct({
557
+ childId: ChildId,
558
+ generation: Generation
559
+ });
560
+ var Running = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
561
+ [StateTypeId] = StateTypeId;
562
+ };
563
+ var Restarting = class extends Schema.TaggedClass()("Restarting", {
564
+ core: SupervisorCore,
565
+ pending: Schema.Array(ChildStart)
566
+ }) {
567
+ [StateTypeId] = StateTypeId;
568
+ };
569
+ var CoolingDown = class extends Schema.TaggedClass()("CoolingDown", {
570
+ core: SupervisorCore,
571
+ millis: PositiveMillis
572
+ }) {
573
+ [StateTypeId] = StateTypeId;
574
+ };
575
+ var ShuttingDown = class extends Schema.TaggedClass()("ShuttingDown", {
576
+ core: SupervisorCore,
577
+ reason: TerminationReason,
578
+ exit: SupervisorExit
579
+ }) {
580
+ [StateTypeId] = StateTypeId;
581
+ };
582
+ var Terminated = class extends Schema.TaggedClass()("Terminated", { reason: TerminationReason }) {
583
+ [StateTypeId] = StateTypeId;
584
+ };
585
+ const SupervisorState = Schema.Union([
586
+ Running,
587
+ Restarting,
588
+ CoolingDown,
589
+ ShuttingDown,
590
+ Terminated
591
+ ]);
470
592
  const initialStateOf = (policy) => ({
471
593
  policy,
472
594
  children: Array.map(policy.childDeclarations, (declaration) => ({
@@ -479,6 +601,28 @@ const initialStateOf = (policy) => ({
479
601
  restartStamps: [],
480
602
  nextOrdinal: 0
481
603
  });
604
+ const withCore = (state, core) => Match.value(state).pipe(Match.tag("Running", () => new Running({ core })), Match.tag("Restarting", (restarting) => new Restarting({
605
+ core,
606
+ pending: restarting.pending
607
+ })), Match.tag("CoolingDown", (cooling) => new CoolingDown({
608
+ core,
609
+ millis: cooling.millis
610
+ })), Match.tag("ShuttingDown", (shutting) => new ShuttingDown({
611
+ core,
612
+ reason: shutting.reason,
613
+ exit: shutting.exit
614
+ })), Match.tag("Terminated", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive);
615
+ const evolved = dual(2, (state, decision) => Match.value(decision).pipe(Match.tag("Stale", () => state), Match.tag("RefuseDynamicStart", () => state), Match.tag("Continue", (continued) => withCore(state, continued.core)), Match.tag("RestartChildren", (restarting) => new Restarting({
616
+ core: restarting.core,
617
+ pending: restarting.pending
618
+ })), Match.tag("StartChildren", (started) => new Running({ core: started.core })), Match.tag("CoolDown", (cooling) => new CoolingDown({
619
+ core: cooling.core,
620
+ millis: cooling.millis
621
+ })), Match.tag("StopChildren", (stopping) => new ShuttingDown({
622
+ core: stopping.core,
623
+ reason: stopping.reason,
624
+ exit: stopping.exit
625
+ })), Match.tag("Terminate", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive));
482
626
  //#endregion
483
627
  //#region src/kernel/SupervisionEvent.schema.ts
484
628
  const TimerKind = Schema.Literals([
@@ -558,10 +702,6 @@ const SupervisionEvent = Schema.Union([
558
702
  ShutdownRequested
559
703
  ]);
560
704
  //#endregion
561
- //#region src/kernel/SupervisionTypeIds.ts
562
- const DecisionTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionDecision");
563
- const StateTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisorState");
564
- //#endregion
565
705
  //#region src/kernel/SupervisorCommand.schema.ts
566
706
  const StartChild = Schema.TaggedStruct("StartChild", {
567
707
  childId: ChildId,
@@ -617,31 +757,155 @@ const SupervisorCommands = Schema.Struct({
617
757
  terminates: Schema.Array(TerminateSupervisor)
618
758
  });
619
759
  //#endregion
620
- //#region src/kernel/SupervisorState.schema.ts
621
- const ChildStatus = Schema.Literals([
622
- "starting",
623
- "ready",
624
- "stopping"
625
- ]);
626
- const ChildInstance = Schema.Struct({
627
- childId: ChildId,
628
- generation: Generation,
629
- status: ChildStatus,
630
- consecutiveRestarts: RestartCount,
631
- probeFailures: ProbeFailures
760
+ //#region src/Supervisor/SupervisorTerminated.schema.ts
761
+ const firstLine = (text) => text.split("\n")[0] ?? "";
762
+ var SupervisorTerminated = class extends Schema.TaggedError()("SupervisorTerminated", {
763
+ name: Schema.String,
764
+ reason: TerminationReason,
765
+ cause: Schema.Cause(Schema.Unknown, Schema.Unknown)
766
+ }) {
767
+ get message() {
768
+ return `Supervisor "${this.name}" terminated (${this.reason._tag}): ${firstLine(Cause.pretty(this.cause))}`;
769
+ }
770
+ };
771
+ //#endregion
772
+ //#region src/Supervisor/supervisor-commands.ts
773
+ const Steps = { runtimeOf: (acquired) => ({ acquired }) };
774
+ const stampedNow = (handle, event) => Effect.flatMap(Clock.currentTimeMillis, (now) => offerEvent(handle, {
775
+ ...event,
776
+ at: now
777
+ }));
778
+ const startedEventOf = (childId, generation) => ({
779
+ _tag: "ChildStarted",
780
+ at: 0,
781
+ childId,
782
+ generation
632
783
  });
633
- const SupervisorCore = Schema.Struct({
634
- policy: SupervisionPolicy,
635
- children: Schema.Array(ChildInstance),
636
- restartStamps: Schema.Array(EventTime),
637
- nextOrdinal: Ordinal
784
+ const readyEventOf = (childId, generation) => ({
785
+ _tag: "ChildReady",
786
+ at: 0,
787
+ childId,
788
+ generation
638
789
  });
639
- const ChildStart = Schema.Struct({
640
- childId: ChildId,
641
- generation: Generation
790
+ const terminatedEventOf = (childId, generation, reason) => ({
791
+ _tag: "ChildTerminated",
792
+ at: 0,
793
+ childId,
794
+ generation,
795
+ reason
796
+ });
797
+ const stoppedEventOf = (childId, generation) => ({
798
+ _tag: "ChildStopped",
799
+ at: 0,
800
+ childId,
801
+ generation
802
+ });
803
+ const probeEventOf = (childId, generation, alive) => ({
804
+ _tag: "ProbeResult",
805
+ at: 0,
806
+ childId,
807
+ generation,
808
+ alive
809
+ });
810
+ const timerEventOf = (kind, childId, generation) => ({
811
+ _tag: "TimerElapsed",
812
+ at: 0,
813
+ kind,
814
+ target: {
815
+ _tag: "ChildTimer",
816
+ childId,
817
+ generation
818
+ }
819
+ });
820
+ const supervisorTimerEventOf = (kind) => ({
821
+ _tag: "TimerElapsed",
822
+ at: 0,
823
+ kind,
824
+ target: { _tag: "SupervisorTimer" }
825
+ });
826
+ const evidenceKeyOf = (childId, generation) => `${childId}#${generation}`;
827
+ const registerStarted = (handle, childId, generation, incarnation) => Ref.update(evidenceOf(handle), (known) => HashMap.set(known, evidenceKeyOf(childId, generation), incarnation));
828
+ const knownStarted = (handle, childId, generation) => Effect.map(Ref.get(evidenceOf(handle)), (known) => HashMap.get(known, evidenceKeyOf(childId, generation)));
829
+ const watchReadiness = (handle, evidence, childId, generation) => Effect.asVoid(Effect.forkIn(Effect.asVoid(Effect.andThen(evidence.ready, stampedNow(handle, readyEventOf(childId, generation)))), ownerScopeOf(handle)));
830
+ const watchReport = (handle, child, incarnation, childId, generation) => Effect.asVoid(Effect.forkIn(Effect.flatMap(child.report(incarnation), (reason) => stampedNow(handle, terminatedEventOf(childId, generation, reason))), ownerScopeOf(handle)));
831
+ /**
832
+ * The child bound to an id. Declared children are bound at acquisition and dynamic
833
+ * ones by `bindDynamicPrograms` before their start runs, so a missing binding is a
834
+ * broken invariant and dies rather than reporting a start that never ran.
835
+ */
836
+ const boundChildFor = (handle, childId) => Effect.flatMap(Ref.get(boundChildrenOf(handle)), (children) => Effect.orDie(Effect.fromOption(HashMap.get(children, childId))));
837
+ const executeStart = (acquired, command) => Effect.gen(function* () {
838
+ const child = yield* boundChildFor(acquired.handle, command.childId);
839
+ const outcome = yield* Effect.exit(child.start);
840
+ yield* Exit.match(outcome, {
841
+ onSuccess: (incarnation) => Effect.andThen(registerStarted(acquired.handle, command.childId, command.generation, incarnation), Effect.andThen(stampedNow(acquired.handle, startedEventOf(command.childId, command.generation)), Effect.andThen(watchReadiness(acquired.handle, incarnation.evidence, command.childId, command.generation), watchReport(acquired.handle, child, incarnation, command.childId, command.generation)))),
842
+ onFailure: (cause) => stampedNow(acquired.handle, terminatedEventOf(command.childId, command.generation, terminationReasonOfCause(cause)))
843
+ });
844
+ });
845
+ /**
846
+ * Moves each answered request's pending child: an accepted start binds it to the
847
+ * child the kernel allocated, and every answered request drops its pending entry.
848
+ */
849
+ const bindDynamicPrograms = (handle, replies) => Effect.andThen(Effect.forEach(Array.filter(replies, Schema.is(ReplyStartAccepted)), (accepted) => Effect.flatMap(Ref.get(pendingChildrenOf(handle)), (pending) => Effect.orDie(Effect.fromOption(HashMap.get(pending, accepted.requestId))).pipe(Effect.flatMap((child) => Ref.update(boundChildrenOf(handle), (children) => HashMap.set(children, accepted.childId, child))))), { discard: true }), Ref.update(pendingChildrenOf(handle), (pending) => Array.reduce(replies, pending, (remaining, reply) => HashMap.remove(remaining, reply.requestId))));
850
+ const executeStop = (acquired, command) => Effect.gen(function* () {
851
+ const child = yield* boundChildFor(acquired.handle, command.childId);
852
+ const found = yield* knownStarted(acquired.handle, command.childId, command.generation);
853
+ yield* Option.match(found, {
854
+ onNone: () => Effect.void,
855
+ onSome: (incarnation) => Effect.asVoid(child.stop(incarnation, command.shutdown))
856
+ });
857
+ yield* stampedNow(acquired.handle, stoppedEventOf(command.childId, command.generation));
858
+ });
859
+ const armTimer = (acquired, deadline, event) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.asVoid(Effect.forkIn(Effect.andThen(Effect.sleep(Duration.millis(Math.max(0, deadline - now))), stampedNow(acquired.handle, event)), ownerScopeOf(acquired.handle))));
860
+ const executeArm = (acquired, arm) => Match.value(arm).pipe(Match.tag("ArmChildTimer", (timer) => armTimer(acquired, timer.deadline, timerEventOf(timer.kind, timer.childId, timer.generation))), Match.tag("ArmSupervisorTimer", (timer) => armTimer(acquired, timer.deadline, supervisorTimerEventOf(timer.kind))), Match.exhaustive);
861
+ const executeReply = (acquired, reply) => Ops.resolveWaiting(repliesOf(acquired.handle), reply.requestId, outcomeOf(reply));
862
+ const giveUpCauseOf = (handle, exit, reason) => Effect.flatMap(Ref.get(evidenceOf(handle)), (evidence) => Option.match(HashMap.get(evidence, evidenceKeyOf(exit.childId, exit.generation)), {
863
+ onNone: () => Effect.succeed(Cause.fail(reason)),
864
+ onSome: (incarnation) => Option.match(failureCauseOf(incarnation.evidence), {
865
+ onNone: () => Effect.succeed(Cause.fail(reason)),
866
+ onSome: (awaited) => Effect.map(awaited, (cause) => Option.getOrElse(cause, () => Cause.fail(reason)))
867
+ })
868
+ }));
869
+ const clearEvidence = (handle) => Ref.update(evidenceOf(handle), () => HashMap.empty());
870
+ const executeTerminate = (acquired, command) => Match.value(command.exit).pipe(Match.tag("RequestedExit", () => Effect.andThen(clearEvidence(acquired.handle), Effect.asVoid(Deferred.succeed(terminatedLatchOf(acquired.handle), void 0)))), Match.tag("IntensityExceededExit", (exit) => Effect.flatMap(giveUpCauseOf(acquired.handle, exit, command.reason), (cause) => Effect.andThen(clearEvidence(acquired.handle), Effect.asVoid(Deferred.fail(terminatedLatchOf(acquired.handle), new SupervisorTerminated({
871
+ name: acquired.handle.name,
872
+ reason: command.reason,
873
+ cause
874
+ })))))), Match.exhaustive);
875
+ const bucketRunnerOf = (acquired) => ({
876
+ stops: (commands) => Effect.forEach(commands.stops, (command) => executeStop(acquired, command), { discard: true }),
877
+ starts: (commands) => Effect.forEach(commands.starts, (command) => executeStart(acquired, command), { discard: true }),
878
+ arms: (commands) => Effect.forEach(commands.arms, (command) => executeArm(acquired, command), { discard: true }),
879
+ replies: (commands) => Effect.forEach(commands.replies, (reply) => executeReply(acquired, reply), { discard: true }),
880
+ terminates: (commands) => Effect.forEach(commands.terminates, (command) => executeTerminate(acquired, command), { discard: true })
881
+ });
882
+ const Commands = {
883
+ runBuckets: (acquired, commands) => runBuckets(acquired, commands),
884
+ probeOnce: (acquired, childId, generation) => probeOnce(acquired, childId, generation),
885
+ answerStale: (acquired, event) => answerStale(acquired, event),
886
+ requestIdOf: (event) => requestIdOf(event)
887
+ };
888
+ const runBuckets = (acquired, commands) => {
889
+ const buckets = bucketRunnerOf(acquired);
890
+ return Effect.andThen(buckets.stops(commands), Effect.andThen(Effect.andThen(bindDynamicPrograms(acquired.handle, commands.replies), buckets.starts(commands)), Effect.andThen(buckets.arms(commands), Effect.andThen(buckets.replies(commands), buckets.terminates(commands)))));
891
+ };
892
+ const probeOnce = (acquired, childId, generation) => Effect.gen(function* () {
893
+ const child = yield* boundChildFor(acquired.handle, childId);
894
+ const found = yield* knownStarted(acquired.handle, childId, generation);
895
+ const alive = yield* Option.match(found, {
896
+ onNone: () => Effect.succeed(false),
897
+ onSome: (incarnation) => child.probe(incarnation)
898
+ });
899
+ yield* stampedNow(acquired.handle, probeEventOf(childId, generation, alive));
642
900
  });
901
+ const requestIdOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, (requested) => requested.requestId), Match.when({ _tag: "DynamicStopRequested" }, (requested) => requested.requestId), Match.orElse(() => void 0));
902
+ const answerStale = (acquired, event) => {
903
+ const requestId = requestIdOf(event);
904
+ return requestId === void 0 ? Effect.void : Ops.resolveWaiting(repliesOf(acquired.handle), requestId, Ops.staleOf(event));
905
+ };
643
906
  //#endregion
644
907
  //#region src/kernel/interpret-supervision-event.workflow.ts
908
+ const DecisionTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionDecision");
645
909
  var Stale = class extends Schema.TaggedClass()("Stale", {}) {
646
910
  [DecisionTypeId] = DecisionTypeId;
647
911
  };
@@ -698,40 +962,8 @@ const SupervisionDecision = Schema.Union([
698
962
  Terminate,
699
963
  RefuseDynamicStart
700
964
  ]);
701
- var Running$1 = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
702
- [StateTypeId] = StateTypeId;
703
- };
704
- var Restarting$1 = class extends Schema.TaggedClass()("Restarting", {
705
- core: SupervisorCore,
706
- pending: Schema.Array(ChildStart)
707
- }) {
708
- [StateTypeId] = StateTypeId;
709
- };
710
- var CoolingDown$1 = class extends Schema.TaggedClass()("CoolingDown", {
711
- core: SupervisorCore,
712
- millis: PositiveMillis
713
- }) {
714
- [StateTypeId] = StateTypeId;
715
- };
716
- var ShuttingDown$1 = class extends Schema.TaggedClass()("ShuttingDown", {
717
- core: SupervisorCore,
718
- reason: TerminationReason,
719
- exit: SupervisorExit
720
- }) {
721
- [StateTypeId] = StateTypeId;
722
- };
723
- var Terminated$1 = class extends Schema.TaggedClass()("Terminated", { reason: TerminationReason }) {
724
- [StateTypeId] = StateTypeId;
725
- };
726
- const SupervisorState$1 = Schema.Union([
727
- Running$1,
728
- Restarting$1,
729
- CoolingDown$1,
730
- ShuttingDown$1,
731
- Terminated$1
732
- ]);
733
965
  var SupervisionStep = class extends Schema.TaggedClass()("SupervisionStep", {
734
- state: SupervisorState$1,
966
+ state: SupervisorState,
735
967
  event: SupervisionEvent
736
968
  }) {
737
969
  static [Workflow.InstrumentationBrand] = {};
@@ -1216,66 +1448,12 @@ const interpretSupervisionEvent = Workflow.make({
1216
1448
  });
1217
1449
  //#endregion
1218
1450
  //#region src/kernel/evolve-supervisor.workflow.ts
1219
- var Running = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
1220
- [StateTypeId] = StateTypeId;
1221
- };
1222
- var Restarting = class extends Schema.TaggedClass()("Restarting", {
1223
- core: SupervisorCore,
1224
- pending: Schema.Array(ChildStart)
1225
- }) {
1226
- [StateTypeId] = StateTypeId;
1227
- };
1228
- var CoolingDown = class extends Schema.TaggedClass()("CoolingDown", {
1229
- core: SupervisorCore,
1230
- millis: PositiveMillis
1231
- }) {
1232
- [StateTypeId] = StateTypeId;
1233
- };
1234
- var ShuttingDown = class extends Schema.TaggedClass()("ShuttingDown", {
1235
- core: SupervisorCore,
1236
- reason: TerminationReason,
1237
- exit: SupervisorExit
1238
- }) {
1239
- [StateTypeId] = StateTypeId;
1240
- };
1241
- var Terminated = class extends Schema.TaggedClass()("Terminated", { reason: TerminationReason }) {
1242
- [StateTypeId] = StateTypeId;
1243
- };
1244
- const SupervisorState = Schema.Union([
1245
- Running,
1246
- Restarting,
1247
- CoolingDown,
1248
- ShuttingDown,
1249
- Terminated
1250
- ]);
1251
1451
  var SupervisionEvolution = class extends Schema.TaggedClass()("SupervisionEvolution", {
1252
1452
  state: SupervisorState,
1253
1453
  decision: SupervisionDecision
1254
1454
  }) {
1255
1455
  static [Workflow.InstrumentationBrand] = {};
1256
1456
  };
1257
- const withCore = (state, core) => Match.value(state).pipe(Match.tag("Running", () => new Running({ core })), Match.tag("Restarting", (restarting) => new Restarting({
1258
- core,
1259
- pending: restarting.pending
1260
- })), Match.tag("CoolingDown", (cooling) => new CoolingDown({
1261
- core,
1262
- millis: cooling.millis
1263
- })), Match.tag("ShuttingDown", (shutting) => new ShuttingDown({
1264
- core,
1265
- reason: shutting.reason,
1266
- exit: shutting.exit
1267
- })), Match.tag("Terminated", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive);
1268
- const evolved = (state, decision) => Match.value(decision).pipe(Match.tag("Stale", () => state), Match.tag("RefuseDynamicStart", () => state), Match.tag("Continue", (continued) => withCore(state, continued.core)), Match.tag("RestartChildren", (restarting) => new Restarting({
1269
- core: restarting.core,
1270
- pending: restarting.pending
1271
- })), Match.tag("StartChildren", (started) => new Running({ core: started.core })), Match.tag("CoolDown", (cooling) => new CoolingDown({
1272
- core: cooling.core,
1273
- millis: cooling.millis
1274
- })), Match.tag("StopChildren", (stopping) => new ShuttingDown({
1275
- core: stopping.core,
1276
- reason: stopping.reason,
1277
- exit: stopping.exit
1278
- })), Match.tag("Terminate", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive);
1279
1457
  const evolveSupervisor = Workflow.make({
1280
1458
  command: SupervisionEvolution,
1281
1459
  decision: SupervisorState,
@@ -1283,164 +1461,6 @@ const evolveSupervisor = Workflow.make({
1283
1461
  decide: (step) => Result.succeed(evolved(step.state, step.decision))
1284
1462
  });
1285
1463
  //#endregion
1286
- //#region src/Supervisor/SupervisorTerminated.schema.ts
1287
- const firstLine = (text) => text.split("\n")[0] ?? "";
1288
- var SupervisorTerminated = class extends Schema.TaggedError()("SupervisorTerminated", {
1289
- name: Schema.String,
1290
- reason: TerminationReason,
1291
- cause: Schema.Cause(Schema.Unknown, Schema.Unknown)
1292
- }) {
1293
- get message() {
1294
- return `Supervisor "${this.name}" terminated (${this.reason._tag}): ${firstLine(Cause.pretty(this.cause))}`;
1295
- }
1296
- };
1297
- //#endregion
1298
- //#region src/Supervisor/supervisor-commands.ts
1299
- const stampedNow = (handle, event) => Effect.flatMap(Clock.currentTimeMillis, (now) => offerEvent(handle, {
1300
- ...event,
1301
- at: now
1302
- }));
1303
- const startedEventOf = (childId, generation) => ({
1304
- _tag: "ChildStarted",
1305
- at: 0,
1306
- childId,
1307
- generation
1308
- });
1309
- const readyEventOf = (childId, generation) => ({
1310
- _tag: "ChildReady",
1311
- at: 0,
1312
- childId,
1313
- generation
1314
- });
1315
- const terminatedEventOf = (childId, generation, reason) => ({
1316
- _tag: "ChildTerminated",
1317
- at: 0,
1318
- childId,
1319
- generation,
1320
- reason
1321
- });
1322
- const stoppedEventOf = (childId, generation) => ({
1323
- _tag: "ChildStopped",
1324
- at: 0,
1325
- childId,
1326
- generation
1327
- });
1328
- const probeEventOf = (childId, generation, alive) => ({
1329
- _tag: "ProbeResult",
1330
- at: 0,
1331
- childId,
1332
- generation,
1333
- alive
1334
- });
1335
- const timerEventOf = (kind, childId, generation) => ({
1336
- _tag: "TimerElapsed",
1337
- at: 0,
1338
- kind,
1339
- target: {
1340
- _tag: "ChildTimer",
1341
- childId,
1342
- generation
1343
- }
1344
- });
1345
- const supervisorTimerEventOf = (kind) => ({
1346
- _tag: "TimerElapsed",
1347
- at: 0,
1348
- kind,
1349
- target: { _tag: "SupervisorTimer" }
1350
- });
1351
- const evidenceKeyOf = (childId, generation) => `${childId}#${generation}`;
1352
- const registerStarted = (handle, childId, generation, evidence) => Ref.update(evidenceOf(handle), (known) => HashMap.set(known, evidenceKeyOf(childId, generation), evidence));
1353
- const knownStarted = (handle, childId, generation) => Effect.map(Ref.get(evidenceOf(handle)), (known) => HashMap.get(known, evidenceKeyOf(childId, generation)));
1354
- const watchReadiness = (handle, evidence, childId, generation) => Effect.asVoid(Effect.forkIn(Effect.asVoid(Effect.andThen(evidence.ready, stampedNow(handle, readyEventOf(childId, generation)))), ownerScopeOf(handle)));
1355
- const watchReport = (handle, child, evidence, childId, generation) => Effect.asVoid(Effect.forkIn(Effect.flatMap(child.report(evidence), (reason) => stampedNow(handle, terminatedEventOf(childId, generation, reason))), ownerScopeOf(handle)));
1356
- /**
1357
- * The child bound to an id. Declared children are bound at acquisition and dynamic
1358
- * ones by `bindDynamicPrograms` before their start runs, so a missing binding is a
1359
- * broken invariant and dies rather than reporting a start that never ran.
1360
- */
1361
- const boundChildFor = (handle, childId) => Effect.flatMap(Ref.get(boundChildrenOf(handle)), (children) => Effect.orDie(Effect.fromOption(HashMap.get(children, childId))));
1362
- const failureReasonOf = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => ({
1363
- _tag: "Abnormal",
1364
- report: {
1365
- _tag: "CauseReport",
1366
- cause: Cause.pretty(cause)
1367
- }
1368
- }));
1369
- const executeStart = (acquired, command) => Effect.gen(function* () {
1370
- const child = yield* boundChildFor(acquired.handle, command.childId);
1371
- const outcome = yield* Effect.exit(child.start);
1372
- yield* Exit.match(outcome, {
1373
- onSuccess: (evidence) => Effect.andThen(registerStarted(acquired.handle, command.childId, command.generation, evidence), Effect.andThen(stampedNow(acquired.handle, startedEventOf(command.childId, command.generation)), Effect.andThen(watchReadiness(acquired.handle, evidence, command.childId, command.generation), watchReport(acquired.handle, child, evidence, command.childId, command.generation)))),
1374
- onFailure: (cause) => stampedNow(acquired.handle, terminatedEventOf(command.childId, command.generation, failureReasonOf(cause)))
1375
- });
1376
- });
1377
- /**
1378
- * Moves each answered request's pending child: an accepted start binds it to the
1379
- * child the kernel allocated, and every answered request drops its pending entry.
1380
- */
1381
- const bindDynamicPrograms = (handle, replies) => Effect.andThen(Effect.forEach(Array.filter(replies, Schema.is(ReplyStartAccepted)), (accepted) => Effect.flatMap(Ref.get(pendingChildrenOf(handle)), (pending) => Effect.orDie(Effect.fromOption(HashMap.get(pending, accepted.requestId))).pipe(Effect.flatMap((child) => Ref.update(boundChildrenOf(handle), (children) => HashMap.set(children, accepted.childId, child))))), { discard: true }), Ref.update(pendingChildrenOf(handle), (pending) => Array.reduce(replies, pending, (remaining, reply) => HashMap.remove(remaining, reply.requestId))));
1382
- const executeStop = (acquired, command) => Effect.gen(function* () {
1383
- const child = yield* boundChildFor(acquired.handle, command.childId);
1384
- const found = yield* knownStarted(acquired.handle, command.childId, command.generation);
1385
- yield* Option.match(found, {
1386
- onNone: () => Effect.void,
1387
- onSome: (evidence) => Effect.asVoid(child.stop(evidence, command.shutdown))
1388
- });
1389
- yield* stampedNow(acquired.handle, stoppedEventOf(command.childId, command.generation));
1390
- });
1391
- const armTimer = (acquired, deadline, event) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.asVoid(Effect.forkIn(Effect.andThen(Effect.sleep(Duration.millis(Math.max(0, deadline - now))), stampedNow(acquired.handle, event)), ownerScopeOf(acquired.handle))));
1392
- const executeArm = (acquired, arm) => Match.value(arm).pipe(Match.tag("ArmChildTimer", (timer) => armTimer(acquired, timer.deadline, timerEventOf(timer.kind, timer.childId, timer.generation))), Match.tag("ArmSupervisorTimer", (timer) => armTimer(acquired, timer.deadline, supervisorTimerEventOf(timer.kind))), Match.exhaustive);
1393
- const outcomeOf = (reply) => Match.value(reply).pipe(Match.tag("ReplyStartAccepted", (accepted) => ({
1394
- outcome: "accepted",
1395
- childId: accepted.childId,
1396
- generation: accepted.generation
1397
- })), Match.tag("ReplyStartRefused", () => ({ outcome: "refused" })), Match.tag("ReplyStopped", () => ({ outcome: "stopped" })), Match.exhaustive);
1398
- const executeReply = (acquired, reply) => Ops.resolveWaiting(repliesOf(acquired.handle), reply.requestId, outcomeOf(reply));
1399
- const giveUpCauseOf = (handle, exit, reason) => Effect.flatMap(Ref.get(evidenceOf(handle)), (evidence) => Option.match(HashMap.get(evidence, evidenceKeyOf(exit.childId, exit.generation)), {
1400
- onNone: () => Effect.succeed(Cause.fail(reason)),
1401
- onSome: (started) => Option.match(failureCauseOf(started), {
1402
- onNone: () => Effect.succeed(Cause.fail(reason)),
1403
- onSome: (awaited) => Effect.map(awaited, (cause) => Option.getOrElse(cause, () => Cause.fail(reason)))
1404
- })
1405
- }));
1406
- const clearEvidence = (handle) => Ref.update(evidenceOf(handle), () => HashMap.empty());
1407
- const executeTerminate = (acquired, command) => Match.value(command.exit).pipe(Match.tag("RequestedExit", () => Effect.andThen(clearEvidence(acquired.handle), Effect.asVoid(Deferred.succeed(terminatedLatchOf(acquired.handle), void 0)))), Match.tag("IntensityExceededExit", (exit) => Effect.flatMap(giveUpCauseOf(acquired.handle, exit, command.reason), (cause) => Effect.andThen(clearEvidence(acquired.handle), Effect.asVoid(Deferred.fail(terminatedLatchOf(acquired.handle), new SupervisorTerminated({
1408
- name: acquired.handle.name,
1409
- reason: command.reason,
1410
- cause
1411
- })))))), Match.exhaustive);
1412
- const bucketRunnerOf = (acquired) => ({
1413
- stops: (commands) => Effect.forEach(commands.stops, (command) => executeStop(acquired, command), { discard: true }),
1414
- starts: (commands) => Effect.forEach(commands.starts, (command) => executeStart(acquired, command), { discard: true }),
1415
- arms: (commands) => Effect.forEach(commands.arms, (command) => executeArm(acquired, command), { discard: true }),
1416
- replies: (commands) => Effect.forEach(commands.replies, (reply) => executeReply(acquired, reply), { discard: true }),
1417
- terminates: (commands) => Effect.forEach(commands.terminates, (command) => executeTerminate(acquired, command), { discard: true })
1418
- });
1419
- const Commands = {
1420
- runBuckets: (acquired, commands) => runBuckets(acquired, commands),
1421
- probeOnce: (acquired, childId, generation) => probeOnce(acquired, childId, generation),
1422
- answerStale: (acquired, event) => answerStale(acquired, event),
1423
- requestIdOf: (event) => requestIdOf(event)
1424
- };
1425
- const runBuckets = (acquired, commands) => {
1426
- const buckets = bucketRunnerOf(acquired);
1427
- return Effect.andThen(buckets.stops(commands), Effect.andThen(Effect.andThen(bindDynamicPrograms(acquired.handle, commands.replies), buckets.starts(commands)), Effect.andThen(buckets.arms(commands), Effect.andThen(buckets.replies(commands), buckets.terminates(commands)))));
1428
- };
1429
- const probeOnce = (acquired, childId, generation) => Effect.gen(function* () {
1430
- const child = yield* boundChildFor(acquired.handle, childId);
1431
- const found = yield* knownStarted(acquired.handle, childId, generation);
1432
- const alive = yield* Option.match(found, {
1433
- onNone: () => Effect.succeed(false),
1434
- onSome: (evidence) => child.probe(evidence)
1435
- });
1436
- yield* stampedNow(acquired.handle, probeEventOf(childId, generation, alive));
1437
- });
1438
- const requestIdOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, (requested) => requested.requestId), Match.when({ _tag: "DynamicStopRequested" }, (requested) => requested.requestId), Match.orElse(() => void 0));
1439
- const answerStale = (acquired, event) => {
1440
- const requestId = requestIdOf(event);
1441
- return requestId === void 0 ? Effect.void : Ops.resolveWaiting(repliesOf(acquired.handle), requestId, Ops.staleOf(event));
1442
- };
1443
- //#endregion
1444
1464
  //#region src/Supervisor/supervisor-step.cell.ts
1445
1465
  const readStep = (runtime, event) => Effect.map(Effect.zip(Clock.currentTimeMillis, Ref.get(stateOf(runtime.acquired.handle))), ([now, state]) => new SupervisionStep({
1446
1466
  state,
@@ -1448,17 +1468,20 @@ const readStep = (runtime, event) => Effect.map(Effect.zip(Clock.currentTimeMill
1448
1468
  ...event,
1449
1469
  at: now
1450
1470
  }
1451
- }, { disableChecks: true }));
1452
- const persistedOf = (previous, decision) => Result.getOrThrow(evolveSupervisor(new SupervisionEvolution({
1471
+ }));
1472
+ const persistedOf = (previous, decision) => Effect.flatMap(Schema.decodeEffect(SupervisionDecision)(decision), (decoded) => Effect.fromResult(evolveSupervisor(new SupervisionEvolution({
1453
1473
  state: previous,
1454
- decision: Result.getOrThrow(Schema.decodeResult(SupervisionDecision)(decision))
1455
- })));
1456
- const persistStep = (runtime, event, previous, decision) => Effect.flatMap(Effect.suspend(() => Effect.succeed(persistedOf(previous, decision))), (next) => Effect.andThen(Ref.set(stateOf(runtime.acquired.handle), next), PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1474
+ decision: decoded
1475
+ }))));
1476
+ const persistStep = (runtime, event, previous, decision) => Effect.flatMap(Effect.orDie(persistedOf(previous, decision)), (next) => Effect.andThen(Ref.set(stateOf(runtime.acquired.handle), next), PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1457
1477
  event,
1458
1478
  decision
1459
1479
  })));
1460
1480
  const runBucketsOf = (runtime, commands) => Commands.runBuckets(runtime.acquired, commands);
1461
- const Steps = { runtimeOf: (acquired) => ({ acquired }) };
1481
+ const persistCommandRejection = (runtime, event) => PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1482
+ event,
1483
+ decision: new Stale({})
1484
+ }).pipe(Effect.asVoid);
1462
1485
  const supervisorStepFor = (runtime) => Sandwich.named("supervisor.step")((event) => readStep(runtime, event)).decide(interpretSupervisionEvent).write({
1463
1486
  Stale: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), Commands.answerStale(runtime.acquired, command.event)),
1464
1487
  Continue: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
@@ -1470,35 +1493,12 @@ const supervisorStepFor = (runtime) => Sandwich.named("supervisor.step")((event)
1470
1493
  RefuseDynamicStart: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1471
1494
  CommandRejected: (_rejected, command) => Effect.andThen(persistCommandRejection(runtime, command.event), Commands.answerStale(runtime.acquired, command.event))
1472
1495
  });
1473
- const persistCommandRejection = (runtime, event) => PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1474
- event,
1475
- decision: new Stale({})
1476
- }).pipe(Effect.asVoid);
1477
1496
  //#endregion
1478
1497
  //#region src/Supervisor/Supervisor.ts
1479
1498
  const SpecTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/SupervisorSpec");
1480
1499
  const hasSpecTag = Predicate.hasProperty(SpecTypeId);
1481
1500
  const isSupervisorSpec = (value) => hasSpecTag(value) && value[SpecTypeId] === SpecTypeId;
1482
- const WORKER_SHUTDOWN = {
1483
- _tag: "Graceful",
1484
- millis: 5e3
1485
- };
1486
- const SUPERVISOR_SHUTDOWN = { _tag: "Infinity" };
1487
1501
  const LIVENESS_TICK_MILLIS = 1e3;
1488
- const policyOfParts = (parts) => ({
1489
- strategy: parts.strategy,
1490
- intensity: parts.intensity,
1491
- periodMillis: parts.periodMillis,
1492
- autoShutdown: parts.autoShutdown,
1493
- coolDown: parts.coolDownMillis === void 0 ? { _tag: "NoCoolDown" } : {
1494
- _tag: "CoolDownAfter",
1495
- millis: parts.coolDownMillis
1496
- },
1497
- backoff: parts.backoff,
1498
- dynamic: parts.dynamic,
1499
- livenessTickMillis: parts.livenessTickMillis,
1500
- childDeclarations: parts.declarations
1501
- });
1502
1502
  const drainOf = (handle, step) => Effect.flatMap(Queue.take(mailboxOf(handle)), (event) => Effect.flatMap(Effect.asVoid(step.run(event)), () => Effect.flatMap(Ref.get(stateOf(handle)), (state) => Match.value(state).pipe(Match.when({ _tag: "Terminated" }, () => Effect.void), Match.orElse(() => drainOf(handle, step))))));
1503
1503
  const fiberMediumOf = () => Effect.map(Effect.serviceOption(fiberPort), (found) => Option.match(found, {
1504
1504
  onNone: () => mediumFor(),
@@ -1506,7 +1506,7 @@ const fiberMediumOf = () => Effect.map(Effect.serviceOption(fiberPort), (found)
1506
1506
  }));
1507
1507
  const scopedOf = (parts) => Effect.gen(function* () {
1508
1508
  const supervisorScope = yield* Effect.scope;
1509
- const initial = new Running$1({ core: initialStateOf(policyOfParts(parts)) });
1509
+ const initial = new Running({ core: initialStateOf(supervisionPolicyOf(parts)) });
1510
1510
  const bound = yield* Effect.forEach(parts.bindings, (entry) => Effect.map(entry.binding, (child) => [entry.declaration.childId, child]), { concurrency: 1 });
1511
1511
  const context = yield* Effect.context();
1512
1512
  const fiber = yield* fiberMediumOf();
@@ -1588,7 +1588,7 @@ const livenessTick = dual(2, (self, millis) => specOf({
1588
1588
  const dynamicKindOf = (options) => ({
1589
1589
  _tag: "DynamicChildren",
1590
1590
  restartType: "permanent",
1591
- shutdown: WORKER_SHUTDOWN,
1591
+ shutdown: childShutdownOf(false),
1592
1592
  startTimeoutMillis: 5e3,
1593
1593
  probeFailureThreshold: 2,
1594
1594
  ...options
@@ -1600,7 +1600,7 @@ const dynamic = dual(2, (self, options) => specOf({
1600
1600
  const declarationOf = (childId, nested, options) => ({
1601
1601
  childId,
1602
1602
  restartType: "permanent",
1603
- shutdown: nested ? SUPERVISOR_SHUTDOWN : WORKER_SHUTDOWN,
1603
+ shutdown: childShutdownOf(nested),
1604
1604
  significant: false,
1605
1605
  startTimeoutMillis: 5e3,
1606
1606
  probeFailureThreshold: 2,
@@ -1661,6 +1661,7 @@ const child = dual((args) => isSupervisorSpec(args[0]), (self, childId, program,
1661
1661
  //#region src/Supervisor/mod.ts
1662
1662
  var Supervisor_exports = /* @__PURE__ */ __exportAll({
1663
1663
  ChildSpecs: () => ChildSpecs,
1664
+ ClassifyChildExit: () => ClassifyChildExit,
1664
1665
  FiberMedium: () => FiberMedium_exports,
1665
1666
  Medium: () => Medium_exports,
1666
1667
  SpecTypeId: () => SpecTypeId,
@@ -1671,6 +1672,7 @@ var Supervisor_exports = /* @__PURE__ */ __exportAll({
1671
1672
  backoff: () => backoff,
1672
1673
  child: () => child,
1673
1674
  children: () => children,
1675
+ classifyChildExit: () => classifyChildExit,
1674
1676
  coolDown: () => coolDown,
1675
1677
  dynamic: () => dynamic,
1676
1678
  intensity: () => intensity,