@systemfsoftware/effect-daemon-spec 4.1.1 → 5.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,1123 +1,1690 @@
1
- import { Array, Cause, Clock, Context, Duration, Effect, Equal, Exit, Fiber, Function, HashMap, Latch, Layer, Match, Metric, Option, Predicate, Ref, Result, Schedule, Schema, SchemaGetter, Scope, Stream } from "effect";
2
- import { Sandwich, Workflow } from "@systemfsoftware/effect-cell-types";
3
- import * as Arr from "effect/Array";
4
- import * as Match$1 from "effect/Match";
5
- import "effect/Option";
6
- import * as Result$1 from "effect/Result";
7
- import * as S from "effect/Schema";
8
- //#region src/Backoff.ts
9
- const cappedBackoff = Function.dual(2, (base, cap) => {
10
- const ceiling = Duration.fromInputUnsafe(cap);
11
- return Schedule.exponential(base).pipe(Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, ceiling))));
12
- });
13
- //#endregion
14
- //#region src/Brands.ts
15
- const WorkerTypeId = Symbol.for("@systemfsoftware/effect-daemon/Worker");
16
- const SupervisorTypeId = Symbol.for("@systemfsoftware/effect-daemon/Supervisor");
17
- const DynamicSpecTypeId = Symbol.for("@systemfsoftware/effect-daemon/DynamicSpec");
18
- //#endregion
19
- //#region src/DaemonHealth.schema.ts
20
- var DynamicLimitExceeded = class extends Schema.TaggedError()("DynamicLimitExceeded", { limit: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0))) }) {};
21
- //#endregion
22
- //#region src/DaemonMetrics.ts
23
- const supervisorRestartsCounter = Metric.counter("app.daemon.supervisor.restart", { description: "Daemon supervisor restart count" });
24
- const supervisorExhaustionsCounter = Metric.counter("app.daemon.supervisor.exhaustion", { description: "Daemon supervisor exhaustion count" });
25
- const supervisorChildrenGauge = Metric.gauge("app.daemon.supervisor.children", { description: "Daemon supervisor current child count (dynamic supervisors only)" });
26
- const healthStateGauge = Metric.gauge("app.daemon.health.state", { description: "Daemon health latch open (1) or closed (0); tagged by daemon name and latch (ready | healthy | paused)" });
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
+ import { Handle, Sandwich, Workflow } from "@systemfsoftware/effect-cell-types";
4
+ import { dual } from "effect/Function";
5
+ import * as Stream from "effect/Stream";
6
+ import { Prototype } from "effect/Pipeable";
7
+ //#region src/kernel/SupervisionLimits.schema.ts
8
+ /**
9
+ * Generation-only bound: the production domains below span the whole
10
+ * non-negative safe-integer range, but unbounded generation would draw
11
+ * astronomically large counters and times in property tests
12
+ * (compound-packs/schema-laws/arbitrary-filter-floors.md). An
13
+ * annotation-only check never rejects a value; it only steers the derived
14
+ * fast-check integer generator into a small range.
15
+ */
16
+ const generatedBetween = (minimum, maximum) => Schema.makeFilter(() => void 0, { arbitraryConstraint: {
17
+ minimum,
18
+ maximum
19
+ } });
20
+ const NonNegativeSafeInt = Schema.Int.pipe(Schema.check(Schema.isBetween({
21
+ minimum: 0,
22
+ maximum: Number.MAX_SAFE_INTEGER
23
+ })));
24
+ const PositiveSafeInt = Schema.Int.pipe(Schema.check(Schema.isBetween({
25
+ minimum: 1,
26
+ maximum: Number.MAX_SAFE_INTEGER
27
+ })));
28
+ /** Millisecond duration; any non-negative safe integer (backoff caps and cool-downs may be long). Generation stays at most one minute. */
29
+ const Millis = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 6e4)));
30
+ /** Millisecond duration that must be positive (periods, timeouts, cool-downs). Generation stays at most one minute. */
31
+ const PositiveMillis = PositiveSafeInt.pipe(Schema.check(generatedBetween(1, 6e4)));
32
+ /** Millisecond timestamp of a supervision event: any non-negative safe integer (a supervisor may run for years). Generation stays small so event arithmetic stays in range. */
33
+ const EventTime = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 1e6)));
34
+ /** Absolute millisecond deadline of an armed timer: any non-negative safe integer. Generation stays small. */
35
+ const Deadline = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 1e6)));
36
+ /** How many times a child incarnation has been replaced: any non-negative safe integer. Generation stays small so generation+1 stays in range. */
37
+ const Generation = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 1024)));
38
+ /** OTP intensity (R3): any non-negative integer restarts per period. Generation stays small because laws fold intensity+1 restarts. */
39
+ const Intensity = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 8)));
40
+ /** OTP simple_one_for_one ceiling (R6): 1..1000, matching the retired package's MAX_CHILDREN_CEILING; a zero ceiling is refused at decode. */
41
+ const Ceiling = Schema.Int.pipe(Schema.check(Schema.isBetween({
42
+ minimum: 1,
43
+ maximum: 1e3
44
+ })));
45
+ /** Consecutive failed probes that decide an inferred death (KTD7): any positive safe integer. Generation stays small. */
46
+ const ProbeThreshold = PositiveSafeInt.pipe(Schema.check(generatedBetween(1, 8)));
47
+ /** Consecutive failed probes observed so far: any non-negative safe integer. Generation stays small. */
48
+ const ProbeFailures = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 8)));
49
+ /** Consecutive restarts of one child driving the backoff exponent (R8): any non-negative safe integer. Generation stays small so k+1 stays in range. */
50
+ const RestartCount = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 1024)));
51
+ /** Identity counter for dynamically started children: any non-negative safe integer. Generation stays small. */
52
+ const Ordinal = NonNegativeSafeInt.pipe(Schema.check(generatedBetween(0, 1024)));
53
+ const ChildId = Schema.String;
54
+ const RequestId = Schema.String;
55
+ Schema.decodeResult(Ceiling);
27
56
  //#endregion
28
- //#region src/SupervisorDynamic.ts
29
- const MAX_CHILDREN_CEILING = 1e3;
30
- const dynamic$2 = (opts) => ({
31
- [DynamicSpecTypeId]: DynamicSpecTypeId,
32
- name: opts.name,
33
- child: opts.child,
34
- maxChildren: opts.maxChildren
57
+ //#region src/kernel/SupervisorPolicy.schema.ts
58
+ const RestartStrategy = Schema.Literals([
59
+ "one_for_one",
60
+ "one_for_all",
61
+ "rest_for_one"
62
+ ]);
63
+ const RestartType = Schema.Literals([
64
+ "permanent",
65
+ "transient",
66
+ "temporary"
67
+ ]);
68
+ const AutoShutdown = Schema.Literals([
69
+ "never",
70
+ "any_significant",
71
+ "all_significant"
72
+ ]);
73
+ const BrutalShutdown = Schema.TaggedStruct("Brutal", {});
74
+ const GracefulShutdown = Schema.TaggedStruct("Graceful", { millis: PositiveMillis });
75
+ const InfinityShutdown = Schema.TaggedStruct("Infinity", {});
76
+ const ShutdownMode = Schema.Union([
77
+ BrutalShutdown,
78
+ GracefulShutdown,
79
+ InfinityShutdown
80
+ ]);
81
+ const BackoffSchedule = Schema.Struct({
82
+ baseMillis: Millis,
83
+ multiplier: Schema.Int.pipe(Schema.check(Schema.isBetween({
84
+ minimum: 1,
85
+ maximum: 4
86
+ }))),
87
+ capMillis: Millis
35
88
  });
36
- //#endregion
37
- //#region src/DaemonPolicy.schema.ts
38
- const IntensityConfig = Schema.Struct({
39
- restarts: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0))),
40
- window: Schema.Duration
41
- });
42
- const IntensityTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/Intensity");
43
- var BoundedIntensity = class extends Schema.TaggedClass()("Bounded", IntensityConfig.fields) {
44
- [IntensityTypeId] = IntensityTypeId;
89
+ const ChildDeclaration = Schema.Struct({
90
+ childId: ChildId,
91
+ restartType: RestartType,
92
+ shutdown: ShutdownMode,
93
+ significant: Schema.Boolean,
94
+ startTimeoutMillis: PositiveMillis,
95
+ probeFailureThreshold: ProbeThreshold
96
+ });
97
+ const NoDynamicChildren = Schema.TaggedStruct("NoDynamicChildren", {});
98
+ const DynamicChildren = Schema.TaggedStruct("DynamicChildren", {
99
+ ceiling: Ceiling,
100
+ restartType: RestartType,
101
+ shutdown: ShutdownMode,
102
+ startTimeoutMillis: PositiveMillis,
103
+ probeFailureThreshold: ProbeThreshold
104
+ });
105
+ const DynamicKind = Schema.Union([NoDynamicChildren, DynamicChildren]);
106
+ const NoCoolDown = Schema.TaggedStruct("NoCoolDown", {});
107
+ const CoolDownAfter = Schema.TaggedStruct("CoolDownAfter", { millis: PositiveMillis });
108
+ const CoolDownSetting = Schema.Union([NoCoolDown, CoolDownAfter]);
109
+ const policyFields = {
110
+ strategy: RestartStrategy,
111
+ intensity: Intensity,
112
+ periodMillis: PositiveMillis,
113
+ autoShutdown: AutoShutdown,
114
+ coolDown: CoolDownSetting,
115
+ backoff: BackoffSchedule,
116
+ dynamic: DynamicKind,
117
+ livenessTickMillis: PositiveMillis,
118
+ childDeclarations: Schema.Array(ChildDeclaration)
45
119
  };
46
- var UnboundedIntensity = class extends Schema.TaggedClass()("Unbounded", {}) {
47
- [IntensityTypeId] = IntensityTypeId;
120
+ Schema.TaggedStruct("SignificantPermanentChild", {});
121
+ Schema.TaggedStruct("SignificantChildUnderNever", {});
122
+ const significantPermanentRefusal = { _tag: "SignificantPermanentChild" };
123
+ const significantUnderNeverRefusal = { _tag: "SignificantChildUnderNever" };
124
+ const POLICY_REFUSAL_MESSAGE = "a significant child must be transient or temporary, and a supervisor that declares one must auto-shutdown on significance";
125
+ const permanentRefusalOf = (child) => Match.value(child.restartType).pipe(Match.when("permanent", () => Option.some(significantPermanentRefusal)), Match.orElse(() => Option.none()));
126
+ const autoRefusalOf = (child, autoShutdown) => Match.value(autoShutdown).pipe(Match.when("never", () => Option.some(significantUnderNeverRefusal)), Match.orElse(() => permanentRefusalOf(child)));
127
+ const childRefusalOf = (child, autoShutdown) => Match.value(child.significant).pipe(Match.when(false, () => Option.none()), Match.orElse(() => autoRefusalOf(child, autoShutdown)));
128
+ const policyRefusalOf = (policy) => {
129
+ const offending = Array.findFirst(policy.childDeclarations, (child) => Option.isSome(childRefusalOf(child, policy.autoShutdown)));
130
+ return Option.flatMap(offending, (child) => childRefusalOf(child, policy.autoShutdown));
48
131
  };
49
- const Intensity = Schema.Union([BoundedIntensity, UnboundedIntensity]);
50
- var ChildPolicyConfig = class extends Schema.Class("ChildPolicyConfig")({
51
- restart: Schema.optional(Schema.Literals([
52
- "permanent",
53
- "transient",
54
- "temporary"
55
- ])),
56
- intensity: Schema.optional(IntensityConfig)
57
- }) {};
58
- Schema.Class("SupervisorPolicyConfig")({
59
- intensity: Schema.optional(IntensityConfig),
60
- cooldown: Schema.optional(Schema.Duration)
61
- });
62
- var LockPolicyConfig = class extends Schema.Class("LockPolicyConfig")({
63
- mode: Schema.optional(Schema.Literals([
64
- "none",
65
- "required",
66
- "optional"
67
- ])),
68
- key: Schema.optional(Schema.String)
69
- }) {};
70
- var TickPolicyConfig = class extends Schema.Class("TickPolicyConfig")({
71
- spanName: Schema.optional(Schema.String),
72
- tickTimeout: Schema.Duration,
73
- startLogLevel: Schema.optional(Schema.Literals(["debug", "info"]))
74
- }) {};
75
- const MaxChildren = Schema.Int.pipe(Schema.check(Schema.isBetween({
76
- minimum: 1,
77
- maximum: MAX_CHILDREN_CEILING
78
- })), Schema.brand("MaxChildren"));
79
- //#endregion
80
- //#region src/DaemonReporterAdapter.ts
81
- var DaemonReporter = class extends Context.Service()("@systemfsoftware/effect-daemon-spec/DaemonReporterAdapter/DaemonReporter") {};
82
- const Noop = Layer.succeed(DaemonReporter, DaemonReporter.of({
83
- onRestart: () => Effect.void,
84
- onExhausted: () => Effect.void
85
- }));
132
+ const policyIsDecodable = (policy) => Option.isNone(policyRefusalOf(policy));
133
+ const ChildSeed = Schema.Struct({
134
+ restartType: RestartType,
135
+ significantBit: Schema.Boolean,
136
+ shutdown: ShutdownMode,
137
+ startTimeoutMillis: PositiveMillis,
138
+ probeFailureThreshold: ProbeThreshold
139
+ });
140
+ Schema.Struct({
141
+ strategy: RestartStrategy,
142
+ intensity: Intensity,
143
+ periodMillis: PositiveMillis,
144
+ autoShutdown: AutoShutdown,
145
+ coolDown: CoolDownSetting,
146
+ backoff: BackoffSchedule,
147
+ dynamic: DynamicKind,
148
+ livenessTickMillis: PositiveMillis,
149
+ childSeeds: Schema.Array(ChildSeed)
150
+ });
151
+ const SupervisionPolicy = Schema.Struct(policyFields).check(Schema.makeFilter(policyIsDecodable, { message: POLICY_REFUSAL_MESSAGE }));
86
152
  //#endregion
87
- //#region src/LoopTags.ts
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
+ ]);
88
181
  /**
89
- * Discriminants on the public Worker loop variants.
90
- *
91
- * These tags are part of the published type identity of `poll`, `stream`,
92
- * and `subscription`. They are not unpublished wiring.
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.
93
186
  */
94
- const PollLoopTag = { _tag: "Poll" };
95
- const StreamLoopTag = { _tag: "Stream" };
96
- const SubscriptionLoopTag = { _tag: "Subscription" };
187
+ const RequestedExit = Schema.TaggedStruct("RequestedExit", {});
188
+ const IntensityExceededExit = Schema.TaggedStruct("IntensityExceededExit", {
189
+ childId: ChildId,
190
+ generation: Generation
191
+ });
192
+ const SupervisorExit = Schema.Union([RequestedExit, IntensityExceededExit]);
97
193
  //#endregion
98
- //#region src/DaemonPoll.ts
99
- const orEmpty$2 = (value) => {
100
- if (typeof value === "undefined") return {};
101
- return value;
102
- };
103
- const poll$1 = (opts) => {
104
- if (typeof opts.prereq === "undefined") {
105
- const gate = Effect.succeedSome(Effect.asVoid(opts.work));
106
- return {
107
- [WorkerTypeId]: WorkerTypeId,
108
- name: opts.name,
109
- loop: {
110
- ...PollLoopTag,
111
- gate,
112
- interval: opts.interval
113
- },
114
- child: orEmpty$2(opts.child),
115
- tick: opts.tick,
116
- tickHooks: orEmpty$2(opts.tickHooks),
117
- lock: opts.lock
118
- };
119
- }
120
- const { prereq, work } = opts;
121
- const gate = Effect.map(prereq, Option.map((data) => work(data)));
122
- return {
123
- [WorkerTypeId]: WorkerTypeId,
124
- name: opts.name,
125
- loop: {
126
- ...PollLoopTag,
127
- gate,
128
- interval: opts.interval
129
- },
130
- child: orEmpty$2(opts.child),
131
- tick: opts.tick,
132
- tickHooks: orEmpty$2(opts.tickHooks),
133
- lock: opts.lock
134
- };
135
- };
194
+ //#region src/Supervisor/MediumDeclaration.schema.ts
195
+ /**
196
+ * What a medium can say about why a child died (R16, KTD8): the in-process fiber
197
+ * medium reports a full `Cause`, a process, socket or microVM medium reports the
198
+ * exit status and signal it observed, and the cluster medium's death is only
199
+ * inferred from failed liveness probes (KTD7). The kernel assumes nothing beyond
200
+ * the declared level; the conformance kit projects traces down to it.
201
+ */
202
+ const MediumReporting = Schema.Literals([
203
+ "full",
204
+ "exit",
205
+ "inferred"
206
+ ]);
207
+ /**
208
+ * The `one_for_all` guarantee a medium can honour (R16, KTD8): `atomic` means no
209
+ * child is left running once the group stop returns, `eventual` means teardown
210
+ * continues on the medium's own clock after the call returns.
211
+ */
212
+ const GroupStopGuarantee = Schema.Literals(["atomic", "eventual"]);
213
+ /**
214
+ * A medium's declaration to the kernel (R16). Both fields are required: a
215
+ * declaration without a reporting level or a group-stop guarantee is refused at
216
+ * decode, so the kernel never guesses what a medium can say or honour.
217
+ */
218
+ const MediumDeclaration = Schema.Struct({
219
+ reporting: MediumReporting,
220
+ groupStop: GroupStopGuarantee
221
+ });
136
222
  //#endregion
137
- //#region src/DaemonStream.ts
138
- const orEmpty$1 = (value) => {
139
- if (typeof value === "undefined") return {};
140
- return value;
141
- };
142
- const stream$1 = (opts) => ({
143
- [WorkerTypeId]: WorkerTypeId,
144
- name: opts.name,
145
- loop: {
146
- ...StreamLoopTag,
147
- stream: opts.stream
148
- },
149
- child: orEmpty$1(opts.child),
150
- tick: opts.tick,
151
- tickHooks: orEmpty$1(opts.tickHooks),
152
- lock: opts.lock
223
+ //#region src/Supervisor/Medium.ts
224
+ var Medium_exports = /* @__PURE__ */ __exportAll({
225
+ AbnormalTermination: () => AbnormalTermination,
226
+ BrutalShutdown: () => BrutalShutdown,
227
+ CauseReport: () => CauseReport,
228
+ DeadlineMissedReport: () => DeadlineMissedReport,
229
+ ExitReport: () => ExitReport,
230
+ FailureReport: () => FailureReport,
231
+ GracefulShutdown: () => GracefulShutdown,
232
+ GroupStopGuarantee: () => GroupStopGuarantee,
233
+ InferredReport: () => InferredReport,
234
+ InfinityShutdown: () => InfinityShutdown,
235
+ MediumDeclaration: () => MediumDeclaration,
236
+ MediumPort: () => MediumPort,
237
+ MediumReporting: () => MediumReporting,
238
+ NormalTermination: () => NormalTermination,
239
+ ShutdownMode: () => ShutdownMode,
240
+ ShutdownTermination: () => ShutdownTermination,
241
+ StartedTypeId: () => StartedTypeId,
242
+ StoppedTypeId: () => StoppedTypeId,
243
+ TerminationReason: () => TerminationReason,
244
+ make: () => make$1,
245
+ started: () => started,
246
+ stopped: () => stopped
247
+ });
248
+ const StartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/Medium/Started");
249
+ const StoppedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/Medium/Stopped");
250
+ /** Mint `Started` evidence for a child whose readiness completes `ready`. */
251
+ const started = (ready) => ({
252
+ [StartedTypeId]: StartedTypeId,
253
+ ready
254
+ });
255
+ /** The single `Stopped` evidence value every medium returns from `stop`. */
256
+ const stopped = { [StoppedTypeId]: StoppedTypeId };
257
+ /**
258
+ * KTD8: a medium exists only through `make`, whose options record requires every
259
+ * obligation. `stop` is wrapped in an uninterruptible region, so owned shutdown
260
+ * honouring R4's modes cannot be interrupted part-way (R15).
261
+ */
262
+ const make$1 = (options) => ({
263
+ ...options,
264
+ stop: (evidence, mode) => Effect.uninterruptible(options.stop(evidence, mode))
153
265
  });
266
+ /** Declare a medium port keyed to the program type it interprets (KTD9). */
267
+ const MediumPort = (key) => Context.Service(key);
154
268
  //#endregion
155
- //#region src/DaemonSubscription.ts
156
- const orEmpty = (value) => {
157
- if (typeof value === "undefined") return {};
158
- return value;
159
- };
160
- const subscription$1 = (opts) => ({
161
- [WorkerTypeId]: WorkerTypeId,
162
- name: opts.name,
163
- loop: {
164
- ...SubscriptionLoopTag,
165
- acquire: Effect.asVoid(opts.acquire)
269
+ //#region src/Supervisor/FiberMedium.ts
270
+ var FiberMedium_exports = /* @__PURE__ */ __exportAll({
271
+ failureCauseOf: () => failureCauseOf,
272
+ fiberPort: () => fiberPort,
273
+ medium: () => medium,
274
+ mediumFor: () => mediumFor,
275
+ readyOnStart: () => readyOnStart
276
+ });
277
+ const readyOnStart = (program) => (ready) => Effect.andThen(ready, program);
278
+ const fiberPort = MediumPort("FiberMedium");
279
+ const FiberStartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/FiberMedium/Started");
280
+ const fiberStarted = (fiber, scope, ready) => ({
281
+ [StartedTypeId]: StartedTypeId,
282
+ [FiberStartedTypeId]: FiberStartedTypeId,
283
+ fiber,
284
+ ready,
285
+ scope
286
+ });
287
+ const isFiberStarted = (evidence) => FiberStartedTypeId in evidence;
288
+ const fiberOf = (evidence) => Option.liftPredicate(evidence, isFiberStarted);
289
+ const normalTermination = { _tag: "Normal" };
290
+ const shutdownTermination = { _tag: "Shutdown" };
291
+ const abnormalOf = (cause) => ({
292
+ _tag: "Abnormal",
293
+ report: {
294
+ _tag: "CauseReport",
295
+ cause: Cause.pretty(cause)
296
+ }
297
+ });
298
+ const terminationOf$1 = (exit) => Exit.match(exit, {
299
+ onSuccess: () => normalTermination,
300
+ onFailure: (cause) => Cause.hasInterruptsOnly(cause) ? shutdownTermination : abnormalOf(cause)
301
+ });
302
+ const closedChild = (self) => Scope.close(self.scope, Exit.void);
303
+ 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);
311
+ const failureCauseOf = (evidence) => Option.map(fiberOf(evidence), (self) => Effect.map(Fiber.await(self.fiber), Exit.getCause));
312
+ const mediumFor = () => make$1({
313
+ declaration: {
314
+ reporting: "full",
315
+ groupStop: "atomic"
166
316
  },
167
- child: orEmpty(opts.child),
168
- tick: opts.tick,
169
- tickHooks: orEmpty(opts.tickHooks),
170
- lock: opts.lock
317
+ start: (program) => Effect.gen(function* () {
318
+ const scope = yield* Effect.scope;
319
+ const signalled = yield* Deferred.make();
320
+ const fiber = yield* Effect.forkIn(program(Deferred.succeed(signalled, void 0)), scope);
321
+ return fiberStarted(fiber, scope, Deferred.await(signalled));
322
+ }),
323
+ report: (evidence) => Option.match(fiberOf(evidence), {
324
+ onNone: () => Effect.succeed(shutdownTermination),
325
+ onSome: (self) => Effect.map(Fiber.await(self.fiber), terminationOf$1)
326
+ }),
327
+ probe: (evidence) => Option.match(fiberOf(evidence), {
328
+ onNone: () => Effect.succeed(false),
329
+ onSome: (self) => Effect.sync(() => self.fiber.pollUnsafe() === void 0)
330
+ }),
331
+ stop: (evidence, mode) => Option.match(fiberOf(evidence), {
332
+ onNone: () => Effect.succeed(stopped),
333
+ onSome: (self) => Effect.as(stopOf(self, mode), stopped)
334
+ })
171
335
  });
336
+ const medium = mediumFor();
172
337
  //#endregion
173
- //#region src/LeaderLock.schema.ts
174
- var LeaderLockNotAcquired = class extends Schema.TaggedError()("LeaderLockNotAcquired", { key: Schema.String }) {};
175
- var LeaderLockInfraError = class extends Schema.TaggedError()("LeaderLockInfraError", {
176
- key: Schema.String,
177
- cause: Schema.Unknown
178
- }) {};
179
- //#endregion
180
- //#region src/LockPrimitive.schema.ts
181
- var LockPrimitiveError = class extends Schema.TaggedError()("LockPrimitiveError", {
182
- key: Schema.String,
183
- cause: Schema.Unknown
184
- }) {};
185
- //#endregion
186
- //#region src/LeaderLockAdapter.ts
187
- var LeaderLock = class LeaderLock extends Context.Service()("@systemfsoftware/effect-daemon-spec/LeaderLockAdapter/LeaderLock") {
188
- static Noop = Layer.succeed(LeaderLock, LeaderLock.of({ withLock: (_key, self) => Effect.asSome(self) }));
189
- };
190
- var LockPrimitive = class extends Context.Service()("@systemfsoftware/effect-daemon-spec/LeaderLockAdapter/LockPrimitive") {};
191
- const LeaderLockFromPrimitive = Layer.effect(LeaderLock, Effect.gen(function* () {
192
- const primitive = yield* LockPrimitive;
193
- return LeaderLock.of({ withLock: (key, self) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
194
- const scope = yield* Scope.make();
195
- if (!(yield* restore(primitive.tryAcquire(key)).pipe(Scope.provide(scope), Effect.mapError((cause) => LeaderLockInfraError.make({
196
- key,
197
- cause
198
- })), Effect.onError(() => Scope.close(scope, Exit.void))))) {
199
- yield* Scope.close(scope, Exit.void);
200
- return Option.none();
201
- }
202
- const result = yield* restore(self).pipe(Effect.ensuring(Scope.close(scope, Exit.void)));
203
- return Option.some(result);
204
- })) });
205
- }));
206
- //#endregion
207
- //#region src/internal/AllocateSupervisorHealth.ts
208
- /** @internal */
209
- const allocateSupervisorHealth = Function.dual(2, (name, children) => Effect.gen(function* () {
210
- const ready = yield* Latch.make(false);
211
- const healthy = yield* Latch.make(true);
212
- const paused = yield* Latch.make(true);
213
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
214
- daemon: name,
215
- latch: "ready"
216
- }), 0);
217
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
218
- daemon: name,
219
- latch: "healthy"
220
- }), 1);
221
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
222
- daemon: name,
223
- latch: "paused"
224
- }), 1);
225
- return {
226
- name,
227
- ready,
228
- healthy,
229
- paused,
230
- children
231
- };
232
- }));
233
- //#endregion
234
- //#region src/internal/AllocateWorkerHealth.ts
235
- /** @internal */
236
- const allocateWorkerHealth = (name) => Effect.gen(function* () {
237
- const ready = yield* Latch.make(false);
238
- const healthy = yield* Latch.make(true);
239
- const paused = yield* Latch.make(true);
240
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
241
- daemon: name,
242
- latch: "ready"
243
- }), 0);
244
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
245
- daemon: name,
246
- latch: "healthy"
247
- }), 1);
248
- yield* Metric.update(Metric.withAttributes(healthStateGauge, {
249
- daemon: name,
250
- latch: "paused"
251
- }), 1);
252
- return {
253
- name,
254
- ready,
255
- healthy,
256
- paused
257
- };
338
+ //#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
+ }
258
345
  });
259
- //#endregion
260
- //#region src/internal/BuildWorkerLoop.ts
261
- const applySpanAttributes = (hooks) => {
262
- const { spanAttributes } = hooks;
263
- return (effect) => {
264
- if (typeof spanAttributes === "undefined") return effect;
265
- return Effect.tap(effect, () => Effect.orElseSucceed(spanAttributes, () => ({})).pipe(Effect.flatMap(Effect.annotateCurrentSpan)));
266
- };
267
- };
268
- const applyTrackDuration = (hooks) => {
269
- const { trackDuration } = hooks;
270
- return (effect) => {
271
- if (typeof trackDuration === "undefined") return effect;
272
- return Effect.trackDuration(effect, trackDuration);
273
- };
274
- };
275
- const applyTimeout = (timeout) => (effect) => effect.pipe(Effect.timeout(timeout), Effect.catchTag("TimeoutError", () => Effect.fail(new Cause.TimeoutError())));
276
- const applyInnerRetry = (hooks) => {
277
- const { innerRetry } = hooks;
278
- return (effect) => {
279
- if (typeof innerRetry === "undefined") return effect;
280
- return Effect.retry(effect, innerRetry);
281
- };
282
- };
283
- const openReadyGauge = (gauge, name) => Metric.update(Metric.withAttributes(gauge, {
284
- daemon: name,
285
- latch: "ready"
286
- }), 1);
287
- const buildPollTick = (worker, health, gate, readyGauge) => {
288
- const spanName = worker.tick.spanName ?? "daemon.tick";
289
- const withSpanAttrs = applySpanAttributes(worker.tickHooks);
290
- const withDuration = applyTrackDuration(worker.tickHooks);
291
- const withTimeout = applyTimeout(worker.tick.tickTimeout);
292
- const withInnerRetry = applyInnerRetry(worker.tickHooks);
293
- const runWork = (work) => work.pipe(withSpanAttrs, withDuration, Effect.withSpan(spanName, {
294
- root: true,
295
- attributes: { "daemon.name": worker.name }
296
- }), Effect.withLogSpan(spanName));
297
- return withInnerRetry(withTimeout(Effect.andThen(health.paused.await, gate).pipe(Effect.flatMap(Option.match({
298
- onNone: () => Effect.void,
299
- onSome: runWork
300
- }))))).pipe(Effect.tap(() => Effect.andThen(health.ready.open, openReadyGauge(readyGauge, worker.name))), Effect.asVoid);
301
- };
302
- const wrapSpan = (worker, effect, spanName) => {
303
- const finalSpan = spanName ?? "daemon.worker";
304
- return effect.pipe(Effect.withSpan(finalSpan, {
305
- root: true,
306
- attributes: { "daemon.name": worker.name }
307
- }), Effect.withLogSpan(finalSpan));
308
- };
309
- const buildPollLoop = (worker, loop, health, readyGauge) => {
310
- const tick = buildPollTick(worker, health, loop.gate, readyGauge);
311
- return Effect.repeat(tick, Schedule.spaced(loop.interval)).pipe(Effect.asVoid);
312
- };
313
- const propagateExit = (exit) => Match.value(exit).pipe(Match.tag("Failure", ({ cause }) => Effect.failCause(cause)), Match.orElse(() => Effect.void));
314
- const buildStreamLoop = (worker, loop, health, readyGauge) => {
315
- const body = Effect.gen(function* () {
316
- yield* health.paused.await;
317
- const fiber = yield* Effect.forkScoped(loop.stream.pipe(Stream.tap(() => Effect.andThen(health.ready.open, openReadyGauge(readyGauge, worker.name))), Stream.runDrain), { startImmediately: true });
318
- const ready = applyTimeout(worker.tick.tickTimeout)(health.ready.await);
319
- yield* Effect.raceFirst(ready, Fiber.await(fiber).pipe(Effect.flatMap(propagateExit)));
320
- yield* Fiber.await(fiber).pipe(Effect.flatMap(propagateExit));
321
- });
322
- const retried = applyInnerRetry(worker.tickHooks)(body);
323
- return wrapSpan(worker, retried.pipe(Effect.asVoid));
324
- };
325
- const buildSubscriptionLoop = (worker, loop, health, readyGauge) => {
326
- const body = Effect.gen(function* () {
327
- yield* health.paused.await;
328
- yield* applyTimeout(worker.tick.tickTimeout)(loop.acquire);
329
- yield* Effect.andThen(health.ready.open, openReadyGauge(readyGauge, worker.name));
330
- return yield* Effect.never;
331
- });
332
- return wrapSpan(worker, body.pipe(Effect.asVoid));
333
- };
334
- /** @internal */
335
- const buildWorkerLoop = Function.dual(3, (worker, health, readyGauge) => Match.value(worker.loop).pipe(Match.tag("Poll", (loop) => buildPollLoop(worker, loop, health, readyGauge)), Match.tag("Stream", (loop) => buildStreamLoop(worker, loop, health, readyGauge)), Match.tag("Subscription", (loop) => buildSubscriptionLoop(worker, loop, health, readyGauge)), Match.exhaustive));
336
- //#endregion
337
- //#region src/RunDynamic.ts
338
- const buildDynamic = (spec, health) => Effect.gen(function* () {
339
- const state = yield* Ref.make({
340
- nextId: 0,
341
- children: HashMap.empty()
342
- });
343
- const startChildImpl = (args) => Effect.gen(function* () {
344
- const childWorker = spec.child(args);
345
- const workerHealth = yield* allocateWorkerHealth(childWorker.name);
346
- const loop = buildWorkerLoop(childWorker, workerHealth, healthStateGauge).pipe(Effect.orDie);
347
- const removed = yield* Latch.make(false);
348
- const reservedId = yield* Ref.modify(state, (current) => {
349
- if (HashMap.size(current.children) >= spec.maxChildren) return [Option.none(), current];
350
- const children = HashMap.set(current.children, current.nextId, Equal.byReferenceUnsafe({
351
- fiber: Option.none(),
352
- removed
353
- }));
354
- return [Option.some(current.nextId), {
355
- nextId: current.nextId + 1,
356
- children
357
- }];
358
- });
359
- if (Option.isNone(reservedId)) return yield* DynamicLimitExceeded.make({ limit: spec.maxChildren });
360
- const id = reservedId.value;
361
- yield* Metric.update(supervisorChildrenGauge, HashMap.size(yield* Ref.get(state).pipe(Effect.map((s) => s.children))));
362
- const cleanup = Effect.gen(function* () {
363
- const count = yield* Ref.modify(state, (current) => {
364
- const children = HashMap.remove(current.children, id);
365
- return [HashMap.size(children), {
366
- ...current,
367
- children
368
- }];
369
- });
370
- yield* Metric.update(supervisorChildrenGauge, count);
371
- yield* removed.open;
372
- }).pipe(Effect.asVoid);
373
- const fiber = yield* Effect.forkScoped(loop.pipe(Effect.ensuring(cleanup)));
374
- const count = yield* Ref.modify(state, (current) => {
375
- const childOpt = HashMap.get(current.children, id);
376
- if (Option.isNone(childOpt)) return [HashMap.size(current.children), current];
377
- const children = HashMap.set(current.children, id, Equal.byReferenceUnsafe({
378
- ...childOpt.value,
379
- fiber: Option.some(fiber)
380
- }));
381
- return [HashMap.size(children), {
382
- nextId: current.nextId,
383
- children
384
- }];
385
- });
386
- yield* Metric.update(supervisorChildrenGauge, count);
387
- return {
388
- id,
389
- removed: removed.await
390
- };
391
- });
392
- const stopChildImpl = (ref) => Effect.gen(function* () {
393
- const [stateOpt, count] = yield* Ref.modify(state, (current) => {
394
- const found = HashMap.get(current.children, ref.id);
395
- const children = HashMap.remove(current.children, ref.id);
396
- return [[found, HashMap.size(children)], {
397
- ...current,
398
- children
399
- }];
400
- });
401
- if (Option.isSome(stateOpt)) {
402
- const { fiber, removed } = stateOpt.value;
403
- yield* Option.match(fiber, {
404
- onNone: () => Effect.void,
405
- onSome: (running) => Effect.gen(function* () {
406
- yield* Fiber.interrupt(running);
407
- yield* Fiber.await(running);
408
- })
409
- });
410
- yield* Metric.update(supervisorChildrenGauge, count);
411
- yield* removed.open;
412
- }
346
+ const reasonOf = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => ({
347
+ _tag: "Abnormal",
348
+ report: {
349
+ _tag: "CauseReport",
350
+ cause: Cause.pretty(cause)
351
+ }
352
+ }));
353
+ const startOf = (program, medium, context) => Effect.gen(function* () {
354
+ const parent = yield* Effect.scope;
355
+ const child = yield* Scope.fork(parent);
356
+ const scoped = Context.add(context, Scope.Scope, child);
357
+ const outcome = yield* Effect.exit(Effect.setContext(Effect.mapError(medium.start(program), rendered), scoped));
358
+ 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)))
413
361
  });
414
- const countImpl = Ref.get(state).pipe(Effect.map((current) => HashMap.size(current.children)));
415
- yield* Effect.andThen(health.ready.open, Metric.update(Metric.withAttributes(healthStateGauge, {
416
- daemon: spec.name,
417
- latch: "ready"
418
- }), 1));
419
- return {
420
- health,
421
- startChild: startChildImpl,
422
- stopChild: stopChildImpl,
423
- count: countImpl
424
- };
425
362
  });
426
- const dynamic$1 = (spec) => Effect.gen(function* () {
427
- const health = yield* allocateSupervisorHealth(spec.name, []);
428
- return yield* buildDynamic(spec, health);
363
+ const bind = (program, medium, context) => ({
364
+ 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)
429
368
  });
430
- //#endregion
431
- //#region src/internal/RestartDecision.schema.ts
432
- /** @internal */
433
- const RestartStrategy = Schema.Literals([
434
- "one_for_one",
435
- "one_for_all",
436
- "rest_for_one"
437
- ]);
438
369
  /**
439
- * The cross-field invariant the command carries: a failed child's index addresses one of
440
- * the children that exist.
441
- *
442
- * It is a named function rather than an inline `Schema.filter` arrow because naming it makes
443
- * it reachable by this file's property block, which an inline arrow is not. It is not
444
- * exported: a `*.schema.ts` declares schemas and the vocabulary they are built from, never
445
- * loose functions, and nothing outside this module needs it.
446
- *
447
- * It lives here rather than beside the decision because the decision now imports
448
- * `DecideInput` as a *value* — `Workflow.make` constrains its command argument on the class
449
- * itself — so the dependency between these two modules has to run one way only. With the
450
- * predicate on the other side, both load orders reach a temporal dead zone: whichever module
451
- * evaluates first suspends on the other, and the name it needs at module scope is not yet
452
- * initialised.
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).
453
374
  */
454
- const failedIndexAddressesAChild = (input) => input.failedIndex < input.totalChildren;
455
- /**
456
- * The message the cross-field filter reports. One binding, referenced by the filter and
457
- * by the law that asserts on it: a second copy would let the law pass against a message
458
- * the schema no longer produces, which is the whole failure the law exists to catch.
459
- */
460
- const BOUND_MESSAGE = "failedIndex must be < totalChildren";
375
+ const Binder = { bind };
376
+ //#endregion
377
+ //#region src/Supervisor/running-supervisor.handle.ts
378
+ /** Brands a running supervisor handle. */
379
+ const TypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/RunningSupervisor");
380
+ const RunningSupervisorDef = Handle.make()(TypeId);
381
+ /** Whether a value is a running supervisor handle. */
382
+ const isRunningSupervisor = RunningSupervisorDef.is;
383
+ const RunningSupervisorHandle = { make: (name, initial, children, context, fiber) => Effect.gen(function* () {
384
+ const scope = yield* Effect.scope;
385
+ const slot = {
386
+ state: yield* Ref.make(initial),
387
+ mailbox: yield* Queue.unbounded(),
388
+ trace: yield* PubSub.unbounded(),
389
+ evidence: yield* Ref.make(HashMap.empty()),
390
+ replies: yield* Ref.make(HashMap.empty()),
391
+ boundChildren: yield* Ref.make(children),
392
+ pending: yield* Ref.make(HashMap.empty()),
393
+ requests: yield* Ref.make(0),
394
+ terminated: yield* Deferred.make(),
395
+ scope,
396
+ context,
397
+ fiber
398
+ };
399
+ return RunningSupervisorDef.make({ name }, slot);
400
+ }) };
401
+ const stateOf = (self) => RunningSupervisorDef.slot(self).state;
402
+ const mailboxOf = (self) => RunningSupervisorDef.slot(self).mailbox;
403
+ const tracePubSubOf = (self) => RunningSupervisorDef.slot(self).trace;
404
+ const evidenceOf = (self) => RunningSupervisorDef.slot(self).evidence;
405
+ const repliesOf = (self) => RunningSupervisorDef.slot(self).replies;
406
+ const boundChildrenOf = (self) => RunningSupervisorDef.slot(self).boundChildren;
407
+ const pendingChildrenOf = (self) => RunningSupervisorDef.slot(self).pending;
408
+ const fiberContextOf = (self) => RunningSupervisorDef.slot(self).context;
409
+ const fiberMediumOf$1 = (self) => RunningSupervisorDef.slot(self).fiber;
410
+ /** The fiber medium bound to `program`, ready to be stored as a dynamic child. */
411
+ const boundFiberProgramOf = (self, program) => Binder.bind(program, fiberMediumOf$1(self), fiberContextOf(self));
412
+ const terminatedLatchOf = (self) => RunningSupervisorDef.slot(self).terminated;
413
+ const ownerScopeOf = (self) => RunningSupervisorDef.slot(self).scope;
461
414
  /**
462
- * Constructive generation for the cross-field invariant. `failedIndexSeed` is independent
463
- * of `totalChildren` and always in `0 .. MAX-1`; the command's `failedIndex` is that seed
464
- * modulo `totalChildren`, so every generated sample satisfies `failedIndex < totalChildren`.
465
- *
466
- * `FilterConstraint` cannot express a relation between two fields. rc.116's constructor
467
- * for that case is `toCodecArbitrary`, not an empty `arbitraryConstraint`.
415
+ * The kernel trace: every step's decoded event and decision, in mailbox order,
416
+ * from the moment the stream is subscribed.
468
417
  */
469
- const DecideInputGenerated = Schema.Struct({
470
- strategy: RestartStrategy,
471
- totalChildren: Schema.Int.pipe(Schema.check(Schema.isBetween({
472
- minimum: 1,
473
- maximum: MAX_CHILDREN_CEILING
474
- }))),
475
- failedIndexSeed: Schema.Int.pipe(Schema.check(Schema.isBetween({
476
- minimum: 0,
477
- maximum: 999
478
- }))),
479
- exitSuccess: Schema.Boolean,
480
- intensityExceeded: Schema.Boolean
481
- });
482
- const commandFromGenerated = (generated) => ({
483
- strategy: generated.strategy,
484
- totalChildren: generated.totalChildren,
485
- failedIndex: generated.failedIndexSeed % generated.totalChildren,
486
- exitSuccess: generated.exitSuccess,
487
- intensityExceeded: generated.intensityExceeded
488
- });
489
- const generatedFromCommand = (command) => ({
490
- strategy: command.strategy,
491
- totalChildren: command.totalChildren,
492
- failedIndexSeed: command.failedIndex,
493
- exitSuccess: command.exitSuccess,
494
- intensityExceeded: command.intensityExceeded
418
+ const traceOf = (self) => Stream.fromPubSub(RunningSupervisorDef.slot(self).trace);
419
+ /** The supervisor's current phase and children, as the kernel last folded them. */
420
+ const statusOf = (self) => Ref.get(RunningSupervisorDef.slot(self).state);
421
+ const offerEvent = dual(2, (self, event) => Effect.asVoid(Queue.offer(RunningSupervisorDef.slot(self).mailbox, event)));
422
+ const shutdownEventOf = (now) => ({
423
+ _tag: "ShutdownRequested",
424
+ at: now,
425
+ reason: { _tag: "Shutdown" }
495
426
  });
427
+ /** Completes once the supervisor has terminated; fails when it gave up. */
428
+ const awaitTerminated = (self) => Deferred.await(RunningSupervisorDef.slot(self).terminated);
496
429
  /**
497
- * The command's field map and cross-field check, named so the class below extends a binding
498
- * rather than an inline factory call. An anonymous base adds a new `ae-forgotten-export`
499
- * `*_base` warning to the committed API report, which this package fixes at the source
500
- * instead of suppressing.
501
- *
502
- * `failedIndex` is at most `MAX_CHILDREN_CEILING - 1` because it must be strictly less
503
- * than `totalChildren`, whose own maximum is the ceiling.
504
- *
505
- * The struct-level cross-field filter relies on Effect's native rejection
506
- * sampling. Constructive generation lives at the class level via
507
- * `toCodecArbitrary` on `DecideInput` below.
430
+ * Asks the supervisor to shut down and waits until it has terminated: children stop
431
+ * in reverse start order through their media before this completes.
508
432
  */
509
- const DecideInputBase = Schema.Struct({
510
- strategy: RestartStrategy,
511
- totalChildren: Schema.Int.pipe(Schema.check(Schema.isBetween({
512
- minimum: 1,
513
- maximum: MAX_CHILDREN_CEILING
514
- }))),
515
- failedIndex: Schema.Int.pipe(Schema.check(Schema.isBetween({
516
- minimum: 0,
517
- maximum: 999
518
- }))),
519
- exitSuccess: Schema.Boolean,
520
- intensityExceeded: Schema.Boolean
521
- }).check(Schema.makeFilter(failedIndexAddressesAChild, { message: BOUND_MESSAGE }));
433
+ const shutdown = (self) => Effect.uninterruptibleMask((restore) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.andThen(Queue.offer(RunningSupervisorDef.slot(self).mailbox, shutdownEventOf(now)), restore(Deferred.await(RunningSupervisorDef.slot(self).terminated)))));
434
+ const nextRequestId = (self, kind) => Effect.map(Ref.getAndUpdate(RunningSupervisorDef.slot(self).requests, (count) => count + 1), (count) => `${kind}-${count}`);
435
+ const awaitReply = (self, requestId, eventOf) => Effect.flatMap(Deferred.make(), (waiter) => Effect.andThen(Ref.update(RunningSupervisorDef.slot(self).replies, (known) => HashMap.set(known, requestId, waiter)), Effect.flatMap(Clock.currentTimeMillis, (now) => {
436
+ const event = eventOf(now);
437
+ return Effect.andThen(Queue.offer(RunningSupervisorDef.slot(self).mailbox, event), Effect.raceFirst(Deferred.await(waiter), Effect.andThen(awaitTerminated(self), resolveWaiting(RunningSupervisorDef.slot(self).replies, requestId, staleOf(event))).pipe(Effect.andThen(Deferred.await(waiter)))));
438
+ })));
522
439
  /**
523
- * The restart command. A `Schema.Class` rather than a `Schema.Struct` because `Workflow.make`
524
- * constrains its `command` on the class itself — a struct carries no `identifier` and no
525
- * `extend`, and the constraint refuses it. Every field schema and the cross-field check are
526
- * the ones the struct carried.
527
- *
528
- * Class-level `toCodecArbitrary` is what `Arbitrary.schema(DecideInput)` compiles. The
529
- * self-reference is `Schema.suspend`, the same delay recursive schemas use: the thunk
530
- * runs at derivation time, after the class exists. The return type is `SchemaAST.Link`
531
- * so the heritage expression does not infer a cycle through `DecideInput`.
440
+ * Starts a dynamic child running `program`. The supervisor allocates its id and
441
+ * answers `accepted` with that id, or `refused` at the declared ceiling.
532
442
  */
533
- /** @internal */
534
- var DecideInput = class DecideInput extends Schema.Class("DecideInput")(DecideInputBase, { toCodecArbitrary: () => Schema.link()(DecideInputGenerated, {
535
- decode: SchemaGetter.transform((generated) => new DecideInput(commandFromGenerated(generated))),
536
- encode: SchemaGetter.transform(generatedFromCommand)
537
- }) }) {
538
- static [Workflow.InstrumentationBrand] = { strategy: "daemon.restart.strategy" };
539
- };
540
- //#endregion
541
- //#region src/internal/choose-restart-strategy.workflow.ts
443
+ const startChild = dual(2, (self, program) => Effect.flatMap(nextRequestId(self, "start"), (requestId) => Effect.andThen(Ref.update(RunningSupervisorDef.slot(self).pending, (pending) => HashMap.set(pending, requestId, boundFiberProgramOf(self, program))), awaitReply(self, requestId, (now) => ({
444
+ _tag: "DynamicStartRequested",
445
+ at: now,
446
+ requestId
447
+ })))));
542
448
  /**
543
- * The child indices a restart covers, by supervision strategy.
544
- *
545
- * A pure total function: the one part of the restart decision that is computation rather
546
- * than dispatch, so it lives in the decision cell beside the `Workflow.make` it serves.
449
+ * Stops the dynamic child's named incarnation and removes it. Answers `stopped`, or
450
+ * `missed` when that incarnation is no longer current.
547
451
  */
548
- /** @internal */
549
- const restartIndicesFor = (strategy, failedIndex, total) => Match$1.value(strategy).pipe(Match$1.when("one_for_one", () => [failedIndex]), Match$1.when("one_for_all", () => Arr.range(0, total - 1)), Match$1.when("rest_for_one", () => Arr.range(failedIndex, total - 1)), Match$1.exhaustive);
550
- const RestartDecisionTypeId = Symbol.for("@systemfsoftware/effect-daemon/RestartDecision");
551
- /** @internal */
552
- var RestartDecisionContinue = class extends S.TaggedClass()("Continue", {}) {
553
- [RestartDecisionTypeId] = RestartDecisionTypeId;
554
- };
555
- /** @internal */
556
- var RestartDecisionRestart = class extends S.TaggedClass()("Restart", { indices: S.NonEmptyArray(S.Int) }) {
557
- [RestartDecisionTypeId] = RestartDecisionTypeId;
558
- };
559
- /** @internal */
560
- var RestartDecisionExhausted = class extends S.TaggedError()("Exhausted", {}) {
561
- [RestartDecisionTypeId] = RestartDecisionTypeId;
452
+ const stopChild = dual(3, (self, childId, generation) => Effect.flatMap(nextRequestId(self, "stop"), (requestId) => awaitReply(self, requestId, (now) => ({
453
+ _tag: "DynamicStopRequested",
454
+ at: now,
455
+ requestId,
456
+ childId,
457
+ generation
458
+ }))));
459
+ const resolveWaiting = (replies, requestId, outcome) => Effect.flatMap(Ref.modify(replies, (pending) => [HashMap.get(pending, requestId), HashMap.remove(pending, requestId)]), Option.match({
460
+ onNone: () => Effect.void,
461
+ onSome: (waiter) => Effect.asVoid(Deferred.succeed(waiter, outcome))
462
+ }));
463
+ const staleOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, () => ({ outcome: "refused" })), Match.orElse(() => ({ outcome: "missed" })));
464
+ const Ops = {
465
+ resolveWaiting,
466
+ staleOf
562
467
  };
468
+ //#endregion
469
+ //#region src/kernel/initial-supervisor-state.ts
470
+ const initialStateOf = (policy) => ({
471
+ policy,
472
+ children: Array.map(policy.childDeclarations, (declaration) => ({
473
+ childId: declaration.childId,
474
+ generation: 0,
475
+ status: "starting",
476
+ consecutiveRestarts: 0,
477
+ probeFailures: 0
478
+ })),
479
+ restartStamps: [],
480
+ nextOrdinal: 0
481
+ });
482
+ //#endregion
483
+ //#region src/kernel/SupervisionEvent.schema.ts
484
+ const TimerKind = Schema.Literals([
485
+ "start_deadline",
486
+ "backoff",
487
+ "liveness_tick",
488
+ "cool_down"
489
+ ]);
490
+ const ChildTimerTarget = Schema.TaggedStruct("ChildTimer", {
491
+ childId: ChildId,
492
+ generation: Generation
493
+ });
494
+ const SupervisorTimerTarget = Schema.TaggedStruct("SupervisorTimer", {});
495
+ const TimerTarget = Schema.Union([ChildTimerTarget, SupervisorTimerTarget]);
563
496
  /**
564
- * The decision channel: the two outcomes a cooldown-or-restart choice is made between, as
565
- * one schema the workflow declares. The error channel carries `RestartDecisionExhausted`, so
566
- * the compiler holds the three-way dispatch over the encoded tags of both channels.
497
+ * The boot event: the handle enqueues exactly one as its first envelope, so the
498
+ * declared children start by an ordinary kernel decision rather than by builder
499
+ * logic. It carries no child identity because it names them all, in declared order.
567
500
  */
568
- /** @internal */
569
- const RestartDecision = S.Union([RestartDecisionContinue, RestartDecisionRestart]);
570
- /** @internal */
571
- const chooseRestartStrategy = Workflow.make({
572
- command: DecideInput,
573
- decision: RestartDecision,
574
- error: RestartDecisionExhausted,
575
- decide: (command) => Match$1.value(command).pipe(Match$1.when({ exitSuccess: true }, () => Result$1.succeed(RestartDecisionContinue.make())), Match$1.when({
576
- exitSuccess: false,
577
- intensityExceeded: true
578
- }, () => Result$1.fail(RestartDecisionExhausted.make())), Match$1.orElse(() => Result$1.succeed(RestartDecisionRestart.make({ indices: restartIndicesFor(command.strategy, command.failedIndex, command.totalChildren) }))))
501
+ const SupervisorStarted = Schema.TaggedStruct("SupervisorStarted", { at: EventTime });
502
+ const ChildStarted = Schema.TaggedStruct("ChildStarted", {
503
+ at: EventTime,
504
+ childId: ChildId,
505
+ generation: Generation
506
+ });
507
+ const ChildReady = Schema.TaggedStruct("ChildReady", {
508
+ at: EventTime,
509
+ childId: ChildId,
510
+ generation: Generation
511
+ });
512
+ const ChildTerminated = Schema.TaggedStruct("ChildTerminated", {
513
+ at: EventTime,
514
+ childId: ChildId,
515
+ generation: Generation,
516
+ reason: TerminationReason
517
+ });
518
+ const ChildStopped = Schema.TaggedStruct("ChildStopped", {
519
+ at: EventTime,
520
+ childId: ChildId,
521
+ generation: Generation
522
+ });
523
+ const ProbeResult = Schema.TaggedStruct("ProbeResult", {
524
+ at: EventTime,
525
+ childId: ChildId,
526
+ generation: Generation,
527
+ alive: Schema.Boolean
579
528
  });
529
+ const TimerElapsed = Schema.TaggedStruct("TimerElapsed", {
530
+ at: EventTime,
531
+ kind: TimerKind,
532
+ target: TimerTarget
533
+ });
534
+ const DynamicStartRequested = Schema.TaggedStruct("DynamicStartRequested", {
535
+ at: EventTime,
536
+ requestId: RequestId
537
+ });
538
+ const DynamicStopRequested = Schema.TaggedStruct("DynamicStopRequested", {
539
+ at: EventTime,
540
+ requestId: RequestId,
541
+ childId: ChildId,
542
+ generation: Generation
543
+ });
544
+ const ShutdownRequested = Schema.TaggedStruct("ShutdownRequested", {
545
+ at: EventTime,
546
+ reason: TerminationReason
547
+ });
548
+ const SupervisionEvent = Schema.Union([
549
+ SupervisorStarted,
550
+ ChildStarted,
551
+ ChildReady,
552
+ ChildTerminated,
553
+ ChildStopped,
554
+ ProbeResult,
555
+ TimerElapsed,
556
+ DynamicStartRequested,
557
+ DynamicStopRequested,
558
+ ShutdownRequested
559
+ ]);
580
560
  //#endregion
581
- //#region src/internal/IntensityWindow.ts
582
- /** @internal */
583
- const isWithinWindow = Function.dual(3, (t, now, windowMillis) => now - t <= windowMillis);
584
- const keepWithin = (now, windowMillis) => (ts) => ts.filter(isWithinWindow(now, windowMillis));
585
- /** @internal */
586
- const pruneTimestamps = Function.dual(3, (ts, now, windowMillis) => keepWithin(now, windowMillis)(ts));
587
- /** @internal */
588
- const recordTimestamp = Function.dual(3, (ts, now, windowMillis) => [now, ...pruneTimestamps(ts, now, windowMillis)]);
589
- /** @internal */
590
- const exceedsRestarts = Function.dual(2, (count, restarts) => count > restarts);
561
+ //#region src/kernel/SupervisionTypeIds.ts
562
+ const DecisionTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionDecision");
563
+ const StateTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisorState");
591
564
  //#endregion
592
- //#region src/internal/Intensity.ts
593
- /** @internal */
594
- const neverExceeds = {
595
- record: Effect.void,
596
- isExceeded: Effect.succeed(false),
597
- count: Effect.succeed(0)
598
- };
599
- /** @internal */
600
- const make = Function.dual(2, (restarts, window) => Effect.gen(function* () {
601
- const windowMillis = Duration.toMillis(window);
602
- const timestamps = yield* Ref.make([]);
603
- const prune = (now) => Ref.modify(timestamps, (ts) => {
604
- const active = pruneTimestamps(ts, now, windowMillis);
605
- return [active, active];
606
- });
607
- return {
608
- record: Effect.gen(function* () {
609
- const now = yield* Clock.currentTimeMillis;
610
- yield* Ref.update(timestamps, (ts) => recordTimestamp(ts, now, windowMillis));
611
- }),
612
- isExceeded: Effect.gen(function* () {
613
- const now = yield* Clock.currentTimeMillis;
614
- const active = yield* prune(now);
615
- return exceedsRestarts(active.length, restarts);
616
- }),
617
- count: Effect.gen(function* () {
618
- const now = yield* Clock.currentTimeMillis;
619
- return (yield* prune(now)).length;
620
- })
621
- };
622
- }));
565
+ //#region src/kernel/SupervisorCommand.schema.ts
566
+ const StartChild = Schema.TaggedStruct("StartChild", {
567
+ childId: ChildId,
568
+ generation: Generation
569
+ });
570
+ const StopChild = Schema.TaggedStruct("StopChild", {
571
+ childId: ChildId,
572
+ generation: Generation,
573
+ shutdown: ShutdownMode
574
+ });
575
+ const ArmChildTimer = Schema.TaggedStruct("ArmChildTimer", {
576
+ kind: TimerKind,
577
+ childId: ChildId,
578
+ generation: Generation,
579
+ deadline: Deadline
580
+ });
581
+ const ArmSupervisorTimer = Schema.TaggedStruct("ArmSupervisorTimer", {
582
+ kind: TimerKind,
583
+ deadline: Deadline
584
+ });
585
+ const ReplyStartAccepted = Schema.TaggedStruct("ReplyStartAccepted", {
586
+ requestId: RequestId,
587
+ childId: ChildId,
588
+ generation: Generation
589
+ });
590
+ const ReplyStartRefused = Schema.TaggedStruct("ReplyStartRefused", { requestId: RequestId });
591
+ const ReplyStopped = Schema.TaggedStruct("ReplyStopped", { requestId: RequestId });
592
+ const TerminateSupervisor = Schema.TaggedStruct("TerminateSupervisor", {
593
+ reason: TerminationReason,
594
+ exit: SupervisorExit
595
+ });
596
+ Schema.Union([
597
+ StartChild,
598
+ StopChild,
599
+ ArmChildTimer,
600
+ ArmSupervisorTimer,
601
+ ReplyStartAccepted,
602
+ ReplyStartRefused,
603
+ ReplyStopped,
604
+ TerminateSupervisor
605
+ ]);
606
+ const SupervisorArm = Schema.Union([ArmChildTimer, ArmSupervisorTimer]);
607
+ const SupervisorReply = Schema.Union([
608
+ ReplyStartAccepted,
609
+ ReplyStartRefused,
610
+ ReplyStopped
611
+ ]);
612
+ const SupervisorCommands = Schema.Struct({
613
+ stops: Schema.Array(StopChild),
614
+ starts: Schema.Array(StartChild),
615
+ arms: Schema.Array(SupervisorArm),
616
+ replies: Schema.Array(SupervisorReply),
617
+ terminates: Schema.Array(TerminateSupervisor)
618
+ });
623
619
  //#endregion
624
- //#region src/internal/RaceForExit.ts
625
- /** @internal */
626
- const raceForExit = (fibers) => Effect.raceAll(fibers.map((f, idx) => Fiber.await(f).pipe(Effect.map((exit) => [idx, exit]))));
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
632
+ });
633
+ const SupervisorCore = Schema.Struct({
634
+ policy: SupervisionPolicy,
635
+ children: Schema.Array(ChildInstance),
636
+ restartStamps: Schema.Array(EventTime),
637
+ nextOrdinal: Ordinal
638
+ });
639
+ const ChildStart = Schema.Struct({
640
+ childId: ChildId,
641
+ generation: Generation
642
+ });
627
643
  //#endregion
628
- //#region src/internal/SupervisionEpoch.schema.ts
629
- const EpochStepTypeId = Symbol.for("@systemfsoftware/effect-daemon/EpochStep");
630
- /** @internal */
631
- var StopEpoch = class extends Schema.TaggedClass()("StopEpoch", {}) {
632
- [EpochStepTypeId] = EpochStepTypeId;
644
+ //#region src/kernel/interpret-supervision-event.workflow.ts
645
+ var Stale = class extends Schema.TaggedClass()("Stale", {}) {
646
+ [DecisionTypeId] = DecisionTypeId;
633
647
  };
634
- /** @internal */
635
- var RestartEpoch = class extends Schema.TaggedClass()("RestartEpoch", {}) {
636
- [EpochStepTypeId] = EpochStepTypeId;
648
+ var Continue = class extends Schema.TaggedClass()("Continue", {
649
+ core: SupervisorCore,
650
+ commands: SupervisorCommands
651
+ }) {
652
+ [DecisionTypeId] = DecisionTypeId;
637
653
  };
638
- /** @internal */
639
- var CooldownEpoch = class extends Schema.TaggedClass()("CooldownEpoch", {}) {
640
- [EpochStepTypeId] = EpochStepTypeId;
654
+ var RestartChildren = class extends Schema.TaggedClass()("RestartChildren", {
655
+ core: SupervisorCore,
656
+ pending: Schema.Array(ChildStart),
657
+ commands: SupervisorCommands
658
+ }) {
659
+ [DecisionTypeId] = DecisionTypeId;
641
660
  };
642
- Schema.Union([
643
- StopEpoch,
644
- RestartEpoch,
645
- CooldownEpoch
661
+ var StartChildren = class extends Schema.TaggedClass()("StartChildren", {
662
+ core: SupervisorCore,
663
+ commands: SupervisorCommands
664
+ }) {
665
+ [DecisionTypeId] = DecisionTypeId;
666
+ };
667
+ var CoolDown = class extends Schema.TaggedClass()("CoolDown", {
668
+ core: SupervisorCore,
669
+ millis: PositiveMillis,
670
+ commands: SupervisorCommands
671
+ }) {
672
+ [DecisionTypeId] = DecisionTypeId;
673
+ };
674
+ var StopChildren = class extends Schema.TaggedClass()("StopChildren", {
675
+ core: SupervisorCore,
676
+ reason: TerminationReason,
677
+ exit: SupervisorExit,
678
+ commands: SupervisorCommands
679
+ }) {
680
+ [DecisionTypeId] = DecisionTypeId;
681
+ };
682
+ var Terminate = class extends Schema.TaggedClass()("Terminate", {
683
+ reason: TerminationReason,
684
+ commands: SupervisorCommands
685
+ }) {
686
+ [DecisionTypeId] = DecisionTypeId;
687
+ };
688
+ var RefuseDynamicStart = class extends Schema.TaggedClass()("RefuseDynamicStart", { commands: SupervisorCommands }) {
689
+ [DecisionTypeId] = DecisionTypeId;
690
+ };
691
+ const SupervisionDecision = Schema.Union([
692
+ Stale,
693
+ Continue,
694
+ RestartChildren,
695
+ StartChildren,
696
+ CoolDown,
697
+ StopChildren,
698
+ Terminate,
699
+ RefuseDynamicStart
646
700
  ]);
647
- const SupervisionEpochResultTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionEpochResult");
648
- /** @internal */
649
- var StopSupervision = class extends Schema.TaggedClass()("StopSupervision", {}) {
650
- [SupervisionEpochResultTypeId] = SupervisionEpochResultTypeId;
701
+ var Running$1 = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
702
+ [StateTypeId] = StateTypeId;
651
703
  };
652
- /** @internal */
653
- var ContinueSupervision = class extends Schema.TaggedClass()("ContinueSupervision", {}) {
654
- [SupervisionEpochResultTypeId] = SupervisionEpochResultTypeId;
704
+ var Restarting$1 = class extends Schema.TaggedClass()("Restarting", {
705
+ core: SupervisorCore,
706
+ pending: Schema.Array(ChildStart)
707
+ }) {
708
+ [StateTypeId] = StateTypeId;
655
709
  };
656
- Schema.Union([StopSupervision, ContinueSupervision]);
657
- //#endregion
658
- //#region src/WithLeaderLock.ts
659
- const acquireWithLock = (self, options, lock) => Effect.gen(function* () {
660
- const out = yield* lock.withLock(options.key, self);
661
- if (Option.isSome(out)) return out.value;
662
- return yield* Match.value(options.mode).pipe(Match.when("required", () => Effect.fail(LeaderLockNotAcquired.make({ key: options.key }))), Match.when("optional", () => Effect.void), Match.exhaustive);
663
- });
664
- const retryAcquire = (acquire, current) => Effect.retry(acquire, {
665
- schedule: current,
666
- while: Predicate.isTagged("LeaderLockNotAcquired")
667
- }).pipe(Effect.catchTag("LeaderLockNotAcquired", () => retryAcquire(acquire, current)));
668
- const withRequiredBackoff = (acquire, backoff) => {
669
- if (typeof backoff === "undefined") return acquire;
670
- return retryAcquire(acquire, backoff);
710
+ var CoolingDown$1 = class extends Schema.TaggedClass()("CoolingDown", {
711
+ core: SupervisorCore,
712
+ millis: PositiveMillis
713
+ }) {
714
+ [StateTypeId] = StateTypeId;
671
715
  };
672
- /**
673
- * Runs `self` while holding the named leader lock.
674
- */
675
- const withLeaderLock = Function.dual(3, (self, options, lock) => {
676
- const acquire = acquireWithLock(self, options, lock);
677
- if (options.mode !== "required") return acquire;
678
- return withRequiredBackoff(acquire, options.acquireRetryBackoff);
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
+ var SupervisionStep = class extends Schema.TaggedClass()("SupervisionStep", {
734
+ state: SupervisorState$1,
735
+ event: SupervisionEvent
736
+ }) {
737
+ static [Workflow.InstrumentationBrand] = {};
738
+ };
739
+ const UNKNOWN_TIMEOUT_MILLIS = 1e3;
740
+ const noCommands = {
741
+ stops: [],
742
+ starts: [],
743
+ arms: [],
744
+ replies: [],
745
+ terminates: []
746
+ };
747
+ const commandsIn = (buckets) => ({
748
+ ...noCommands,
749
+ ...buckets
679
750
  });
680
- //#endregion
681
- //#region src/internal/WithLockByModeExecutor.ts
682
- /**
683
- * Runs `self` under whichever lock discipline the binding asks for.
684
- *
685
- * An absent lock adapter and a `mode: 'none'` spec are one case, not two: a spec that
686
- * declines the lock and a composition root that supplies no adapter both leave the
687
- * body unwrapped, and nothing downstream can tell them apart from the effect that
688
- * comes back. `unlocked` is that single case; `locked` dispatches on the spec's mode
689
- * to the existing `withLeaderLock` calls. There is no null arm because the null state
690
- * is now a constructor choice, not a runtime case.
691
- *
692
- * The worker and the supervisor make the same choice over the same cases, so it is
693
- * made here once rather than in each of them.
694
- */
695
- const withKeyedLock = (self, spec, lock) => {
696
- if (spec.mode === "required") return withLeaderLock(self, {
697
- key: spec.key,
698
- mode: "required",
699
- acquireRetryBackoff: spec.acquireRetryBackoff
700
- }, lock);
701
- return withLeaderLock(self, {
702
- key: spec.key,
703
- mode: "optional"
704
- }, lock);
751
+ const restartsOn = (restartType, reason) => Match.value(reason._tag).pipe(Match.when("Abnormal", () => restartType !== "temporary"), Match.when("Normal", () => restartType === "permanent"), Match.when("Shutdown", () => restartType === "permanent"), Match.exhaustive);
752
+ const incarnationMatches = (childId, generation) => (child) => [child.childId === childId, child.generation === generation].every((holds) => holds);
753
+ const planMatches = (childId, generation) => (plan) => [plan.childId === childId, plan.generation === generation].every((holds) => holds);
754
+ const currentIncarnation = (core, childId, generation) => Array.findFirst(core.children, incarnationMatches(childId, generation));
755
+ const declarationOf$1 = (policy, childId) => Array.findFirst(policy.childDeclarations, (declaration) => declaration.childId === childId);
756
+ const dynamicKindOf$1 = (policy) => Match.value(policy.dynamic).pipe(Match.tag("DynamicChildren", (dynamic) => Option.some(dynamic)), Match.tag("NoDynamicChildren", () => Option.none()), Match.exhaustive);
757
+ const declaredKind = (declaration) => ({
758
+ restartType: declaration.restartType,
759
+ shutdown: declaration.shutdown,
760
+ startTimeoutMillis: declaration.startTimeoutMillis,
761
+ probeFailureThreshold: declaration.probeFailureThreshold,
762
+ significant: declaration.significant
763
+ });
764
+ const dynamicKindAs = (dynamic) => ({
765
+ restartType: dynamic.restartType,
766
+ shutdown: dynamic.shutdown,
767
+ startTimeoutMillis: dynamic.startTimeoutMillis,
768
+ probeFailureThreshold: dynamic.probeFailureThreshold,
769
+ significant: false
770
+ });
771
+ const unknownKind = {
772
+ restartType: "temporary",
773
+ shutdown: { _tag: "Infinity" },
774
+ startTimeoutMillis: UNKNOWN_TIMEOUT_MILLIS,
775
+ probeFailureThreshold: 1,
776
+ significant: false
705
777
  };
706
- /** @internal */
707
- const withLockByMode = Function.dual(2, (self, binding) => {
708
- if (binding.kind === "unlocked") return self;
709
- return withKeyedLock(self, binding.spec, binding.lock);
778
+ const fallbackKind = (policy) => Match.value(dynamicKindOf$1(policy)).pipe(Match.tag("Some", ({ value }) => dynamicKindAs(value)), Match.tag("None", () => unknownKind), Match.exhaustive);
779
+ const kindOfPolicy = (policy, childId) => Match.value(declarationOf$1(policy, childId)).pipe(Match.tag("Some", ({ value }) => declaredKind(value)), Match.tag("None", () => fallbackKind(policy)), Match.exhaustive);
780
+ const indexOfChild = (core, childId) => Array.findFirstIndex(core.children, (child) => child.childId === childId);
781
+ const scopeIndices = (strategy, failedIndex, total) => Match.value(strategy).pipe(Match.when("one_for_one", () => [failedIndex]), Match.when("one_for_all", () => Array.range(0, total - 1)), Match.when("rest_for_one", () => Array.range(failedIndex, total - 1)), Match.exhaustive);
782
+ const stoppingOf = (child) => ({
783
+ ...child,
784
+ status: "stopping"
710
785
  });
711
- //#endregion
712
- //#region src/internal/SupervisorBodyExecutor.ts
713
- const handleExhausted = (ctx, cause) => Effect.gen(function* () {
714
- yield* Effect.andThen(ctx.health.healthy.close, Metric.update(Metric.withAttributes(healthStateGauge, {
715
- daemon: ctx.name,
716
- latch: "healthy"
717
- }), 0));
718
- yield* ctx.reportExhausted(cause);
719
- return CooldownEpoch.make();
720
- });
721
- const handleRestart = (ctx, cause, onSignal) => Effect.gen(function* () {
722
- yield* ctx.reportRestart(cause);
723
- yield* onSignal;
724
- return RestartEpoch.make();
786
+ const restartingOf = (child, generation) => ({
787
+ childId: child.childId,
788
+ generation,
789
+ status: "starting",
790
+ consecutiveRestarts: child.consecutiveRestarts + 1,
791
+ probeFailures: 0
725
792
  });
726
- /**
727
- * The restart decision, as a description whose phases chain by type and read in the order
728
- * they run.
729
- *
730
- * The read is a bump-and-report: recording a restart is how the current rate is obtained, so
731
- * the mutation is a product gathered across the read's interior rather than a write standing
732
- * before a decision. That is what keeps this one layer instead of two, and it is why
733
- * `intensity.record` sits where it does. The read is also where the command's encoded form is
734
- * gathered, so the library decodes it through the workflow's command schema before `decide`
735
- * runs and encodes the decision or the refusal the workflow returns.
736
- *
737
- * The write dispatches one handler per encoded tag, and each handler answers with the epoch
738
- * step that follows: a decision to continue stops the epoch, a decision to restart reports and
739
- * reboots, and the `Exhausted` refusal cools down. A command the supervisor built that fails its
740
- * own schema is a regression in this module, so it is logged and treated as exhausted: the
741
- * supervisor cools down instead of dying and taking every child with it.
742
- *
743
- * A description is built per failure because the write needs that failure's context, and the
744
- * phase signatures hand the command to the read alone. Restarts are rare, so the allocation is
745
- * paid only when a supervised child has actually died.
746
- */
747
- const restartDescription = (spec) => Sandwich.named("supervisor.restart-description")((intensity) => Effect.map(Effect.andThen(intensity.record, intensity.isExceeded), (intensityExceeded) => ({
748
- strategy: spec.strategy,
749
- totalChildren: spec.totalChildren,
750
- failedIndex: spec.failedIndex,
751
- exitSuccess: false,
752
- intensityExceeded
753
- }))).decide(chooseRestartStrategy).write({
754
- Continue: () => Effect.succeed(StopEpoch.make()),
755
- Restart: (decision) => handleRestart(spec.ctx, spec.cause, spec.onRestart(decision)),
756
- Exhausted: () => handleExhausted(spec.ctx, spec.cause),
757
- CommandRejected: (rejected) => Effect.andThen(Effect.logError("supervisor restart command failed its own schema; cooling down", {
758
- daemon: spec.ctx.name,
759
- issue: String(rejected.issue)
760
- }), handleExhausted(spec.ctx, spec.cause))
761
- });
762
- const reopenHealthyAfterCooldown = (ctx) => Effect.andThen(ctx.health.healthy.open, Metric.update(Metric.withAttributes(healthStateGauge, {
763
- daemon: ctx.name,
764
- latch: "healthy"
765
- }), 1));
766
- const runSupervisionEpochWithBackoff = (attempt, ctx) => Effect.gen(function* () {
767
- const advance = yield* Schedule.toStep(ctx.policy.backoff);
768
- const loop = () => Effect.gen(function* () {
769
- const epochStep = yield* attempt.pipe(Effect.scoped);
770
- return yield* Match.value(epochStep).pipe(Match.tag("StopEpoch", () => Effect.succeed(StopSupervision.make())), Match.tag("CooldownEpoch", () => Effect.gen(function* () {
771
- yield* Effect.sleep(ctx.policy.cooldown);
772
- yield* reopenHealthyAfterCooldown(ctx);
773
- return ContinueSupervision.make();
774
- })), Match.tag("RestartEpoch", () => Effect.gen(function* () {
775
- const now = yield* Clock.currentTimeMillis;
776
- const pulled = yield* Effect.result(advance(now, void 0));
777
- if (Result.isFailure(pulled)) return StopSupervision.make();
778
- const [, delay] = pulled.success;
779
- yield* Effect.sleep(delay);
780
- return yield* loop();
781
- })), Match.exhaustive);
782
- });
783
- return yield* loop();
793
+ const readiedOf = (child) => ({
794
+ childId: child.childId,
795
+ generation: child.generation,
796
+ status: "ready",
797
+ consecutiveRestarts: 0,
798
+ probeFailures: 0
784
799
  });
785
- const openAllReady = (ctx) => Effect.gen(function* () {
786
- yield* Effect.yieldNow;
787
- yield* Effect.forEach(ctx.booted, (b) => b.health.ready.await, { concurrency: "unbounded" });
788
- yield* Effect.andThen(ctx.health.ready.open, Metric.update(Metric.withAttributes(healthStateGauge, {
789
- daemon: ctx.name,
790
- latch: "ready"
791
- }), 1));
800
+ const probedAs = (child, alive) => Match.value(alive).pipe(Match.when(true, () => ({
801
+ ...child,
802
+ probeFailures: 0
803
+ })), Match.when(false, () => ({
804
+ ...child,
805
+ probeFailures: child.probeFailures + 1
806
+ })), Match.exhaustive);
807
+ const replacing = (next) => (child) => Match.value(child.childId === next.childId).pipe(Match.when(true, () => next), Match.when(false, () => child), Match.exhaustive);
808
+ const withChildren = (core, children) => ({
809
+ ...core,
810
+ children
792
811
  });
793
- /**
794
- * Records one restart against the child's intensity tracker and reports whether the
795
- * child's restart budget is now exceeded. A child without a bounded intensity policy
796
- * never hits the budget.
797
- */
798
- const isChildIntensityBudgetDone = (tracker) => Option.match(tracker, {
799
- onNone: () => Effect.succeed(false),
800
- onSome: (ci) => Effect.gen(function* () {
801
- yield* ci.record;
802
- return yield* ci.isExceeded;
803
- })
812
+ const withStamps = (core, restartStamps) => ({
813
+ ...core,
814
+ restartStamps
815
+ });
816
+ const prunedStamps = (core, at) => Array.filter(core.restartStamps, (stamp) => at - stamp <= core.policy.periodMillis);
817
+ const backoffDelay = (schedule, consecutiveRestarts) => Match.value(schedule.baseMillis).pipe(Match.when(0, () => 0), Match.orElse((baseMillis) => Number$1.min(schedule.capMillis, baseMillis * schedule.multiplier ** consecutiveRestarts)));
818
+ const startCommandOf = (start) => ({
819
+ _tag: "StartChild",
820
+ childId: start.childId,
821
+ generation: start.generation
822
+ });
823
+ const stopCommandOf = (policy, child) => ({
824
+ _tag: "StopChild",
825
+ childId: child.childId,
826
+ generation: child.generation,
827
+ shutdown: kindOfPolicy(policy, child.childId).shutdown
828
+ });
829
+ const backoffCommandOf = (start, deadline) => ({
830
+ _tag: "ArmChildTimer",
831
+ kind: "backoff",
832
+ childId: start.childId,
833
+ generation: start.generation,
834
+ deadline
835
+ });
836
+ const deadlineCommandOf = (start, deadline) => ({
837
+ _tag: "ArmChildTimer",
838
+ kind: "start_deadline",
839
+ childId: start.childId,
840
+ generation: start.generation,
841
+ deadline
842
+ });
843
+ const tickCommandOf = (child, deadline) => ({
844
+ _tag: "ArmChildTimer",
845
+ kind: "liveness_tick",
846
+ childId: child.childId,
847
+ generation: child.generation,
848
+ deadline
849
+ });
850
+ const coolDownCommandOf = (deadline) => ({
851
+ _tag: "ArmSupervisorTimer",
852
+ kind: "cool_down",
853
+ deadline
854
+ });
855
+ const terminateCommandOf = (reason, exit) => ({
856
+ _tag: "TerminateSupervisor",
857
+ reason,
858
+ exit
859
+ });
860
+ const replyAcceptedOf = (requestId, start) => ({
861
+ _tag: "ReplyStartAccepted",
862
+ requestId,
863
+ childId: start.childId,
864
+ generation: start.generation
865
+ });
866
+ const replyRefusedOf = (requestId) => ({
867
+ _tag: "ReplyStartRefused",
868
+ requestId
869
+ });
870
+ const replyStoppedOf = (requestId) => ({
871
+ _tag: "ReplyStopped",
872
+ requestId
873
+ });
874
+ const refusedStartOf = (requestId) => new RefuseDynamicStart({ commands: commandsIn({ replies: [replyRefusedOf(requestId)] }) });
875
+ const holdOf = (core) => new Continue({
876
+ core,
877
+ commands: noCommands
878
+ });
879
+ const terminatedReason = { _tag: "Shutdown" };
880
+ const requestedExit = { _tag: "RequestedExit" };
881
+ const failureReportOf = (reason) => Match.value(reason).pipe(Match.tag("Abnormal", (abnormal) => abnormal.report), Match.orElse(() => ({
882
+ _tag: "CauseReport",
883
+ cause: Cause.pretty(Cause.fail(reason))
884
+ })));
885
+ const giveUpReasonOf = (termination) => ({
886
+ _tag: "Abnormal",
887
+ report: failureReportOf(termination.reason)
888
+ });
889
+ const giveUpExitOf = (termination) => ({
890
+ _tag: "IntensityExceededExit",
891
+ childId: termination.childId,
892
+ generation: termination.generation
804
893
  });
805
- const childEpochOnRestartable = (ctx, idx, childIntensityOpt, supIntensity, cause) => Effect.gen(function* () {
806
- if (yield* isChildIntensityBudgetDone(childIntensityOpt)) return StopEpoch.make();
807
- return yield* restartDescription({
808
- strategy: "one_for_one",
809
- failedIndex: idx,
810
- totalChildren: ctx.booted.length,
811
- ctx,
812
- cause,
813
- onRestart: () => Effect.void
814
- }).run(supIntensity);
815
- });
816
- const childEpochOnFailure = (ctx, child, idx, childIntensityOpt, supIntensity, cause) => {
817
- if (child.childPolicy.restart === "temporary") return Effect.succeed(StopEpoch.make());
818
- return childEpochOnRestartable(ctx, idx, childIntensityOpt, supIntensity, cause);
894
+ const terminateDecisionOf = (reason, exit) => new Terminate({
895
+ reason,
896
+ commands: commandsIn({ terminates: [terminateCommandOf(reason, exit)] })
897
+ });
898
+ const stopEverything = (core, reason, exit) => Match.value(Array.isReadonlyArrayNonEmpty(core.children)).pipe(Match.when(true, () => new StopChildren({
899
+ core: withChildren(core, Array.map(core.children, stoppingOf)),
900
+ reason,
901
+ exit,
902
+ commands: commandsIn({ stops: Array.map(Array.reverse(core.children), (child) => stopCommandOf(core.policy, child)) })
903
+ })), Match.when(false, () => terminateDecisionOf(reason, exit)), Match.exhaustive);
904
+ const terminationOf = (childId, generation, reason, at) => ({
905
+ childId,
906
+ generation,
907
+ reason,
908
+ at
909
+ });
910
+ const restartScopeOf = (core, failedIndex, termination) => {
911
+ const group = Array.getSomes(Array.map(scopeIndices(core.policy.strategy, failedIndex, Array.length(core.children)), (index) => Array.get(core.children, index)));
912
+ const coming = Array.filter(group, (child) => restartsOn(kindOfPolicy(core.policy, child.childId).restartType, termination.reason));
913
+ const comingIds = Array.map(coming, (child) => child.childId);
914
+ const removed = Array.filter(group, (child) => Array.contains(comingIds, child.childId) === false);
915
+ const removedIds = Array.map(removed, (child) => child.childId);
916
+ return {
917
+ coming,
918
+ comingIds,
919
+ removedIds,
920
+ remaining: Array.filter(core.children, (child) => Array.contains(removedIds, child.childId) === false),
921
+ stops: Array.map(Array.reverse(group), (child) => stopCommandOf(core.policy, child))
922
+ };
819
923
  };
820
- const childEpochOnExit = (ctx, child, idx, childIntensityOpt, supIntensity, exit) => {
821
- if (Exit.isSuccess(exit)) return Effect.succeed(StopEpoch.make());
822
- return childEpochOnFailure(ctx, child, idx, childIntensityOpt, supIntensity, exit.cause);
924
+ const restartedChildrenOf = (core, scope) => Array.flatMap(core.children, (child) => Match.value(Array.contains(scope.comingIds, child.childId)).pipe(Match.when(true, () => [restartingOf(child, child.generation + 1)]), Match.orElse(() => removalRemnant(scope.removedIds, child))));
925
+ const removalRemnant = (removedIds, child) => Match.value(Array.contains(removedIds, child.childId)).pipe(Match.when(true, () => []), Match.orElse(() => [child]));
926
+ const phasedCommands = (core, at, coming) => {
927
+ const steps = Array.map(coming, (child) => {
928
+ return {
929
+ start: {
930
+ childId: child.childId,
931
+ generation: child.generation + 1
932
+ },
933
+ delay: backoffDelay(core.policy.backoff, child.consecutiveRestarts)
934
+ };
935
+ });
936
+ const ready = Array.filter(steps, (step) => step.delay === 0);
937
+ const deferred = Array.filter(steps, (step) => step.delay > 0);
938
+ const timeoutOf = (step) => at + kindOfPolicy(core.policy, step.start.childId).startTimeoutMillis;
939
+ return {
940
+ commands: commandsIn({
941
+ starts: Array.map(ready, (step) => startCommandOf(step.start)),
942
+ arms: Array.appendAll(Array.map(ready, (step) => deadlineCommandOf(step.start, timeoutOf(step))), Array.map(deferred, (step) => backoffCommandOf(step.start, at + step.delay)))
943
+ }),
944
+ pending: Array.map(deferred, (step) => step.start)
945
+ };
823
946
  };
824
- const groupEpochOnRestartable = (strategy, ctx, failedIdx, childIntensityTrackers, intensity, cursor, cause) => Effect.gen(function* () {
825
- const cIntForFailed = Option.flatten(Array.get(childIntensityTrackers, failedIdx));
826
- if (yield* isChildIntensityBudgetDone(cIntForFailed)) return StopEpoch.make();
827
- return yield* restartDescription({
828
- strategy,
829
- failedIndex: failedIdx,
830
- totalChildren: ctx.booted.length,
831
- ctx,
832
- cause,
833
- onRestart: (decision) => Ref.set(cursor, decision.indices[0])
834
- }).run(intensity);
835
- });
836
- const groupEpochOnFailedChild = (strategy, ctx, failedBooted, failedIdx, childIntensityTrackers, intensity, cursor, cause) => {
837
- if (failedBooted.childPolicy.restart === "temporary") return Effect.succeed(StopEpoch.make());
838
- return groupEpochOnRestartable(strategy, ctx, failedIdx, childIntensityTrackers, intensity, cursor, cause);
947
+ const exhaustedDecisionOf = (policy, original, restarted, stops, at, termination) => Match.value(policy.coolDown).pipe(Match.tag("CoolDownAfter", ({ millis }) => new CoolDown({
948
+ core: restarted,
949
+ millis,
950
+ commands: commandsIn({
951
+ stops,
952
+ arms: [coolDownCommandOf(at + millis)]
953
+ })
954
+ })), Match.tag("NoCoolDown", () => stopEverything(original, giveUpReasonOf(termination), giveUpExitOf(termination))), Match.exhaustive);
955
+ const stampedCoreOf = (core, scope, at) => {
956
+ const stamped = withStamps(core, [at, ...prunedStamps(core, at)]);
957
+ return withChildren(stamped, restartedChildrenOf(core, scope));
839
958
  };
840
- const groupEpochOnFailure = (strategy, ctx, startIdx, failedOffset, childIntensityTrackers, intensity, cursor, cause) => {
841
- const failedIdx = startIdx + failedOffset;
842
- const failedBootedOpt = Option.fromNullishOr(ctx.booted[failedIdx]);
843
- if (Option.isNone(failedBootedOpt)) return Effect.succeed(StopEpoch.make());
844
- return groupEpochOnFailedChild(strategy, ctx, failedBootedOpt.value, failedIdx, childIntensityTrackers, intensity, cursor, cause);
959
+ const restartOutcomeOf = (core, scope, at) => {
960
+ const nextCore = stampedCoreOf(core, scope, at);
961
+ const phased = phasedCommands(core, at, scope.coming);
962
+ return {
963
+ core: nextCore,
964
+ stops: scope.stops,
965
+ pending: phased.pending,
966
+ commands: commandsIn({
967
+ stops: scope.stops,
968
+ starts: phased.commands.starts,
969
+ arms: phased.commands.arms
970
+ }),
971
+ exhausted: Array.length(nextCore.restartStamps) > nextCore.policy.intensity
972
+ };
845
973
  };
846
- const groupEpochOnExit = (strategy, ctx, startIdx, childIntensityTrackers, intensity, cursor, failedOffset, firstExit) => {
847
- if (Exit.isSuccess(firstExit)) return Effect.succeed(StopEpoch.make());
848
- return groupEpochOnFailure(strategy, ctx, startIdx, failedOffset, childIntensityTrackers, intensity, cursor, firstExit.cause);
974
+ const restartedDecisionOf = (core, outcome, termination) => Match.value(outcome.exhausted).pipe(Match.when(true, () => exhaustedDecisionOf(core.policy, core, outcome.core, outcome.stops, termination.at, termination)), Match.when(false, () => Match.value(Array.length(outcome.pending) === 0).pipe(Match.when(true, () => new StartChildren({
975
+ core: outcome.core,
976
+ commands: outcome.commands
977
+ })), Match.when(false, () => new RestartChildren({
978
+ core: outcome.core,
979
+ pending: outcome.pending,
980
+ commands: outcome.commands
981
+ })), Match.exhaustive)), Match.exhaustive);
982
+ const isSignificant = (policy, child) => Match.value(declarationOf$1(policy, child.childId)).pipe(Match.tag("Some", ({ value }) => value.significant), Match.tag("None", () => false), Match.exhaustive);
983
+ const autoShutsDown = (policy, removed, remaining) => Match.value(policy.autoShutdown).pipe(Match.when("never", () => false), Match.when("any_significant", () => Array.some(removed, (child) => isSignificant(policy, child))), Match.when("all_significant", () => Array.every(remaining, (child) => isSignificant(policy, child) === false)), Match.exhaustive);
984
+ const shutdownOrContinue = (core, removed, remaining) => Match.value(autoShutsDown(core.policy, removed, remaining)).pipe(Match.when(true, () => stopEverything(withChildren(core, remaining), terminatedReason, requestedExit)), Match.when(false, () => new Continue({
985
+ core: withChildren(core, remaining),
986
+ commands: noCommands
987
+ })), Match.exhaustive);
988
+ Schema.TaggedStruct("Restarted", { outcome: Schema.Struct({
989
+ core: SupervisorCore,
990
+ stops: Schema.Array(StopChild),
991
+ pending: Schema.Array(ChildStart),
992
+ commands: SupervisorCommands,
993
+ exhausted: Schema.Boolean
994
+ }) });
995
+ Schema.TaggedStruct("Quiet", {
996
+ removedIds: Schema.Array(ChildId),
997
+ remaining: Schema.Array(ChildInstance)
998
+ });
999
+ const failedChildOf = (core, failedIndex) => Array.get(core.children, failedIndex);
1000
+ const failedComesBack = (core, failedIndex, termination) => Match.value(failedChildOf(core, failedIndex)).pipe(Match.tag("Some", (found) => restartsOn(kindOfPolicy(core.policy, found.value.childId).restartType, termination.reason)), Match.tag("None", () => false), Match.exhaustive);
1001
+ const quietSplitOf = (core, failedIndex) => Match.value(failedChildOf(core, failedIndex)).pipe(Match.tag("Some", (found) => ({
1002
+ _tag: "Quiet",
1003
+ removedIds: [found.value.childId],
1004
+ remaining: Array.filter(core.children, (child) => incarnationMatches(found.value.childId, found.value.generation)(child) === false)
1005
+ })), Match.tag("None", () => ({
1006
+ _tag: "Quiet",
1007
+ removedIds: [],
1008
+ remaining: core.children
1009
+ })), Match.exhaustive);
1010
+ const restartSplitOf = (core, failedIndex, termination) => Match.value(failedComesBack(core, failedIndex, termination)).pipe(Match.when(true, () => ({
1011
+ _tag: "Restarted",
1012
+ outcome: restartOutcomeOf(core, restartScopeOf(core, failedIndex, termination), termination.at)
1013
+ })), Match.when(false, () => quietSplitOf(core, failedIndex)), Match.exhaustive);
1014
+ const terminatedIndexed = (core, failedIndex, termination) => Match.value(restartSplitOf(core, failedIndex, termination)).pipe(Match.tag("Restarted", (restarted) => restartedDecisionOf(core, restarted.outcome, termination)), Match.tag("Quiet", (quiet) => shutdownOrContinue(core, Array.filter(core.children, (child) => Array.contains(quiet.removedIds, child.childId)), quiet.remaining)), Match.exhaustive);
1015
+ const terminatedCurrent = (core, child, termination) => Match.value(child.status).pipe(Match.when("stopping", () => removalContinue(core, termination)), Match.orElse(() => Match.value(indexOfChild(core, child.childId)).pipe(Match.tag("Some", (index) => terminatedIndexed(core, index.value, termination)), Match.tag("None", () => new Stale({})), Match.exhaustive)));
1016
+ const removalOf = (core, childId, generation) => withChildren(core, Array.filter(core.children, (child) => incarnationMatches(childId, generation)(child) === false));
1017
+ const removalContinue = (core, termination) => new Continue({
1018
+ core: removalOf(core, termination.childId, termination.generation),
1019
+ commands: noCommands
1020
+ });
1021
+ const terminatedRunning = (core, event) => Match.value(currentIncarnation(core, event.childId, event.generation)).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", (found) => terminatedCurrent(core, found.value, terminationOf(event.childId, event.generation, event.reason, event.at))), Match.exhaustive);
1022
+ const startedInRunning = (core, childId, generation) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("Some", () => holdOf(core)), Match.tag("None", () => new Stale({})), Match.exhaustive);
1023
+ const readyInRunning = (core, childId, generation, at) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", (found) => becomingReady(core, found.value, at)), Match.exhaustive);
1024
+ const becomingReady = (core, child, at) => Match.value(child.status).pipe(Match.when("starting", () => {
1025
+ const next = readiedOf(child);
1026
+ return new Continue({
1027
+ core: withChildren(core, Array.map(core.children, replacing(next))),
1028
+ commands: commandsIn({ arms: [tickCommandOf(next, at + core.policy.livenessTickMillis)] })
1029
+ });
1030
+ }), Match.orElse(() => holdOf(core)));
1031
+ const stoppedInShuttingDown = (core, reason, exit, childId, generation) => {
1032
+ const next = removalOf(core, childId, generation);
1033
+ return Match.value(Array.every(next.children, (child) => child.status !== "stopping")).pipe(Match.when(true, () => terminateDecisionOf(reason, exit)), Match.when(false, () => new Continue({
1034
+ core: next,
1035
+ commands: noCommands
1036
+ })), Match.exhaustive);
849
1037
  };
850
- const superviseChild = (ctx, child, idx) => Effect.gen(function* () {
851
- const childIntensityOpt = yield* Option.match(Option.fromNullishOr(child.childPolicy.intensity), {
852
- onNone: () => Effect.succeed(Option.none()),
853
- onSome: (cfg) => Effect.asSome(make(cfg.restarts, cfg.window))
1038
+ const probedInRunning = (core, childId, generation, alive, at) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", (found) => probedOutcomeOf(core, found.value, alive, at)), Match.exhaustive);
1039
+ const probedOutcomeOf = (core, child, alive, at) => Match.value(child.status).pipe(Match.when("ready", () => probedReadyOutcomeOf(core, child, alive, at)), Match.orElse(() => holdOf(core)));
1040
+ const probedReadyOutcomeOf = (core, child, alive, at) => Match.value(alive).pipe(Match.when(true, () => new Continue({
1041
+ core: withChildren(core, Array.map(core.children, replacing(probedAs(child, true)))),
1042
+ commands: noCommands
1043
+ })), Match.when(false, () => failedProbeOutcomeOf(core, child, at)), Match.exhaustive);
1044
+ const failedProbeOutcomeOf = (core, child, at) => Match.value(child.probeFailures + 1 >= kindOfPolicy(core.policy, child.childId).probeFailureThreshold).pipe(Match.when(true, () => terminatedIndexed(core, Option.getOrThrow(indexOfChild(core, child.childId)), terminationOf(child.childId, child.generation, {
1045
+ _tag: "Abnormal",
1046
+ report: {
1047
+ _tag: "InferredReport",
1048
+ failedProbes: child.probeFailures + 1
1049
+ }
1050
+ }, at))), Match.when(false, () => new Continue({
1051
+ core: withChildren(core, Array.map(core.children, replacing(probedAs(child, false)))),
1052
+ commands: noCommands
1053
+ })), Match.exhaustive);
1054
+ const namedTimerInRunning = (core, child, kind, at) => Match.value(kind).pipe(Match.when("start_deadline", () => deadlineInRunning(core, child, at)), Match.when("liveness_tick", () => tickInRunning(core, child, at)), Match.when("backoff", () => new Stale({})), Match.when("cool_down", () => new Stale({})), Match.exhaustive);
1055
+ const deadlineInRunning = (core, child, at) => Match.value(child.status).pipe(Match.when("starting", () => terminatedIndexed(core, Option.getOrThrow(indexOfChild(core, child.childId)), {
1056
+ childId: child.childId,
1057
+ generation: child.generation,
1058
+ reason: {
1059
+ _tag: "Abnormal",
1060
+ report: {
1061
+ _tag: "DeadlineMissed",
1062
+ waitedMillis: kindOfPolicy(core.policy, child.childId).startTimeoutMillis
1063
+ }
1064
+ },
1065
+ at
1066
+ })), Match.orElse(() => new Stale({})));
1067
+ const tickInRunning = (core, child, at) => Match.value(child.status).pipe(Match.when("ready", () => new Continue({
1068
+ core,
1069
+ commands: commandsIn({ arms: [tickCommandOf(child, at + core.policy.livenessTickMillis)] })
1070
+ })), Match.orElse(() => new Stale({})));
1071
+ const timerInRunning = (core, childId, generation, kind, at) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", (found) => namedTimerInRunning(core, found.value, kind, at)), Match.exhaustive);
1072
+ const fireBackoffOf = (core, pending, childId, generation, at) => {
1073
+ const start = {
1074
+ childId,
1075
+ generation
1076
+ };
1077
+ const remaining = Array.filter(pending, (plan) => planMatches(childId, generation)(plan) === false);
1078
+ const commands = commandsIn({
1079
+ starts: [startCommandOf(start)],
1080
+ arms: [deadlineCommandOf(start, at + kindOfPolicy(core.policy, childId).startTimeoutMillis)]
854
1081
  });
855
- const loop = () => Effect.gen(function* () {
856
- const supIntensity = yield* ctx.intensityEff;
857
- const attempt = Effect.gen(function* () {
858
- yield* ctx.health.paused.await;
859
- const fiber = yield* Effect.forkScoped(child.run, { startImmediately: true });
860
- const exit = yield* Fiber.await(fiber);
861
- return yield* childEpochOnExit(ctx, child, idx, childIntensityOpt, supIntensity, exit);
862
- });
863
- const epochResult = yield* runSupervisionEpochWithBackoff(attempt, ctx);
864
- return yield* Match.value(epochResult).pipe(Match.tag("ContinueSupervision", () => loop()), Match.tag("StopSupervision", () => Effect.void), Match.exhaustive);
1082
+ return Match.value(Array.length(remaining) === 0).pipe(Match.when(true, () => new StartChildren({
1083
+ core,
1084
+ commands
1085
+ })), Match.when(false, () => new RestartChildren({
1086
+ core,
1087
+ pending: remaining,
1088
+ commands
1089
+ })), Match.exhaustive);
1090
+ };
1091
+ const backoffInRestarting = (core, pending, childId, generation, kind, at) => Match.value(kind).pipe(Match.when("backoff", () => Match.value(Array.findFirst(pending, planMatches(childId, generation))).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", () => fireBackoffOf(core, pending, childId, generation, at)), Match.exhaustive)), Match.orElse(() => new Stale({})));
1092
+ const cooledStartsOf = (core, at) => {
1093
+ const fresh = Array.map(core.children, (child) => ({
1094
+ ...child,
1095
+ status: "starting",
1096
+ consecutiveRestarts: 0,
1097
+ probeFailures: 0
1098
+ }));
1099
+ const deadlineOf = (child) => deadlineCommandOf({
1100
+ childId: child.childId,
1101
+ generation: child.generation
1102
+ }, at + kindOfPolicy(core.policy, child.childId).startTimeoutMillis);
1103
+ return {
1104
+ fresh,
1105
+ commands: commandsIn({
1106
+ starts: Array.map(fresh, (child) => startCommandOf({
1107
+ childId: child.childId,
1108
+ generation: child.generation
1109
+ })),
1110
+ arms: Array.map(fresh, deadlineOf)
1111
+ })
1112
+ };
1113
+ };
1114
+ const cooledRestartOf = (core, at) => {
1115
+ const starts = cooledStartsOf(core, at);
1116
+ const clearedStamps = [];
1117
+ return new StartChildren({
1118
+ core: {
1119
+ ...core,
1120
+ children: starts.fresh,
1121
+ restartStamps: clearedStamps
1122
+ },
1123
+ commands: starts.commands
865
1124
  });
866
- return yield* loop();
867
- });
868
- const runIndependent = (ctx) => Effect.gen(function* () {
869
- const fibers = yield* Effect.forEach(ctx.booted, (child, childIdx) => Effect.forkScoped(superviseChild(ctx, child, childIdx), { startImmediately: true }));
870
- yield* Effect.yieldNow;
871
- yield* openAllReady(ctx);
872
- yield* Effect.forEach(fibers, (f) => Fiber.await(f), { concurrency: "unbounded" });
873
- });
874
- const runGroup = (strategy, ctx) => Effect.gen(function* () {
875
- const loop = () => Effect.gen(function* () {
876
- const intensity = yield* ctx.intensityEff;
877
- const childIntensityTrackers = yield* Effect.forEach(ctx.booted, (b) => Option.match(Option.fromNullishOr(b.childPolicy.intensity), {
878
- onNone: () => Effect.succeed(Option.none()),
879
- onSome: (cfg) => Effect.asSome(make(cfg.restarts, cfg.window))
880
- }));
881
- const cursor = yield* Ref.make(0);
882
- const attempt = Effect.gen(function* () {
883
- yield* ctx.health.paused.await;
884
- const startIdx = yield* Ref.get(cursor);
885
- const slice = ctx.booted.slice(startIdx);
886
- const fibers = yield* Effect.forEach(slice, (c) => Effect.forkScoped(c.run, { startImmediately: true }));
887
- yield* Effect.yieldNow;
888
- yield* Effect.forkScoped(openAllReady(ctx), { startImmediately: true });
889
- const [failedOffset, firstExit] = yield* raceForExit(fibers);
890
- return yield* groupEpochOnExit(strategy, ctx, startIdx, childIntensityTrackers, intensity, cursor, failedOffset, firstExit);
891
- });
892
- const epochResult = yield* runSupervisionEpochWithBackoff(attempt, ctx);
893
- return yield* Match.value(epochResult).pipe(Match.tag("ContinueSupervision", () => loop()), Match.tag("StopSupervision", () => Effect.void), Match.exhaustive);
1125
+ };
1126
+ const runningDynamicCount = (core) => Array.length(Array.filter(core.children, (child) => child.status !== "stopping"));
1127
+ const isDeclaredChild = (core, childId) => Option.isSome(declarationOf$1(core.policy, childId));
1128
+ const dynamicIdOf = (core) => `d${core.nextOrdinal}`;
1129
+ const dynamicInstanceOf = (core) => {
1130
+ const start = {
1131
+ childId: dynamicIdOf(core),
1132
+ generation: 0
1133
+ };
1134
+ const instance = {
1135
+ childId: start.childId,
1136
+ generation: start.generation,
1137
+ status: "starting",
1138
+ consecutiveRestarts: 0,
1139
+ probeFailures: 0
1140
+ };
1141
+ return {
1142
+ core: {
1143
+ ...core,
1144
+ children: Array.append(core.children, instance),
1145
+ nextOrdinal: core.nextOrdinal + 1
1146
+ },
1147
+ start
1148
+ };
1149
+ };
1150
+ const allocatedDecisionOf = (core, allocated, requestId, at) => {
1151
+ const timeoutMillis = Match.value(dynamicKindOf$1(allocated.core.policy)).pipe(Match.tag("Some", ({ value }) => value.startTimeoutMillis), Match.tag("None", () => UNKNOWN_TIMEOUT_MILLIS), Match.exhaustive);
1152
+ return new StartChildren({
1153
+ core: allocated.core,
1154
+ commands: commandsIn({
1155
+ starts: [startCommandOf(allocated.start)],
1156
+ arms: [deadlineCommandOf(allocated.start, at + timeoutMillis)],
1157
+ replies: [replyAcceptedOf(requestId, allocated.start)]
1158
+ })
894
1159
  });
895
- return yield* loop();
896
- });
897
- const superviseTree = (strategy, ctx) => Match.value(strategy).pipe(Match.when("one_for_one", () => runIndependent(ctx)), Match.when("one_for_all", () => runGroup("one_for_all", ctx)), Match.when("rest_for_one", () => runGroup("rest_for_one", ctx)), Match.exhaustive);
898
- const intensityTracker = (intensity) => Match.value(intensity).pipe(Match.tag("Unbounded", () => Effect.succeed(neverExceeds)), Match.tag("Bounded", ({ restarts, window }) => make(restarts, window)), Match.exhaustive);
899
- const buildSupervisorBody = (sup, health, booted, reporter) => Effect.gen(function* () {
900
- const policy = yield* sup.supervision;
901
- const tracker = yield* intensityTracker(policy.intensity);
902
- const intensityEff = Effect.succeed(tracker);
903
- const reportRestart = (cause) => Effect.gen(function* () {
904
- yield* Metric.update(Metric.withAttributes(supervisorRestartsCounter, { supervisor: sup.name }), 1);
905
- yield* reporter.onRestart(sup.name, cause);
906
- yield* Option.match(Option.fromNullishOr(sup.reporter.onRestart), {
907
- onNone: () => Effect.void,
908
- onSome: (fn) => fn(cause)
909
- });
1160
+ };
1161
+ const ceilingReached = (core, ceiling) => runningDynamicCount(core) >= ceiling;
1162
+ const dynamicStartOf = (core, requestId, at) => Match.value(dynamicKindOf$1(core.policy)).pipe(Match.tag("None", () => refusedStartOf(requestId)), Match.tag("Some", (dynamic) => Match.value(ceilingReached(core, dynamic.value.ceiling)).pipe(Match.when(true, () => refusedStartOf(requestId)), Match.when(false, () => allocatedDecisionOf(core, dynamicInstanceOf(core), requestId, at)), Match.exhaustive)), Match.exhaustive);
1163
+ const dynamicStopOf = (core, requestId, childId, generation) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("None", () => new Stale({})), Match.tag("Some", (found) => dynamicStopCurrentOf(core, found.value, requestId)), Match.exhaustive);
1164
+ const stoppable = (core, child) => Match.value(isDeclaredChild(core, child.childId)).pipe(Match.when(true, () => false), Match.when(false, () => child.status !== "stopping"), Match.exhaustive);
1165
+ const stoppingContinue = (core, child, requestId) => {
1166
+ const next = stoppingOf(child);
1167
+ return new Continue({
1168
+ core: withChildren(core, Array.map(core.children, replacing(next))),
1169
+ commands: commandsIn({
1170
+ stops: [stopCommandOf(core.policy, next)],
1171
+ replies: [replyStoppedOf(requestId)]
1172
+ })
910
1173
  });
911
- const reportExhausted = (cause) => Effect.gen(function* () {
912
- yield* Metric.update(Metric.withAttributes(supervisorExhaustionsCounter, { supervisor: sup.name }), 1);
913
- yield* reporter.onExhausted(sup.name, cause);
914
- yield* Option.match(Option.fromNullishOr(sup.reporter.onExhausted), {
915
- onNone: () => Effect.void,
916
- onSome: (fn) => fn(cause)
917
- });
1174
+ };
1175
+ const dynamicStopCurrentOf = (core, child, requestId) => Match.value(stoppable(core, child)).pipe(Match.when(true, () => stoppingContinue(core, child, requestId)), Match.when(false, () => new Stale({})), Match.exhaustive);
1176
+ const onChildStarted = (state, childId, generation) => Match.value(state).pipe(Match.tag("Running", ({ core }) => startedInRunning(core, childId, generation)), Match.tag("Restarting", ({ core }) => holdOf(core)), Match.tag("CoolingDown", ({ core }) => holdOf(core)), Match.tag("ShuttingDown", ({ core }) => holdOf(core)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1177
+ const onChildReady = (state, childId, generation, at) => Match.value(state).pipe(Match.tag("Running", ({ core }) => readyInRunning(core, childId, generation, at)), Match.tag("Restarting", ({ core }) => holdOf(core)), Match.tag("CoolingDown", ({ core }) => holdOf(core)), Match.tag("ShuttingDown", ({ core }) => holdOf(core)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1178
+ const onChildTerminated = (state, termination) => Match.value(state).pipe(Match.tag("Running", ({ core }) => terminatedRunning(core, {
1179
+ childId: termination.childId,
1180
+ generation: termination.generation,
1181
+ reason: termination.reason,
1182
+ at: termination.at
1183
+ })), Match.tag("Restarting", () => new Stale({})), Match.tag("CoolingDown", ({ core }) => holdOf(core)), Match.tag("ShuttingDown", ({ core }) => terminatedShuttingDown(core, ShuttingDownReasonOf(state), ShuttingDownExitOf(state), termination)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1184
+ const ShuttingDownReasonOf = (state) => Match.value(state).pipe(Match.tag("ShuttingDown", ({ reason }) => reason), Match.orElse(() => terminatedReason));
1185
+ const ShuttingDownExitOf = (state) => Match.value(state).pipe(Match.tag("ShuttingDown", ({ exit }) => exit), Match.orElse(() => requestedExit));
1186
+ const terminatedShuttingDown = (core, reason, exit, termination) => stoppedInShuttingDown(core, reason, exit, termination.childId, termination.generation);
1187
+ const stoppedInRunning = (core, childId, generation) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("Some", () => removalContinue(core, terminationOf(childId, generation, terminatedReason, 0))), Match.tag("None", () => new Stale({})), Match.exhaustive);
1188
+ const onChildStopped = (state, childId, generation) => Match.value(state).pipe(Match.tag("Running", ({ core }) => stoppedInRunning(core, childId, generation)), Match.tag("Restarting", () => new Stale({})), Match.tag("CoolingDown", ({ core }) => holdOf(core)), Match.tag("ShuttingDown", ({ core, reason, exit }) => stoppedInShuttingDown(core, reason, exit, childId, generation)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1189
+ const onProbeResult = (state, childId, generation, alive, at) => Match.value(state).pipe(Match.tag("Running", ({ core }) => probedInRunning(core, childId, generation, alive, at)), Match.tag("Restarting", () => new Stale({})), Match.tag("CoolingDown", ({ core }) => holdOf(core)), Match.tag("ShuttingDown", ({ core }) => holdOf(core)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1190
+ const onTimerElapsed = (state, kind, childId, generation, at) => Match.value(state).pipe(Match.tag("Running", ({ core }) => timerInRunning(core, childId, generation, kind, at)), Match.tag("Restarting", ({ core, pending }) => Match.value(childId).pipe(Match.when("", () => new Stale({})), Match.orElse((named) => backoffInRestarting(core, pending, named, generation, kind, at)))), Match.tag("CoolingDown", ({ core }) => coolDownElapsedOf(core, kind, at)), Match.tag("ShuttingDown", ({ core }) => holdOf(core)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1191
+ const coolDownElapsedOf = (core, kind, at) => Match.value(kind).pipe(Match.when("cool_down", () => cooledRestartOf(core, at)), Match.orElse(() => new Stale({})));
1192
+ const onDynamicStartRequested = (state, requestId, at) => Match.value(state).pipe(Match.tag("Running", ({ core }) => dynamicStartOf(core, requestId, at)), Match.tag("Restarting", () => refusedStartOf(requestId)), Match.tag("CoolingDown", () => refusedStartOf(requestId)), Match.tag("ShuttingDown", () => refusedStartOf(requestId)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1193
+ const onDynamicStopRequested = (state, requestId, childId, generation) => Match.value(state).pipe(Match.tag("Running", ({ core }) => dynamicStopOf(core, requestId, childId, generation)), Match.tag("Restarting", () => new Stale({})), Match.tag("CoolingDown", () => new Stale({})), Match.tag("ShuttingDown", () => new Stale({})), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1194
+ const onShutdownRequested = (state, reason) => Match.value(state).pipe(Match.tag("Running", ({ core }) => stopEverything(core, reason, requestedExit)), Match.tag("Restarting", ({ core }) => stopEverything(core, reason, requestedExit)), Match.tag("CoolingDown", ({ core }) => stopEverything(core, reason, requestedExit)), Match.tag("ShuttingDown", ({ core }) => holdOf(core)), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1195
+ const bootedChildrenOf = (core, at) => {
1196
+ const incarnationOf = (child) => ({
1197
+ childId: child.childId,
1198
+ generation: child.generation
918
1199
  });
919
- const runStrategy = superviseTree(sup.strategy, {
920
- name: sup.name,
921
- booted,
922
- health,
923
- policy,
924
- reportRestart,
925
- reportExhausted,
926
- intensityEff
1200
+ const deadlineOf = (child) => deadlineCommandOf(incarnationOf(child), at + kindOfPolicy(core.policy, child.childId).startTimeoutMillis);
1201
+ return new StartChildren({
1202
+ core,
1203
+ commands: commandsIn({
1204
+ starts: Array.map(core.children, (child) => startCommandOf(incarnationOf(child))),
1205
+ arms: Array.map(core.children, deadlineOf)
1206
+ })
927
1207
  });
928
- yield* Effect.andThen(health.paused.await, runStrategy);
1208
+ };
1209
+ const onSupervisorStarted = (state, at) => Match.value(state).pipe(Match.tag("Running", ({ core }) => bootedChildrenOf(core, at)), Match.tag("Restarting", () => new Stale({})), Match.tag("CoolingDown", () => new Stale({})), Match.tag("ShuttingDown", () => new Stale({})), Match.tag("Terminated", () => new Stale({})), Match.exhaustive);
1210
+ const decided = (state, event) => Match.value(event).pipe(Match.tag("SupervisorStarted", (started) => onSupervisorStarted(state, started.at)), Match.tag("ChildStarted", (started) => onChildStarted(state, started.childId, started.generation)), Match.tag("ChildReady", (ready) => onChildReady(state, ready.childId, ready.generation, ready.at)), Match.tag("ChildTerminated", (terminated) => onChildTerminated(state, terminationOf(terminated.childId, terminated.generation, terminated.reason, terminated.at))), Match.tag("ChildStopped", (stopped) => onChildStopped(state, stopped.childId, stopped.generation)), Match.tag("ProbeResult", (probe) => onProbeResult(state, probe.childId, probe.generation, probe.alive, probe.at)), Match.tag("TimerElapsed", (elapsed) => Match.value(elapsed.target).pipe(Match.tag("ChildTimer", (target) => onTimerElapsed(state, elapsed.kind, target.childId, target.generation, elapsed.at)), Match.tag("SupervisorTimer", () => onTimerElapsed(state, elapsed.kind, "", 0, elapsed.at)), Match.exhaustive)), Match.tag("DynamicStartRequested", (requested) => onDynamicStartRequested(state, requested.requestId, requested.at)), Match.tag("DynamicStopRequested", (requested) => onDynamicStopRequested(state, requested.requestId, requested.childId, requested.generation)), Match.tag("ShutdownRequested", (requested) => onShutdownRequested(state, requested.reason)), Match.exhaustive);
1211
+ const interpretSupervisionEvent = Workflow.make({
1212
+ command: SupervisionStep,
1213
+ decision: SupervisionDecision,
1214
+ error: Schema.Never,
1215
+ decide: (step) => Result.succeed(decided(step.state, step.event))
929
1216
  });
930
- const isWorker = (x) => WorkerTypeId in x;
931
- const bootChild = (child, reporter) => Effect.gen(function* () {
932
- if (isWorker(child)) {
933
- const health = yield* allocateWorkerHealth(child.name);
934
- const loop = buildWorkerLoop(child, health, healthStateGauge).pipe(Effect.orDie);
935
- return {
936
- name: child.name,
937
- health,
938
- run: loop,
939
- childPolicy: child.child
940
- };
941
- }
942
- const bootedChildren = yield* Effect.forEach(child.children, (c) => bootChild(c, reporter));
943
- const health = yield* allocateSupervisorHealth(child.name, bootedChildren.map((b) => b.health));
944
- const body = buildSupervisorBody(child, health, bootedChildren, reporter).pipe(Effect.orDie);
945
- return {
946
- name: child.name,
947
- health,
948
- run: body,
949
- childPolicy: {}
950
- };
1217
+ //#endregion
1218
+ //#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
+ var SupervisionEvolution = class extends Schema.TaggedClass()("SupervisionEvolution", {
1252
+ state: SupervisorState,
1253
+ decision: SupervisionDecision
1254
+ }) {
1255
+ static [Workflow.InstrumentationBrand] = {};
1256
+ };
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
+ const evolveSupervisor = Workflow.make({
1280
+ command: SupervisionEvolution,
1281
+ decision: SupervisorState,
1282
+ error: Schema.Never,
1283
+ decide: (step) => Result.succeed(evolved(step.state, step.decision))
951
1284
  });
952
- /** @internal */
953
- const supervisor$1 = Function.dual(3, (s, reporter, binding) => Effect.gen(function* () {
954
- const booted = yield* Effect.forEach(s.children, (child) => bootChild(child, reporter));
955
- const health = yield* allocateSupervisorHealth(s.name, booted.map((b) => b.health));
956
- const body = buildSupervisorBody(s, health, booted, reporter).pipe(Effect.orDie);
957
- const locked = withLockByMode(body, binding);
958
- yield* Effect.forkScoped(locked.pipe(Effect.orDie), { startImmediately: true });
959
- return health;
960
- }));
961
1285
  //#endregion
962
- //#region src/LeaderLock.ts
963
- const isModeNone = (lock) => lock.mode === "none";
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
+ };
964
1297
  //#endregion
965
- //#region src/RunSupervisor.ts
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)));
966
1356
  /**
967
- * The supervisor: acquires the `DaemonReporter` and — unless the lock mode is none —
968
- * the `LeaderLock` capabilities at the composition root, then hands them down to the
969
- * supervisor body via the lock binding. The body itself only ever sees the service
970
- * values.
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.
971
1360
  */
972
- const supervisor = (s) => Effect.gen(function* () {
973
- const reporter = yield* DaemonReporter;
974
- let binding;
975
- if (isModeNone(s.lock)) binding = { kind: "unlocked" };
976
- else {
977
- const lock = yield* LeaderLock;
978
- binding = {
979
- kind: "locked",
980
- spec: s.lock,
981
- lock
982
- };
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)
983
1367
  }
984
- return yield* supervisor$1(s, reporter, binding);
985
- });
986
- //#endregion
987
- //#region src/DaemonWorkerExecutor.ts
988
- const worker$2 = Function.dual(2, (w, binding) => Effect.gen(function* () {
989
- const health = yield* allocateWorkerHealth(w.name);
990
- const loop = buildWorkerLoop(w, health, healthStateGauge).pipe(Effect.orDie);
991
- const locked = withLockByMode(loop, binding);
992
- yield* Effect.forkScoped(locked.pipe(Effect.orDie));
993
- return health;
994
1368
  }));
995
- //#endregion
996
- //#region src/RunWorker.ts
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
+ });
997
1377
  /**
998
- * Boots a worker. The leader-lock capability is acquired here, at the composition
999
- * root, and handed down as part of the lock binding: the executor behind this
1000
- * entry point never sees the tag. A worker whose lock is `{ mode: 'none' }`
1001
- * takes no lock at all.
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.
1002
1380
  */
1003
- const worker = (w) => Effect.gen(function* () {
1004
- let binding;
1005
- if (isModeNone(w.lock)) binding = { kind: "unlocked" };
1006
- else {
1007
- const lock = yield* LeaderLock;
1008
- binding = {
1009
- kind: "locked",
1010
- spec: w.lock,
1011
- lock
1012
- };
1013
- }
1014
- return yield* worker$2(w, binding);
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));
1015
1390
  });
1016
- //#endregion
1017
- //#region src/SupervisionCustom.ts
1018
- const custom = (policy) => Effect.succeed(policy);
1019
- //#endregion
1020
- //#region src/SupervisionLeader.ts
1021
- const LeaderConfig = Context.Reference("@systemfsoftware/effect-daemon-spec/LeaderConfig", { defaultValue: () => ({
1022
- backoffBase: Duration.seconds(1),
1023
- intensity: UnboundedIntensity.make(),
1024
- cooldown: Duration.zero
1025
- }) });
1026
- const leader$1 = Function.dual(2, (config, cap) => Effect.succeed({
1027
- intensity: config.intensity,
1028
- backoff: cappedBackoff(config.backoffBase, cap),
1029
- cooldown: config.cooldown
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
+ })
1030
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
+ };
1031
1443
  //#endregion
1032
- //#region src/SupervisionTask.ts
1033
- const TaskConfig = Context.Reference("@systemfsoftware/effect-daemon-spec/TaskConfig", { defaultValue: () => ({
1034
- backoffBase: Duration.seconds(1),
1035
- intensity: UnboundedIntensity.make(),
1036
- cooldown: Duration.zero
1037
- }) });
1038
- const task$1 = Function.dual(2, (config, budget) => Effect.succeed({
1039
- intensity: config.intensity,
1040
- backoff: Schedule.exponential(config.backoffBase).pipe(Schedule.jittered, Schedule.upTo({ duration: budget })),
1041
- cooldown: config.cooldown
1042
- }));
1444
+ //#region src/Supervisor/supervisor-step.cell.ts
1445
+ const readStep = (runtime, event) => Effect.map(Effect.zip(Clock.currentTimeMillis, Ref.get(stateOf(runtime.acquired.handle))), ([now, state]) => new SupervisionStep({
1446
+ state,
1447
+ event: {
1448
+ ...event,
1449
+ at: now
1450
+ }
1451
+ }, { disableChecks: true }));
1452
+ const persistedOf = (previous, decision) => Result.getOrThrow(evolveSupervisor(new SupervisionEvolution({
1453
+ 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), {
1457
+ event,
1458
+ decision
1459
+ })));
1460
+ const runBucketsOf = (runtime, commands) => Commands.runBuckets(runtime.acquired, commands);
1461
+ const Steps = { runtimeOf: (acquired) => ({ acquired }) };
1462
+ const supervisorStepFor = (runtime) => Sandwich.named("supervisor.step")((event) => readStep(runtime, event)).decide(interpretSupervisionEvent).write({
1463
+ Stale: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), Commands.answerStale(runtime.acquired, command.event)),
1464
+ Continue: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1465
+ RestartChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1466
+ StartChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1467
+ CoolDown: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1468
+ StopChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1469
+ Terminate: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1470
+ RefuseDynamicStart: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1471
+ CommandRejected: (_rejected, command) => Effect.andThen(persistCommandRejection(runtime, command.event), Commands.answerStale(runtime.acquired, command.event))
1472
+ });
1473
+ const persistCommandRejection = (runtime, event) => PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1474
+ event,
1475
+ decision: new Stale({})
1476
+ }).pipe(Effect.asVoid);
1043
1477
  //#endregion
1044
- //#region src/SupervisionWorker.ts
1045
- const WorkerConfig = Context.Reference("@systemfsoftware/effect-daemon-spec/WorkerConfig", { defaultValue: () => ({
1046
- backoffBase: Duration.seconds(10),
1047
- intensity: BoundedIntensity.make({
1048
- restarts: 10,
1049
- window: Duration.seconds(60)
1050
- }),
1051
- cooldown: Duration.seconds(30)
1052
- }) });
1053
- const worker$1 = Function.dual(2, (config, cap) => Effect.succeed({
1054
- intensity: config.intensity,
1055
- backoff: cappedBackoff(config.backoffBase, cap),
1056
- cooldown: config.cooldown
1478
+ //#region src/Supervisor/Supervisor.ts
1479
+ const SpecTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/SupervisorSpec");
1480
+ const hasSpecTag = Predicate.hasProperty(SpecTypeId);
1481
+ 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
+ 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
+ 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
+ const fiberMediumOf = () => Effect.map(Effect.serviceOption(fiberPort), (found) => Option.match(found, {
1504
+ onNone: () => mediumFor(),
1505
+ onSome: (port) => port.medium
1057
1506
  }));
1058
- //#endregion
1059
- //#region src/SupervisorOneForAll.ts
1060
- const oneForAll$1 = (opts) => ({
1061
- [SupervisorTypeId]: SupervisorTypeId,
1062
- name: opts.name,
1063
- strategy: "one_for_all",
1064
- children: opts.children,
1065
- supervision: opts.supervision,
1066
- lock: opts.lock,
1067
- reporter: opts.reporter ?? {}
1507
+ const scopedOf = (parts) => Effect.gen(function* () {
1508
+ const supervisorScope = yield* Effect.scope;
1509
+ const initial = new Running$1({ core: initialStateOf(policyOfParts(parts)) });
1510
+ const bound = yield* Effect.forEach(parts.bindings, (entry) => Effect.map(entry.binding, (child) => [entry.declaration.childId, child]), { concurrency: 1 });
1511
+ const context = yield* Effect.context();
1512
+ const fiber = yield* fiberMediumOf();
1513
+ const handle = yield* RunningSupervisorHandle.make(parts.name, initial, HashMap.fromIterable(bound), context, fiber);
1514
+ const step = supervisorStepFor(Steps.runtimeOf({ handle }));
1515
+ yield* Effect.forkIn(drainOf(handle, step), supervisorScope);
1516
+ yield* offerEvent(handle, {
1517
+ _tag: "SupervisorStarted",
1518
+ at: 0
1519
+ });
1520
+ yield* Effect.addFinalizer(() => Effect.catchTag(shutdown(handle), "SupervisorTerminated", () => Effect.void));
1521
+ return handle;
1068
1522
  });
1069
- //#endregion
1070
- //#region src/SupervisorOneForOne.ts
1071
- const oneForOne$1 = (opts) => ({
1072
- [SupervisorTypeId]: SupervisorTypeId,
1073
- name: opts.name,
1523
+ const specOf = (parts) => {
1524
+ const scoped = scopedOf(parts);
1525
+ return {
1526
+ [SpecTypeId]: SpecTypeId,
1527
+ ...parts,
1528
+ scoped,
1529
+ layer: Layer.effectDiscard(Effect.asVoid(scoped)),
1530
+ ...Prototype
1531
+ };
1532
+ };
1533
+ const partsOf = (self) => ({
1534
+ name: self.name,
1535
+ strategy: self.strategy,
1536
+ intensity: self.intensity,
1537
+ periodMillis: self.periodMillis,
1538
+ autoShutdown: self.autoShutdown,
1539
+ coolDownMillis: self.coolDownMillis,
1540
+ backoff: self.backoff,
1541
+ livenessTickMillis: self.livenessTickMillis,
1542
+ declarations: self.declarations,
1543
+ bindings: self.bindings,
1544
+ dynamic: self.dynamic
1545
+ });
1546
+ const make = (name) => specOf({
1547
+ name,
1074
1548
  strategy: "one_for_one",
1075
- children: opts.children,
1076
- supervision: opts.supervision,
1077
- lock: opts.lock,
1078
- reporter: opts.reporter ?? {}
1549
+ intensity: 1,
1550
+ periodMillis: 5e3,
1551
+ autoShutdown: "never",
1552
+ coolDownMillis: void 0,
1553
+ backoff: {
1554
+ baseMillis: 0,
1555
+ multiplier: 1,
1556
+ capMillis: 0
1557
+ },
1558
+ livenessTickMillis: LIVENESS_TICK_MILLIS,
1559
+ declarations: [],
1560
+ bindings: [],
1561
+ dynamic: { _tag: "NoDynamicChildren" }
1079
1562
  });
1080
- //#endregion
1081
- //#region src/SupervisorRestForOne.ts
1082
- const restForOne$1 = (opts) => ({
1083
- [SupervisorTypeId]: SupervisorTypeId,
1084
- name: opts.name,
1085
- strategy: "rest_for_one",
1086
- children: opts.children,
1087
- supervision: opts.supervision,
1088
- lock: opts.lock,
1089
- reporter: opts.reporter ?? {}
1563
+ const strategy = dual(2, (self, strategy) => specOf({
1564
+ ...partsOf(self),
1565
+ strategy
1566
+ }));
1567
+ const intensity = dual(3, (self, intensity, periodMillis) => specOf({
1568
+ ...partsOf(self),
1569
+ intensity,
1570
+ periodMillis
1571
+ }));
1572
+ const autoShutdown = dual(2, (self, autoShutdown) => specOf({
1573
+ ...partsOf(self),
1574
+ autoShutdown
1575
+ }));
1576
+ const coolDown = dual(2, (self, millis) => specOf({
1577
+ ...partsOf(self),
1578
+ coolDownMillis: millis
1579
+ }));
1580
+ const backoff = dual(2, (self, schedule) => specOf({
1581
+ ...partsOf(self),
1582
+ backoff: schedule
1583
+ }));
1584
+ const livenessTick = dual(2, (self, millis) => specOf({
1585
+ ...partsOf(self),
1586
+ livenessTickMillis: millis
1587
+ }));
1588
+ const dynamicKindOf = (options) => ({
1589
+ _tag: "DynamicChildren",
1590
+ restartType: "permanent",
1591
+ shutdown: WORKER_SHUTDOWN,
1592
+ startTimeoutMillis: 5e3,
1593
+ probeFailureThreshold: 2,
1594
+ ...options
1090
1595
  });
1091
- //#endregion
1092
- //#region src/mod.ts
1093
- const poll = (opts) => poll$1(opts);
1094
- const stream = (opts) => stream$1(opts);
1095
- const subscription = (opts) => subscription$1(opts);
1096
- const Daemon = {
1097
- poll,
1098
- stream,
1099
- subscription
1100
- };
1101
- const run = {
1102
- worker,
1103
- supervisor,
1104
- dynamic: dynamic$1
1596
+ const dynamic = dual(2, (self, options) => specOf({
1597
+ ...partsOf(self),
1598
+ dynamic: dynamicKindOf(options)
1599
+ }));
1600
+ const declarationOf = (childId, nested, options) => ({
1601
+ childId,
1602
+ restartType: "permanent",
1603
+ shutdown: nested ? SUPERVISOR_SHUTDOWN : WORKER_SHUTDOWN,
1604
+ significant: false,
1605
+ startTimeoutMillis: 5e3,
1606
+ probeFailureThreshold: 2,
1607
+ ...options
1608
+ });
1609
+ const isNestedSpec = (value) => hasSpecTag(value) && value[SpecTypeId] === SpecTypeId;
1610
+ const nestedProgramOf = (nested) => (ready) => Effect.flatMap(nested.scoped, (handle) => Effect.andThen(ready, Effect.andThen(awaitTerminated(handle), Effect.interrupt)));
1611
+ const fiberMediumForChild = () => mediumFor();
1612
+ const bindFiberChild = (program) => Effect.gen(function* () {
1613
+ const context = yield* Effect.context();
1614
+ const runnable = typeof program === "function" ? program : readyOnStart(program);
1615
+ return Binder.bind(runnable, fiberMediumForChild(), context);
1616
+ });
1617
+ const bindNestedChild = (nested) => Effect.gen(function* () {
1618
+ const context = yield* Effect.context();
1619
+ return Binder.bind(nestedProgramOf(nested), fiberMediumForChild(), context);
1620
+ });
1621
+ const childSpecMake = (childId, program, options) => isNestedSpec(program) ? {
1622
+ childId,
1623
+ declaration: declarationOf(childId, true, options),
1624
+ binding: bindNestedChild(program),
1625
+ ...Prototype
1626
+ } : {
1627
+ childId,
1628
+ declaration: declarationOf(childId, false, options),
1629
+ binding: bindFiberChild(program),
1630
+ ...Prototype
1105
1631
  };
1106
- const leader = (cap) => Effect.flatMap(LeaderConfig, (config) => leader$1(config, cap));
1107
- const task = (budget) => Effect.flatMap(TaskConfig, (config) => task$1(config, budget));
1108
- const supervision = (cap) => Effect.flatMap(WorkerConfig, (config) => worker$1(config, cap));
1109
- const Supervision = {
1110
- leader,
1111
- worker: supervision,
1112
- task,
1113
- custom
1632
+ const childSpecOn = (port) => (childId, program, options) => ({
1633
+ childId,
1634
+ declaration: declarationOf(childId, false, options),
1635
+ binding: Effect.gen(function* () {
1636
+ const shape = yield* port;
1637
+ const context = yield* Effect.context();
1638
+ return Binder.bind(program, shape.medium, context);
1639
+ }),
1640
+ ...Prototype
1641
+ });
1642
+ /**
1643
+ * The two ways to declare a child: `make`, which binds to the fiber medium (and
1644
+ * to the `FiberMedium` port when one is provided), and `on`, which binds to a
1645
+ * named medium port (KTD9).
1646
+ */
1647
+ const ChildSpecs = {
1648
+ make: childSpecMake,
1649
+ on: childSpecOn
1114
1650
  };
1115
- const dynamic = (opts) => dynamic$2({
1116
- ...opts,
1117
- maxChildren: opts.maxChildren ?? MaxChildren.make(1e3)
1651
+ const children = dual(2, (self, specs) => specOf({
1652
+ ...partsOf(self),
1653
+ declarations: [...self.declarations, ...specs.map((spec) => spec.declaration)],
1654
+ bindings: [...self.bindings, ...specs.map((spec) => ({
1655
+ declaration: spec.declaration,
1656
+ binding: spec.binding
1657
+ }))]
1658
+ }));
1659
+ const child = dual((args) => isSupervisorSpec(args[0]), (self, childId, program, options) => children(self, [childSpecMake(childId, program, options)]));
1660
+ //#endregion
1661
+ //#region src/Supervisor/mod.ts
1662
+ var Supervisor_exports = /* @__PURE__ */ __exportAll({
1663
+ ChildSpecs: () => ChildSpecs,
1664
+ FiberMedium: () => FiberMedium_exports,
1665
+ Medium: () => Medium_exports,
1666
+ SpecTypeId: () => SpecTypeId,
1667
+ SupervisorTerminated: () => SupervisorTerminated,
1668
+ TypeId: () => TypeId,
1669
+ autoShutdown: () => autoShutdown,
1670
+ awaitTerminated: () => awaitTerminated,
1671
+ backoff: () => backoff,
1672
+ child: () => child,
1673
+ children: () => children,
1674
+ coolDown: () => coolDown,
1675
+ dynamic: () => dynamic,
1676
+ intensity: () => intensity,
1677
+ isRunningSupervisor: () => isRunningSupervisor,
1678
+ isSupervisorSpec: () => isSupervisorSpec,
1679
+ livenessTick: () => livenessTick,
1680
+ make: () => make,
1681
+ readyOnStart: () => readyOnStart,
1682
+ shutdown: () => shutdown,
1683
+ startChild: () => startChild,
1684
+ statusOf: () => statusOf,
1685
+ stopChild: () => stopChild,
1686
+ strategy: () => strategy,
1687
+ traceOf: () => traceOf
1118
1688
  });
1119
- const oneForAll = (opts) => oneForAll$1(opts);
1120
- const oneForOne = (opts) => oneForOne$1(opts);
1121
- const restForOne = (opts) => restForOne$1(opts);
1122
1689
  //#endregion
1123
- export { BoundedIntensity, ChildPolicyConfig, Daemon, DaemonReporter, DynamicLimitExceeded, DynamicSpecTypeId, Intensity, IntensityConfig, LeaderConfig, LeaderLock, LeaderLockFromPrimitive, LeaderLockInfraError, LeaderLockNotAcquired, LockPolicyConfig, LockPrimitive, LockPrimitiveError, MaxChildren, Noop, PollLoopTag, StreamLoopTag, SubscriptionLoopTag, Supervision, SupervisorTypeId, TaskConfig, TickPolicyConfig, UnboundedIntensity, WorkerConfig, WorkerTypeId, cappedBackoff, dynamic, healthStateGauge, leader, oneForAll, oneForOne, poll, restForOne, run, stream, subscription, supervision, supervisor, supervisorChildrenGauge, supervisorExhaustionsCounter, supervisorRestartsCounter, task, withLeaderLock, worker };
1690
+ export { Supervisor_exports as Supervisor };