@systemfsoftware/effect-daemon-spec 4.1.1 → 4.2.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,1730 @@
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, SchemaGetter, 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/boundary-testing/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
+ const PolicyGenerated = 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 decodable = (holds) => holds.every((single) => single);
152
+ const declarationOf$2 = (seed, index, autoShutdown) => ({
153
+ childId: `c${index}`,
154
+ restartType: seed.restartType,
155
+ shutdown: seed.shutdown,
156
+ significant: decodable([
157
+ seed.significantBit,
158
+ seed.restartType !== "permanent",
159
+ autoShutdown !== "never"
160
+ ]),
161
+ startTimeoutMillis: seed.startTimeoutMillis,
162
+ probeFailureThreshold: seed.probeFailureThreshold
163
+ });
164
+ const seedOf = (declaration) => ({
165
+ restartType: declaration.restartType,
166
+ significantBit: declaration.significant,
167
+ shutdown: declaration.shutdown,
168
+ startTimeoutMillis: declaration.startTimeoutMillis,
169
+ probeFailureThreshold: declaration.probeFailureThreshold
170
+ });
171
+ const policyOf = (generated) => new SupervisionPolicy({
172
+ strategy: generated.strategy,
173
+ intensity: generated.intensity,
174
+ periodMillis: generated.periodMillis,
175
+ autoShutdown: generated.autoShutdown,
176
+ coolDown: generated.coolDown,
177
+ backoff: generated.backoff,
178
+ dynamic: generated.dynamic,
179
+ livenessTickMillis: generated.livenessTickMillis,
180
+ childDeclarations: Array.map(generated.childSeeds, (seed, index) => declarationOf$2(seed, index, generated.autoShutdown))
181
+ });
182
+ const generatedFromPolicy = (policy) => ({
183
+ strategy: policy.strategy,
184
+ intensity: policy.intensity,
185
+ periodMillis: policy.periodMillis,
186
+ autoShutdown: policy.autoShutdown,
187
+ coolDown: policy.coolDown,
188
+ backoff: policy.backoff,
189
+ dynamic: policy.dynamic,
190
+ livenessTickMillis: policy.livenessTickMillis,
191
+ childSeeds: Array.map(policy.childDeclarations, seedOf)
192
+ });
193
+ var SupervisionPolicy = class extends Schema.Class("SupervisionPolicy")(Schema.Struct(policyFields).check(Schema.makeFilter(policyIsDecodable, { message: POLICY_REFUSAL_MESSAGE })), { toCodecArbitrary: () => Schema.link()(PolicyGenerated, {
194
+ decode: SchemaGetter.transform((generated) => policyOf(generated)),
195
+ encode: SchemaGetter.transform(generatedFromPolicy)
196
+ }) }) {};
86
197
  //#endregion
87
- //#region src/LoopTags.ts
198
+ //#region src/kernel/TerminationReport.schema.ts
199
+ /**
200
+ * What a medium can say about why a child died (R16): a fiber supplies a cause, a process
201
+ * supplies an exit status and signal, and a remote runner's death is inferred. No event
202
+ * claims a level its medium cannot supply — the medium declares which one it reports, and
203
+ * the kernel assumes nothing beyond that declaration.
204
+ */
205
+ const CauseReport = Schema.TaggedStruct("CauseReport", { cause: Schema.String });
206
+ const ExitReport = Schema.TaggedStruct("ExitReport", {
207
+ code: Schema.Int,
208
+ signal: Schema.String
209
+ });
210
+ const InferredReport = Schema.TaggedStruct("InferredReport", { failedProbes: ProbeThreshold });
211
+ const DeadlineMissedReport = Schema.TaggedStruct("DeadlineMissed", { waitedMillis: Schema.Int });
212
+ const FailureReport = Schema.Union([
213
+ CauseReport,
214
+ ExitReport,
215
+ InferredReport,
216
+ DeadlineMissedReport
217
+ ]);
218
+ const NormalTermination = Schema.TaggedStruct("Normal", {});
219
+ const ShutdownTermination = Schema.TaggedStruct("Shutdown", {});
220
+ const AbnormalTermination = Schema.TaggedStruct("Abnormal", { report: FailureReport });
221
+ const TerminationReason = Schema.Union([
222
+ NormalTermination,
223
+ ShutdownTermination,
224
+ AbnormalTermination
225
+ ]);
88
226
  /**
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.
227
+ * Why the supervisor itself is terminating: a shutdown something asked of it, or a
228
+ * give-up after its children terminated more often than its intensity allows. The
229
+ * decision and command data carry this, so the shell never infers which one it is.
230
+ * A give-up names the child incarnation whose termination exhausted the intensity.
93
231
  */
94
- const PollLoopTag = { _tag: "Poll" };
95
- const StreamLoopTag = { _tag: "Stream" };
96
- const SubscriptionLoopTag = { _tag: "Subscription" };
232
+ const RequestedExit = Schema.TaggedStruct("RequestedExit", {});
233
+ const IntensityExceededExit = Schema.TaggedStruct("IntensityExceededExit", {
234
+ childId: ChildId,
235
+ generation: Generation
236
+ });
237
+ const SupervisorExit = Schema.Union([RequestedExit, IntensityExceededExit]);
97
238
  //#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
- };
239
+ //#region src/Supervisor/MediumDeclaration.schema.ts
240
+ /**
241
+ * What a medium can say about why a child died (R16, KTD8): the in-process fiber
242
+ * medium reports a full `Cause`, a process, socket or microVM medium reports the
243
+ * exit status and signal it observed, and the cluster medium's death is only
244
+ * inferred from failed liveness probes (KTD7). The kernel assumes nothing beyond
245
+ * the declared level; the conformance kit projects traces down to it.
246
+ */
247
+ const MediumReporting = Schema.Literals([
248
+ "full",
249
+ "exit",
250
+ "inferred"
251
+ ]);
252
+ /**
253
+ * The `one_for_all` guarantee a medium can honour (R16, KTD8): `atomic` means no
254
+ * child is left running once the group stop returns, `eventual` means teardown
255
+ * continues on the medium's own clock after the call returns.
256
+ */
257
+ const GroupStopGuarantee = Schema.Literals(["atomic", "eventual"]);
258
+ /**
259
+ * A medium's declaration to the kernel (R16). Both fields are required: a
260
+ * declaration without a reporting level or a group-stop guarantee is refused at
261
+ * decode, so the kernel never guesses what a medium can say or honour.
262
+ */
263
+ const MediumDeclaration = Schema.Struct({
264
+ reporting: MediumReporting,
265
+ groupStop: GroupStopGuarantee
266
+ });
136
267
  //#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
268
+ //#region src/Supervisor/Medium.ts
269
+ var Medium_exports = /* @__PURE__ */ __exportAll({
270
+ AbnormalTermination: () => AbnormalTermination,
271
+ BrutalShutdown: () => BrutalShutdown,
272
+ CauseReport: () => CauseReport,
273
+ DeadlineMissedReport: () => DeadlineMissedReport,
274
+ ExitReport: () => ExitReport,
275
+ FailureReport: () => FailureReport,
276
+ GracefulShutdown: () => GracefulShutdown,
277
+ GroupStopGuarantee: () => GroupStopGuarantee,
278
+ InferredReport: () => InferredReport,
279
+ InfinityShutdown: () => InfinityShutdown,
280
+ MediumDeclaration: () => MediumDeclaration,
281
+ MediumPort: () => MediumPort,
282
+ MediumReporting: () => MediumReporting,
283
+ NormalTermination: () => NormalTermination,
284
+ ShutdownMode: () => ShutdownMode,
285
+ ShutdownTermination: () => ShutdownTermination,
286
+ StartedTypeId: () => StartedTypeId,
287
+ StoppedTypeId: () => StoppedTypeId,
288
+ TerminationReason: () => TerminationReason,
289
+ make: () => make$1,
290
+ started: () => started,
291
+ stopped: () => stopped
292
+ });
293
+ const StartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/Medium/Started");
294
+ const StoppedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/Medium/Stopped");
295
+ /** Mint `Started` evidence for a child whose readiness completes `ready`. */
296
+ const started = (ready) => ({
297
+ [StartedTypeId]: StartedTypeId,
298
+ ready
299
+ });
300
+ /** The single `Stopped` evidence value every medium returns from `stop`. */
301
+ const stopped = { [StoppedTypeId]: StoppedTypeId };
302
+ /**
303
+ * KTD8: a medium exists only through `make`, whose options record requires every
304
+ * obligation. `stop` is wrapped in an uninterruptible region, so owned shutdown
305
+ * honouring R4's modes cannot be interrupted part-way (R15).
306
+ */
307
+ const make$1 = (options) => ({
308
+ ...options,
309
+ stop: (evidence, mode) => Effect.uninterruptible(options.stop(evidence, mode))
153
310
  });
311
+ /** Declare a medium port keyed to the program type it interprets (KTD9). */
312
+ const MediumPort = (key) => Context.Service(key);
154
313
  //#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)
314
+ //#region src/Supervisor/FiberMedium.ts
315
+ var FiberMedium_exports = /* @__PURE__ */ __exportAll({
316
+ failureCauseOf: () => failureCauseOf,
317
+ fiberPort: () => fiberPort,
318
+ medium: () => medium,
319
+ mediumFor: () => mediumFor,
320
+ readyOnStart: () => readyOnStart
321
+ });
322
+ const readyOnStart = (program) => (ready) => Effect.andThen(ready, program);
323
+ const fiberPort = MediumPort("FiberMedium");
324
+ const FiberStartedTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/FiberMedium/Started");
325
+ const fiberStarted = (fiber, scope, ready) => ({
326
+ [StartedTypeId]: StartedTypeId,
327
+ [FiberStartedTypeId]: FiberStartedTypeId,
328
+ fiber,
329
+ ready,
330
+ scope
331
+ });
332
+ const isFiberStarted = (evidence) => FiberStartedTypeId in evidence;
333
+ const fiberOf = (evidence) => Option.liftPredicate(evidence, isFiberStarted);
334
+ const normalTermination = { _tag: "Normal" };
335
+ const shutdownTermination = { _tag: "Shutdown" };
336
+ const abnormalOf = (cause) => ({
337
+ _tag: "Abnormal",
338
+ report: {
339
+ _tag: "CauseReport",
340
+ cause: Cause.pretty(cause)
341
+ }
342
+ });
343
+ const terminationOf$1 = (exit) => Exit.match(exit, {
344
+ onSuccess: () => normalTermination,
345
+ onFailure: (cause) => Cause.hasInterruptsOnly(cause) ? shutdownTermination : abnormalOf(cause)
346
+ });
347
+ const closedChild = (self) => Scope.close(self.scope, Exit.void);
348
+ const forcedChild = (self) => Fiber.interrupt(self.fiber);
349
+ /**
350
+ * OTP's timed shutdown: the signal (interruption) goes out at once, and the window
351
+ * bounds only how long the stop waits for the child's finalizers before closing its
352
+ * scope.
353
+ */
354
+ const signalledWithin = (self, millis) => Effect.andThen(Effect.timeoutOption(forcedChild(self), Duration.millis(millis)), closedChild(self));
355
+ 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);
356
+ const failureCauseOf = (evidence) => Option.map(fiberOf(evidence), (self) => Effect.map(Fiber.await(self.fiber), Exit.getCause));
357
+ const mediumFor = () => make$1({
358
+ declaration: {
359
+ reporting: "full",
360
+ groupStop: "atomic"
166
361
  },
167
- child: orEmpty(opts.child),
168
- tick: opts.tick,
169
- tickHooks: orEmpty(opts.tickHooks),
170
- lock: opts.lock
362
+ start: (program) => Effect.gen(function* () {
363
+ const scope = yield* Effect.scope;
364
+ const signalled = yield* Deferred.make();
365
+ const fiber = yield* Effect.forkIn(program(Deferred.succeed(signalled, void 0)), scope);
366
+ return fiberStarted(fiber, scope, Deferred.await(signalled));
367
+ }),
368
+ report: (evidence) => Option.match(fiberOf(evidence), {
369
+ onNone: () => Effect.succeed(shutdownTermination),
370
+ onSome: (self) => Effect.map(Fiber.await(self.fiber), terminationOf$1)
371
+ }),
372
+ probe: (evidence) => Option.match(fiberOf(evidence), {
373
+ onNone: () => Effect.succeed(false),
374
+ onSome: (self) => Effect.sync(() => self.fiber.pollUnsafe() === void 0)
375
+ }),
376
+ stop: (evidence, mode) => Option.match(fiberOf(evidence), {
377
+ onNone: () => Effect.succeed(stopped),
378
+ onSome: (self) => Effect.as(stopOf(self, mode), stopped)
379
+ })
171
380
  });
381
+ const medium = mediumFor();
172
382
  //#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
- };
383
+ //#region src/Supervisor/bound-child.ts
384
+ const rendered = (failure) => ({
385
+ _tag: "Abnormal",
386
+ report: {
387
+ _tag: "CauseReport",
388
+ cause: Cause.pretty(Cause.fail(failure))
389
+ }
258
390
  });
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
- }
391
+ const reasonOf = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => ({
392
+ _tag: "Abnormal",
393
+ report: {
394
+ _tag: "CauseReport",
395
+ cause: Cause.pretty(cause)
396
+ }
397
+ }));
398
+ const startOf = (program, medium, context) => Effect.gen(function* () {
399
+ const parent = yield* Effect.scope;
400
+ const child = yield* Scope.fork(parent);
401
+ const scoped = Context.add(context, Scope.Scope, child);
402
+ const outcome = yield* Effect.exit(Effect.setContext(Effect.mapError(medium.start(program), rendered), scoped));
403
+ return yield* Exit.match(outcome, {
404
+ onSuccess: (evidence) => Effect.succeed(evidence),
405
+ onFailure: (cause) => Effect.andThen(Scope.close(child, Exit.void), Effect.fail(reasonOf(cause)))
413
406
  });
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
407
  });
426
- const dynamic$1 = (spec) => Effect.gen(function* () {
427
- const health = yield* allocateSupervisorHealth(spec.name, []);
428
- return yield* buildDynamic(spec, health);
408
+ const bind = (program, medium, context) => ({
409
+ start: startOf(program, medium, context),
410
+ report: (evidence) => Effect.setContext(medium.report(evidence), context),
411
+ probe: (evidence) => Effect.setContext(medium.probe(evidence), context),
412
+ stop: (evidence, mode) => Effect.setContext(medium.stop(evidence, mode), context)
429
413
  });
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
414
  /**
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.
415
+ * Binds a program to the medium that interprets it, capturing the services
416
+ * resolved at acquisition: the medium's own requirements are read from
417
+ * `context` once, and `start` forks a fresh child scope so closing that scope
418
+ * owns the child's shutdown (KTD9).
453
419
  */
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";
420
+ const Binder = { bind };
421
+ //#endregion
422
+ //#region src/Supervisor/running-supervisor.handle.ts
423
+ /** Brands a running supervisor handle. */
424
+ const TypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/RunningSupervisor");
425
+ const RunningSupervisorDef = Handle.make()(TypeId);
426
+ /** Whether a value is a running supervisor handle. */
427
+ const isRunningSupervisor = RunningSupervisorDef.is;
428
+ const RunningSupervisorHandle = { make: (name, initial, children, context, fiber) => Effect.gen(function* () {
429
+ const scope = yield* Effect.scope;
430
+ const slot = {
431
+ state: yield* Ref.make(initial),
432
+ mailbox: yield* Queue.unbounded(),
433
+ trace: yield* PubSub.unbounded(),
434
+ evidence: yield* Ref.make(HashMap.empty()),
435
+ replies: yield* Ref.make(HashMap.empty()),
436
+ boundChildren: yield* Ref.make(children),
437
+ pending: yield* Ref.make(HashMap.empty()),
438
+ requests: yield* Ref.make(0),
439
+ terminated: yield* Deferred.make(),
440
+ scope,
441
+ context,
442
+ fiber
443
+ };
444
+ return RunningSupervisorDef.make({ name }, slot);
445
+ }) };
446
+ const stateOf = (self) => RunningSupervisorDef.slot(self).state;
447
+ const mailboxOf = (self) => RunningSupervisorDef.slot(self).mailbox;
448
+ const tracePubSubOf = (self) => RunningSupervisorDef.slot(self).trace;
449
+ const evidenceOf = (self) => RunningSupervisorDef.slot(self).evidence;
450
+ const repliesOf = (self) => RunningSupervisorDef.slot(self).replies;
451
+ const boundChildrenOf = (self) => RunningSupervisorDef.slot(self).boundChildren;
452
+ const pendingChildrenOf = (self) => RunningSupervisorDef.slot(self).pending;
453
+ const fiberContextOf = (self) => RunningSupervisorDef.slot(self).context;
454
+ const fiberMediumOf$1 = (self) => RunningSupervisorDef.slot(self).fiber;
455
+ /** The fiber medium bound to `program`, ready to be stored as a dynamic child. */
456
+ const boundFiberProgramOf = (self, program) => Binder.bind(program, fiberMediumOf$1(self), fiberContextOf(self));
457
+ const terminatedLatchOf = (self) => RunningSupervisorDef.slot(self).terminated;
458
+ const ownerScopeOf = (self) => RunningSupervisorDef.slot(self).scope;
461
459
  /**
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`.
460
+ * The kernel trace: every step's decoded event and decision, in mailbox order,
461
+ * from the moment the stream is subscribed.
468
462
  */
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
463
+ const traceOf = (self) => Stream.fromPubSub(RunningSupervisorDef.slot(self).trace);
464
+ /** The supervisor's current phase and children, as the kernel last folded them. */
465
+ const statusOf = (self) => Ref.get(RunningSupervisorDef.slot(self).state);
466
+ const offerEvent = dual(2, (self, event) => Effect.asVoid(Queue.offer(RunningSupervisorDef.slot(self).mailbox, event)));
467
+ const shutdownEventOf = (now) => ({
468
+ _tag: "ShutdownRequested",
469
+ at: now,
470
+ reason: { _tag: "Shutdown" }
495
471
  });
472
+ /** Completes once the supervisor has terminated; fails when it gave up. */
473
+ const awaitTerminated = (self) => Deferred.await(RunningSupervisorDef.slot(self).terminated);
496
474
  /**
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.
475
+ * Asks the supervisor to shut down and waits until it has terminated: children stop
476
+ * in reverse start order through their media before this completes.
508
477
  */
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 }));
478
+ 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)))));
479
+ const nextRequestId = (self, kind) => Effect.map(Ref.getAndUpdate(RunningSupervisorDef.slot(self).requests, (count) => count + 1), (count) => `${kind}-${count}`);
480
+ 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) => {
481
+ const event = eventOf(now);
482
+ 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)))));
483
+ })));
522
484
  /**
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`.
485
+ * Starts a dynamic child running `program`. The supervisor allocates its id and
486
+ * answers `accepted` with that id, or `refused` at the declared ceiling.
532
487
  */
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
488
+ 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) => ({
489
+ _tag: "DynamicStartRequested",
490
+ at: now,
491
+ requestId
492
+ })))));
542
493
  /**
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.
494
+ * Stops the dynamic child's named incarnation and removes it. Answers `stopped`, or
495
+ * `missed` when that incarnation is no longer current.
547
496
  */
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;
497
+ const stopChild = dual(3, (self, childId, generation) => Effect.flatMap(nextRequestId(self, "stop"), (requestId) => awaitReply(self, requestId, (now) => ({
498
+ _tag: "DynamicStopRequested",
499
+ at: now,
500
+ requestId,
501
+ childId,
502
+ generation
503
+ }))));
504
+ const resolveWaiting = (replies, requestId, outcome) => Effect.flatMap(Ref.modify(replies, (pending) => [HashMap.get(pending, requestId), HashMap.remove(pending, requestId)]), Option.match({
505
+ onNone: () => Effect.void,
506
+ onSome: (waiter) => Effect.asVoid(Deferred.succeed(waiter, outcome))
507
+ }));
508
+ const staleOf = (event) => Match.value(event).pipe(Match.when({ _tag: "DynamicStartRequested" }, () => ({ outcome: "refused" })), Match.orElse(() => ({ outcome: "missed" })));
509
+ const Ops = {
510
+ resolveWaiting,
511
+ staleOf
562
512
  };
513
+ //#endregion
514
+ //#region src/kernel/initial-supervisor-state.ts
515
+ const initialStateOf = (policy) => ({
516
+ policy,
517
+ children: Array.map(policy.childDeclarations, (declaration) => ({
518
+ childId: declaration.childId,
519
+ generation: 0,
520
+ status: "starting",
521
+ consecutiveRestarts: 0,
522
+ probeFailures: 0
523
+ })),
524
+ restartStamps: [],
525
+ nextOrdinal: 0
526
+ });
527
+ //#endregion
528
+ //#region src/kernel/SupervisionEvent.schema.ts
529
+ const TimerKind = Schema.Literals([
530
+ "start_deadline",
531
+ "backoff",
532
+ "liveness_tick",
533
+ "cool_down"
534
+ ]);
535
+ const ChildTimerTarget = Schema.TaggedStruct("ChildTimer", {
536
+ childId: ChildId,
537
+ generation: Generation
538
+ });
539
+ const SupervisorTimerTarget = Schema.TaggedStruct("SupervisorTimer", {});
540
+ const TimerTarget = Schema.Union([ChildTimerTarget, SupervisorTimerTarget]);
563
541
  /**
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.
542
+ * The boot event: the handle enqueues exactly one as its first envelope, so the
543
+ * declared children start by an ordinary kernel decision rather than by builder
544
+ * logic. It carries no child identity because it names them all, in declared order.
567
545
  */
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) }))))
546
+ const SupervisorStarted = Schema.TaggedStruct("SupervisorStarted", { at: EventTime });
547
+ const ChildStarted = Schema.TaggedStruct("ChildStarted", {
548
+ at: EventTime,
549
+ childId: ChildId,
550
+ generation: Generation
551
+ });
552
+ const ChildReady = Schema.TaggedStruct("ChildReady", {
553
+ at: EventTime,
554
+ childId: ChildId,
555
+ generation: Generation
556
+ });
557
+ const ChildTerminated = Schema.TaggedStruct("ChildTerminated", {
558
+ at: EventTime,
559
+ childId: ChildId,
560
+ generation: Generation,
561
+ reason: TerminationReason
579
562
  });
563
+ const ChildStopped = Schema.TaggedStruct("ChildStopped", {
564
+ at: EventTime,
565
+ childId: ChildId,
566
+ generation: Generation
567
+ });
568
+ const ProbeResult = Schema.TaggedStruct("ProbeResult", {
569
+ at: EventTime,
570
+ childId: ChildId,
571
+ generation: Generation,
572
+ alive: Schema.Boolean
573
+ });
574
+ const TimerElapsed = Schema.TaggedStruct("TimerElapsed", {
575
+ at: EventTime,
576
+ kind: TimerKind,
577
+ target: TimerTarget
578
+ });
579
+ const DynamicStartRequested = Schema.TaggedStruct("DynamicStartRequested", {
580
+ at: EventTime,
581
+ requestId: RequestId
582
+ });
583
+ const DynamicStopRequested = Schema.TaggedStruct("DynamicStopRequested", {
584
+ at: EventTime,
585
+ requestId: RequestId,
586
+ childId: ChildId,
587
+ generation: Generation
588
+ });
589
+ const ShutdownRequested = Schema.TaggedStruct("ShutdownRequested", {
590
+ at: EventTime,
591
+ reason: TerminationReason
592
+ });
593
+ const SupervisionEvent = Schema.Union([
594
+ SupervisorStarted,
595
+ ChildStarted,
596
+ ChildReady,
597
+ ChildTerminated,
598
+ ChildStopped,
599
+ ProbeResult,
600
+ TimerElapsed,
601
+ DynamicStartRequested,
602
+ DynamicStopRequested,
603
+ ShutdownRequested
604
+ ]);
580
605
  //#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);
606
+ //#region src/kernel/SupervisionTypeIds.ts
607
+ const DecisionTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionDecision");
608
+ const StateTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisorState");
591
609
  //#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
- }));
610
+ //#region src/kernel/SupervisorCommand.schema.ts
611
+ const StartChild = Schema.TaggedStruct("StartChild", {
612
+ childId: ChildId,
613
+ generation: Generation
614
+ });
615
+ const StopChild = Schema.TaggedStruct("StopChild", {
616
+ childId: ChildId,
617
+ generation: Generation,
618
+ shutdown: ShutdownMode
619
+ });
620
+ const ArmChildTimer = Schema.TaggedStruct("ArmChildTimer", {
621
+ kind: TimerKind,
622
+ childId: ChildId,
623
+ generation: Generation,
624
+ deadline: Deadline
625
+ });
626
+ const ArmSupervisorTimer = Schema.TaggedStruct("ArmSupervisorTimer", {
627
+ kind: TimerKind,
628
+ deadline: Deadline
629
+ });
630
+ const ReplyStartAccepted = Schema.TaggedStruct("ReplyStartAccepted", {
631
+ requestId: RequestId,
632
+ childId: ChildId,
633
+ generation: Generation
634
+ });
635
+ const ReplyStartRefused = Schema.TaggedStruct("ReplyStartRefused", { requestId: RequestId });
636
+ const ReplyStopped = Schema.TaggedStruct("ReplyStopped", { requestId: RequestId });
637
+ const TerminateSupervisor = Schema.TaggedStruct("TerminateSupervisor", {
638
+ reason: TerminationReason,
639
+ exit: SupervisorExit
640
+ });
641
+ Schema.Union([
642
+ StartChild,
643
+ StopChild,
644
+ ArmChildTimer,
645
+ ArmSupervisorTimer,
646
+ ReplyStartAccepted,
647
+ ReplyStartRefused,
648
+ ReplyStopped,
649
+ TerminateSupervisor
650
+ ]);
651
+ const SupervisorArm = Schema.Union([ArmChildTimer, ArmSupervisorTimer]);
652
+ const SupervisorReply = Schema.Union([
653
+ ReplyStartAccepted,
654
+ ReplyStartRefused,
655
+ ReplyStopped
656
+ ]);
657
+ const SupervisorCommands = Schema.Struct({
658
+ stops: Schema.Array(StopChild),
659
+ starts: Schema.Array(StartChild),
660
+ arms: Schema.Array(SupervisorArm),
661
+ replies: Schema.Array(SupervisorReply),
662
+ terminates: Schema.Array(TerminateSupervisor)
663
+ });
623
664
  //#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]))));
665
+ //#region src/kernel/SupervisorState.schema.ts
666
+ const ChildStatus = Schema.Literals([
667
+ "starting",
668
+ "ready",
669
+ "stopping"
670
+ ]);
671
+ const ChildInstance = Schema.Struct({
672
+ childId: ChildId,
673
+ generation: Generation,
674
+ status: ChildStatus,
675
+ consecutiveRestarts: RestartCount,
676
+ probeFailures: ProbeFailures
677
+ });
678
+ const SupervisorCore = Schema.Struct({
679
+ policy: SupervisionPolicy,
680
+ children: Schema.Array(ChildInstance),
681
+ restartStamps: Schema.Array(EventTime),
682
+ nextOrdinal: Ordinal
683
+ });
684
+ const ChildStart = Schema.Struct({
685
+ childId: ChildId,
686
+ generation: Generation
687
+ });
627
688
  //#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;
689
+ //#region src/kernel/interpret-supervision-event.workflow.ts
690
+ var Stale = class extends Schema.TaggedClass()("Stale", {}) {
691
+ [DecisionTypeId] = DecisionTypeId;
633
692
  };
634
- /** @internal */
635
- var RestartEpoch = class extends Schema.TaggedClass()("RestartEpoch", {}) {
636
- [EpochStepTypeId] = EpochStepTypeId;
693
+ var Continue = class extends Schema.TaggedClass()("Continue", {
694
+ core: SupervisorCore,
695
+ commands: SupervisorCommands
696
+ }) {
697
+ [DecisionTypeId] = DecisionTypeId;
637
698
  };
638
- /** @internal */
639
- var CooldownEpoch = class extends Schema.TaggedClass()("CooldownEpoch", {}) {
640
- [EpochStepTypeId] = EpochStepTypeId;
699
+ var RestartChildren = class extends Schema.TaggedClass()("RestartChildren", {
700
+ core: SupervisorCore,
701
+ pending: Schema.Array(ChildStart),
702
+ commands: SupervisorCommands
703
+ }) {
704
+ [DecisionTypeId] = DecisionTypeId;
641
705
  };
642
- Schema.Union([
643
- StopEpoch,
644
- RestartEpoch,
645
- CooldownEpoch
706
+ var StartChildren = class extends Schema.TaggedClass()("StartChildren", {
707
+ core: SupervisorCore,
708
+ commands: SupervisorCommands
709
+ }) {
710
+ [DecisionTypeId] = DecisionTypeId;
711
+ };
712
+ var CoolDown = class extends Schema.TaggedClass()("CoolDown", {
713
+ core: SupervisorCore,
714
+ millis: PositiveMillis,
715
+ commands: SupervisorCommands
716
+ }) {
717
+ [DecisionTypeId] = DecisionTypeId;
718
+ };
719
+ var StopChildren = class extends Schema.TaggedClass()("StopChildren", {
720
+ core: SupervisorCore,
721
+ reason: TerminationReason,
722
+ exit: SupervisorExit,
723
+ commands: SupervisorCommands
724
+ }) {
725
+ [DecisionTypeId] = DecisionTypeId;
726
+ };
727
+ var Terminate = class extends Schema.TaggedClass()("Terminate", {
728
+ reason: TerminationReason,
729
+ commands: SupervisorCommands
730
+ }) {
731
+ [DecisionTypeId] = DecisionTypeId;
732
+ };
733
+ var RefuseDynamicStart = class extends Schema.TaggedClass()("RefuseDynamicStart", { commands: SupervisorCommands }) {
734
+ [DecisionTypeId] = DecisionTypeId;
735
+ };
736
+ const SupervisionDecision = Schema.Union([
737
+ Stale,
738
+ Continue,
739
+ RestartChildren,
740
+ StartChildren,
741
+ CoolDown,
742
+ StopChildren,
743
+ Terminate,
744
+ RefuseDynamicStart
646
745
  ]);
647
- const SupervisionEpochResultTypeId = Symbol.for("@systemfsoftware/effect-daemon/SupervisionEpochResult");
648
- /** @internal */
649
- var StopSupervision = class extends Schema.TaggedClass()("StopSupervision", {}) {
650
- [SupervisionEpochResultTypeId] = SupervisionEpochResultTypeId;
746
+ var Running$1 = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
747
+ [StateTypeId] = StateTypeId;
651
748
  };
652
- /** @internal */
653
- var ContinueSupervision = class extends Schema.TaggedClass()("ContinueSupervision", {}) {
654
- [SupervisionEpochResultTypeId] = SupervisionEpochResultTypeId;
749
+ var Restarting$1 = class extends Schema.TaggedClass()("Restarting", {
750
+ core: SupervisorCore,
751
+ pending: Schema.Array(ChildStart)
752
+ }) {
753
+ [StateTypeId] = StateTypeId;
655
754
  };
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);
755
+ var CoolingDown$1 = class extends Schema.TaggedClass()("CoolingDown", {
756
+ core: SupervisorCore,
757
+ millis: PositiveMillis
758
+ }) {
759
+ [StateTypeId] = StateTypeId;
671
760
  };
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);
761
+ var ShuttingDown$1 = class extends Schema.TaggedClass()("ShuttingDown", {
762
+ core: SupervisorCore,
763
+ reason: TerminationReason,
764
+ exit: SupervisorExit
765
+ }) {
766
+ [StateTypeId] = StateTypeId;
767
+ };
768
+ var Terminated$1 = class extends Schema.TaggedClass()("Terminated", { reason: TerminationReason }) {
769
+ [StateTypeId] = StateTypeId;
770
+ };
771
+ const SupervisorState$1 = Schema.Union([
772
+ Running$1,
773
+ Restarting$1,
774
+ CoolingDown$1,
775
+ ShuttingDown$1,
776
+ Terminated$1
777
+ ]);
778
+ var SupervisionStep = class extends Schema.TaggedClass()("SupervisionStep", {
779
+ state: SupervisorState$1,
780
+ event: SupervisionEvent
781
+ }) {
782
+ static [Workflow.InstrumentationBrand] = {};
783
+ };
784
+ const UNKNOWN_TIMEOUT_MILLIS = 1e3;
785
+ const noCommands = {
786
+ stops: [],
787
+ starts: [],
788
+ arms: [],
789
+ replies: [],
790
+ terminates: []
791
+ };
792
+ const commandsIn = (buckets) => ({
793
+ ...noCommands,
794
+ ...buckets
679
795
  });
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);
796
+ 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);
797
+ const incarnationMatches = (childId, generation) => (child) => [child.childId === childId, child.generation === generation].every((holds) => holds);
798
+ const planMatches = (childId, generation) => (plan) => [plan.childId === childId, plan.generation === generation].every((holds) => holds);
799
+ const currentIncarnation = (core, childId, generation) => Array.findFirst(core.children, incarnationMatches(childId, generation));
800
+ const declarationOf$1 = (policy, childId) => Array.findFirst(policy.childDeclarations, (declaration) => declaration.childId === childId);
801
+ const dynamicKindOf$1 = (policy) => Match.value(policy.dynamic).pipe(Match.tag("DynamicChildren", (dynamic) => Option.some(dynamic)), Match.tag("NoDynamicChildren", () => Option.none()), Match.exhaustive);
802
+ const declaredKind = (declaration) => ({
803
+ restartType: declaration.restartType,
804
+ shutdown: declaration.shutdown,
805
+ startTimeoutMillis: declaration.startTimeoutMillis,
806
+ probeFailureThreshold: declaration.probeFailureThreshold,
807
+ significant: declaration.significant
808
+ });
809
+ const dynamicKindAs = (dynamic) => ({
810
+ restartType: dynamic.restartType,
811
+ shutdown: dynamic.shutdown,
812
+ startTimeoutMillis: dynamic.startTimeoutMillis,
813
+ probeFailureThreshold: dynamic.probeFailureThreshold,
814
+ significant: false
815
+ });
816
+ const unknownKind = {
817
+ restartType: "temporary",
818
+ shutdown: { _tag: "Infinity" },
819
+ startTimeoutMillis: UNKNOWN_TIMEOUT_MILLIS,
820
+ probeFailureThreshold: 1,
821
+ significant: false
705
822
  };
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);
823
+ const fallbackKind = (policy) => Match.value(dynamicKindOf$1(policy)).pipe(Match.tag("Some", ({ value }) => dynamicKindAs(value)), Match.tag("None", () => unknownKind), Match.exhaustive);
824
+ const kindOfPolicy = (policy, childId) => Match.value(declarationOf$1(policy, childId)).pipe(Match.tag("Some", ({ value }) => declaredKind(value)), Match.tag("None", () => fallbackKind(policy)), Match.exhaustive);
825
+ const indexOfChild = (core, childId) => Array.findFirstIndex(core.children, (child) => child.childId === childId);
826
+ 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);
827
+ const stoppingOf = (child) => ({
828
+ ...child,
829
+ status: "stopping"
710
830
  });
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();
831
+ const restartingOf = (child, generation) => ({
832
+ childId: child.childId,
833
+ generation,
834
+ status: "starting",
835
+ consecutiveRestarts: child.consecutiveRestarts + 1,
836
+ probeFailures: 0
725
837
  });
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();
838
+ const readiedOf = (child) => ({
839
+ childId: child.childId,
840
+ generation: child.generation,
841
+ status: "ready",
842
+ consecutiveRestarts: 0,
843
+ probeFailures: 0
784
844
  });
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));
845
+ const probedAs = (child, alive) => Match.value(alive).pipe(Match.when(true, () => ({
846
+ ...child,
847
+ probeFailures: 0
848
+ })), Match.when(false, () => ({
849
+ ...child,
850
+ probeFailures: child.probeFailures + 1
851
+ })), Match.exhaustive);
852
+ const replacing = (next) => (child) => Match.value(child.childId === next.childId).pipe(Match.when(true, () => next), Match.when(false, () => child), Match.exhaustive);
853
+ const withChildren = (core, children) => ({
854
+ ...core,
855
+ children
792
856
  });
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
- })
857
+ const withStamps = (core, restartStamps) => ({
858
+ ...core,
859
+ restartStamps
860
+ });
861
+ const prunedStamps = (core, at) => Array.filter(core.restartStamps, (stamp) => at - stamp <= core.policy.periodMillis);
862
+ 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)));
863
+ const startCommandOf = (start) => ({
864
+ _tag: "StartChild",
865
+ childId: start.childId,
866
+ generation: start.generation
867
+ });
868
+ const stopCommandOf = (policy, child) => ({
869
+ _tag: "StopChild",
870
+ childId: child.childId,
871
+ generation: child.generation,
872
+ shutdown: kindOfPolicy(policy, child.childId).shutdown
873
+ });
874
+ const backoffCommandOf = (start, deadline) => ({
875
+ _tag: "ArmChildTimer",
876
+ kind: "backoff",
877
+ childId: start.childId,
878
+ generation: start.generation,
879
+ deadline
880
+ });
881
+ const deadlineCommandOf = (start, deadline) => ({
882
+ _tag: "ArmChildTimer",
883
+ kind: "start_deadline",
884
+ childId: start.childId,
885
+ generation: start.generation,
886
+ deadline
887
+ });
888
+ const tickCommandOf = (child, deadline) => ({
889
+ _tag: "ArmChildTimer",
890
+ kind: "liveness_tick",
891
+ childId: child.childId,
892
+ generation: child.generation,
893
+ deadline
894
+ });
895
+ const coolDownCommandOf = (deadline) => ({
896
+ _tag: "ArmSupervisorTimer",
897
+ kind: "cool_down",
898
+ deadline
899
+ });
900
+ const terminateCommandOf = (reason, exit) => ({
901
+ _tag: "TerminateSupervisor",
902
+ reason,
903
+ exit
904
+ });
905
+ const replyAcceptedOf = (requestId, start) => ({
906
+ _tag: "ReplyStartAccepted",
907
+ requestId,
908
+ childId: start.childId,
909
+ generation: start.generation
910
+ });
911
+ const replyRefusedOf = (requestId) => ({
912
+ _tag: "ReplyStartRefused",
913
+ requestId
804
914
  });
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);
915
+ const replyStoppedOf = (requestId) => ({
916
+ _tag: "ReplyStopped",
917
+ requestId
918
+ });
919
+ const refusedStartOf = (requestId) => new RefuseDynamicStart({ commands: commandsIn({ replies: [replyRefusedOf(requestId)] }) });
920
+ const holdOf = (core) => new Continue({
921
+ core,
922
+ commands: noCommands
923
+ });
924
+ const terminatedReason = { _tag: "Shutdown" };
925
+ const requestedExit = { _tag: "RequestedExit" };
926
+ const failureReportOf = (reason) => Match.value(reason).pipe(Match.tag("Abnormal", (abnormal) => abnormal.report), Match.orElse(() => ({
927
+ _tag: "CauseReport",
928
+ cause: Cause.pretty(Cause.fail(reason))
929
+ })));
930
+ const giveUpReasonOf = (termination) => ({
931
+ _tag: "Abnormal",
932
+ report: failureReportOf(termination.reason)
933
+ });
934
+ const giveUpExitOf = (termination) => ({
935
+ _tag: "IntensityExceededExit",
936
+ childId: termination.childId,
937
+ generation: termination.generation
938
+ });
939
+ const terminateDecisionOf = (reason, exit) => new Terminate({
940
+ reason,
941
+ commands: commandsIn({ terminates: [terminateCommandOf(reason, exit)] })
942
+ });
943
+ const stopEverything = (core, reason, exit) => Match.value(Array.isReadonlyArrayNonEmpty(core.children)).pipe(Match.when(true, () => new StopChildren({
944
+ core: withChildren(core, Array.map(core.children, stoppingOf)),
945
+ reason,
946
+ exit,
947
+ commands: commandsIn({ stops: Array.map(Array.reverse(core.children), (child) => stopCommandOf(core.policy, child)) })
948
+ })), Match.when(false, () => terminateDecisionOf(reason, exit)), Match.exhaustive);
949
+ const terminationOf = (childId, generation, reason, at) => ({
950
+ childId,
951
+ generation,
952
+ reason,
953
+ at
954
+ });
955
+ const restartScopeOf = (core, failedIndex, termination) => {
956
+ const group = Array.getSomes(Array.map(scopeIndices(core.policy.strategy, failedIndex, Array.length(core.children)), (index) => Array.get(core.children, index)));
957
+ const coming = Array.filter(group, (child) => restartsOn(kindOfPolicy(core.policy, child.childId).restartType, termination.reason));
958
+ const comingIds = Array.map(coming, (child) => child.childId);
959
+ const removed = Array.filter(group, (child) => Array.contains(comingIds, child.childId) === false);
960
+ const removedIds = Array.map(removed, (child) => child.childId);
961
+ return {
962
+ coming,
963
+ comingIds,
964
+ removedIds,
965
+ remaining: Array.filter(core.children, (child) => Array.contains(removedIds, child.childId) === false),
966
+ stops: Array.map(Array.reverse(group), (child) => stopCommandOf(core.policy, child))
967
+ };
819
968
  };
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);
969
+ 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))));
970
+ const removalRemnant = (removedIds, child) => Match.value(Array.contains(removedIds, child.childId)).pipe(Match.when(true, () => []), Match.orElse(() => [child]));
971
+ const phasedCommands = (core, at, coming) => {
972
+ const steps = Array.map(coming, (child) => {
973
+ return {
974
+ start: {
975
+ childId: child.childId,
976
+ generation: child.generation + 1
977
+ },
978
+ delay: backoffDelay(core.policy.backoff, child.consecutiveRestarts)
979
+ };
980
+ });
981
+ const ready = Array.filter(steps, (step) => step.delay === 0);
982
+ const deferred = Array.filter(steps, (step) => step.delay > 0);
983
+ const timeoutOf = (step) => at + kindOfPolicy(core.policy, step.start.childId).startTimeoutMillis;
984
+ return {
985
+ commands: commandsIn({
986
+ starts: Array.map(ready, (step) => startCommandOf(step.start)),
987
+ arms: Array.appendAll(Array.map(ready, (step) => deadlineCommandOf(step.start, timeoutOf(step))), Array.map(deferred, (step) => backoffCommandOf(step.start, at + step.delay)))
988
+ }),
989
+ pending: Array.map(deferred, (step) => step.start)
990
+ };
823
991
  };
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);
992
+ const exhaustedDecisionOf = (policy, original, restarted, stops, at, termination) => Match.value(policy.coolDown).pipe(Match.tag("CoolDownAfter", ({ millis }) => new CoolDown({
993
+ core: restarted,
994
+ millis,
995
+ commands: commandsIn({
996
+ stops,
997
+ arms: [coolDownCommandOf(at + millis)]
998
+ })
999
+ })), Match.tag("NoCoolDown", () => stopEverything(original, giveUpReasonOf(termination), giveUpExitOf(termination))), Match.exhaustive);
1000
+ const stampedCoreOf = (core, scope, at) => {
1001
+ const stamped = withStamps(core, [at, ...prunedStamps(core, at)]);
1002
+ return withChildren(stamped, restartedChildrenOf(core, scope));
839
1003
  };
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);
1004
+ const restartOutcomeOf = (core, scope, at) => {
1005
+ const nextCore = stampedCoreOf(core, scope, at);
1006
+ const phased = phasedCommands(core, at, scope.coming);
1007
+ return {
1008
+ core: nextCore,
1009
+ stops: scope.stops,
1010
+ pending: phased.pending,
1011
+ commands: commandsIn({
1012
+ stops: scope.stops,
1013
+ starts: phased.commands.starts,
1014
+ arms: phased.commands.arms
1015
+ }),
1016
+ exhausted: Array.length(nextCore.restartStamps) > nextCore.policy.intensity
1017
+ };
845
1018
  };
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);
1019
+ 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({
1020
+ core: outcome.core,
1021
+ commands: outcome.commands
1022
+ })), Match.when(false, () => new RestartChildren({
1023
+ core: outcome.core,
1024
+ pending: outcome.pending,
1025
+ commands: outcome.commands
1026
+ })), Match.exhaustive)), Match.exhaustive);
1027
+ const isSignificant = (policy, child) => Match.value(declarationOf$1(policy, child.childId)).pipe(Match.tag("Some", ({ value }) => value.significant), Match.tag("None", () => false), Match.exhaustive);
1028
+ 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);
1029
+ 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({
1030
+ core: withChildren(core, remaining),
1031
+ commands: noCommands
1032
+ })), Match.exhaustive);
1033
+ Schema.TaggedStruct("Restarted", { outcome: Schema.Struct({
1034
+ core: SupervisorCore,
1035
+ stops: Schema.Array(StopChild),
1036
+ pending: Schema.Array(ChildStart),
1037
+ commands: SupervisorCommands,
1038
+ exhausted: Schema.Boolean
1039
+ }) });
1040
+ Schema.TaggedStruct("Quiet", {
1041
+ removedIds: Schema.Array(ChildId),
1042
+ remaining: Schema.Array(ChildInstance)
1043
+ });
1044
+ const failedChildOf = (core, failedIndex) => Array.get(core.children, failedIndex);
1045
+ 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);
1046
+ const quietSplitOf = (core, failedIndex) => Match.value(failedChildOf(core, failedIndex)).pipe(Match.tag("Some", (found) => ({
1047
+ _tag: "Quiet",
1048
+ removedIds: [found.value.childId],
1049
+ remaining: Array.filter(core.children, (child) => incarnationMatches(found.value.childId, found.value.generation)(child) === false)
1050
+ })), Match.tag("None", () => ({
1051
+ _tag: "Quiet",
1052
+ removedIds: [],
1053
+ remaining: core.children
1054
+ })), Match.exhaustive);
1055
+ const restartSplitOf = (core, failedIndex, termination) => Match.value(failedComesBack(core, failedIndex, termination)).pipe(Match.when(true, () => ({
1056
+ _tag: "Restarted",
1057
+ outcome: restartOutcomeOf(core, restartScopeOf(core, failedIndex, termination), termination.at)
1058
+ })), Match.when(false, () => quietSplitOf(core, failedIndex)), Match.exhaustive);
1059
+ 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);
1060
+ 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)));
1061
+ const removalOf = (core, childId, generation) => withChildren(core, Array.filter(core.children, (child) => incarnationMatches(childId, generation)(child) === false));
1062
+ const removalContinue = (core, termination) => new Continue({
1063
+ core: removalOf(core, termination.childId, termination.generation),
1064
+ commands: noCommands
1065
+ });
1066
+ 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);
1067
+ const startedInRunning = (core, childId, generation) => Match.value(currentIncarnation(core, childId, generation)).pipe(Match.tag("Some", () => holdOf(core)), Match.tag("None", () => new Stale({})), Match.exhaustive);
1068
+ 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);
1069
+ const becomingReady = (core, child, at) => Match.value(child.status).pipe(Match.when("starting", () => {
1070
+ const next = readiedOf(child);
1071
+ return new Continue({
1072
+ core: withChildren(core, Array.map(core.children, replacing(next))),
1073
+ commands: commandsIn({ arms: [tickCommandOf(next, at + core.policy.livenessTickMillis)] })
1074
+ });
1075
+ }), Match.orElse(() => holdOf(core)));
1076
+ const stoppedInShuttingDown = (core, reason, exit, childId, generation) => {
1077
+ const next = removalOf(core, childId, generation);
1078
+ return Match.value(Array.every(next.children, (child) => child.status !== "stopping")).pipe(Match.when(true, () => terminateDecisionOf(reason, exit)), Match.when(false, () => new Continue({
1079
+ core: next,
1080
+ commands: noCommands
1081
+ })), Match.exhaustive);
849
1082
  };
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))
1083
+ 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);
1084
+ const probedOutcomeOf = (core, child, alive, at) => Match.value(child.status).pipe(Match.when("ready", () => probedReadyOutcomeOf(core, child, alive, at)), Match.orElse(() => holdOf(core)));
1085
+ const probedReadyOutcomeOf = (core, child, alive, at) => Match.value(alive).pipe(Match.when(true, () => new Continue({
1086
+ core: withChildren(core, Array.map(core.children, replacing(probedAs(child, true)))),
1087
+ commands: noCommands
1088
+ })), Match.when(false, () => failedProbeOutcomeOf(core, child, at)), Match.exhaustive);
1089
+ 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, {
1090
+ _tag: "Abnormal",
1091
+ report: {
1092
+ _tag: "InferredReport",
1093
+ failedProbes: child.probeFailures + 1
1094
+ }
1095
+ }, at))), Match.when(false, () => new Continue({
1096
+ core: withChildren(core, Array.map(core.children, replacing(probedAs(child, false)))),
1097
+ commands: noCommands
1098
+ })), Match.exhaustive);
1099
+ 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);
1100
+ const deadlineInRunning = (core, child, at) => Match.value(child.status).pipe(Match.when("starting", () => terminatedIndexed(core, Option.getOrThrow(indexOfChild(core, child.childId)), {
1101
+ childId: child.childId,
1102
+ generation: child.generation,
1103
+ reason: {
1104
+ _tag: "Abnormal",
1105
+ report: {
1106
+ _tag: "DeadlineMissed",
1107
+ waitedMillis: kindOfPolicy(core.policy, child.childId).startTimeoutMillis
1108
+ }
1109
+ },
1110
+ at
1111
+ })), Match.orElse(() => new Stale({})));
1112
+ const tickInRunning = (core, child, at) => Match.value(child.status).pipe(Match.when("ready", () => new Continue({
1113
+ core,
1114
+ commands: commandsIn({ arms: [tickCommandOf(child, at + core.policy.livenessTickMillis)] })
1115
+ })), Match.orElse(() => new Stale({})));
1116
+ 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);
1117
+ const fireBackoffOf = (core, pending, childId, generation, at) => {
1118
+ const start = {
1119
+ childId,
1120
+ generation
1121
+ };
1122
+ const remaining = Array.filter(pending, (plan) => planMatches(childId, generation)(plan) === false);
1123
+ const commands = commandsIn({
1124
+ starts: [startCommandOf(start)],
1125
+ arms: [deadlineCommandOf(start, at + kindOfPolicy(core.policy, childId).startTimeoutMillis)]
854
1126
  });
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);
1127
+ return Match.value(Array.length(remaining) === 0).pipe(Match.when(true, () => new StartChildren({
1128
+ core,
1129
+ commands
1130
+ })), Match.when(false, () => new RestartChildren({
1131
+ core,
1132
+ pending: remaining,
1133
+ commands
1134
+ })), Match.exhaustive);
1135
+ };
1136
+ 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({})));
1137
+ const cooledStartsOf = (core, at) => {
1138
+ const fresh = Array.map(core.children, (child) => ({
1139
+ ...child,
1140
+ status: "starting",
1141
+ consecutiveRestarts: 0,
1142
+ probeFailures: 0
1143
+ }));
1144
+ const deadlineOf = (child) => deadlineCommandOf({
1145
+ childId: child.childId,
1146
+ generation: child.generation
1147
+ }, at + kindOfPolicy(core.policy, child.childId).startTimeoutMillis);
1148
+ return {
1149
+ fresh,
1150
+ commands: commandsIn({
1151
+ starts: Array.map(fresh, (child) => startCommandOf({
1152
+ childId: child.childId,
1153
+ generation: child.generation
1154
+ })),
1155
+ arms: Array.map(fresh, deadlineOf)
1156
+ })
1157
+ };
1158
+ };
1159
+ const cooledRestartOf = (core, at) => {
1160
+ const starts = cooledStartsOf(core, at);
1161
+ const clearedStamps = [];
1162
+ return new StartChildren({
1163
+ core: {
1164
+ ...core,
1165
+ children: starts.fresh,
1166
+ restartStamps: clearedStamps
1167
+ },
1168
+ commands: starts.commands
865
1169
  });
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);
1170
+ };
1171
+ const runningDynamicCount = (core) => Array.length(Array.filter(core.children, (child) => child.status !== "stopping"));
1172
+ const isDeclaredChild = (core, childId) => Option.isSome(declarationOf$1(core.policy, childId));
1173
+ const dynamicIdOf = (core) => `d${core.nextOrdinal}`;
1174
+ const dynamicInstanceOf = (core) => {
1175
+ const start = {
1176
+ childId: dynamicIdOf(core),
1177
+ generation: 0
1178
+ };
1179
+ const instance = {
1180
+ childId: start.childId,
1181
+ generation: start.generation,
1182
+ status: "starting",
1183
+ consecutiveRestarts: 0,
1184
+ probeFailures: 0
1185
+ };
1186
+ return {
1187
+ core: {
1188
+ ...core,
1189
+ children: Array.append(core.children, instance),
1190
+ nextOrdinal: core.nextOrdinal + 1
1191
+ },
1192
+ start
1193
+ };
1194
+ };
1195
+ const allocatedDecisionOf = (core, allocated, requestId, at) => {
1196
+ const timeoutMillis = Match.value(dynamicKindOf$1(allocated.core.policy)).pipe(Match.tag("Some", ({ value }) => value.startTimeoutMillis), Match.tag("None", () => UNKNOWN_TIMEOUT_MILLIS), Match.exhaustive);
1197
+ return new StartChildren({
1198
+ core: allocated.core,
1199
+ commands: commandsIn({
1200
+ starts: [startCommandOf(allocated.start)],
1201
+ arms: [deadlineCommandOf(allocated.start, at + timeoutMillis)],
1202
+ replies: [replyAcceptedOf(requestId, allocated.start)]
1203
+ })
894
1204
  });
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
- });
1205
+ };
1206
+ const ceilingReached = (core, ceiling) => runningDynamicCount(core) >= ceiling;
1207
+ 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);
1208
+ 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);
1209
+ const stoppable = (core, child) => Match.value(isDeclaredChild(core, child.childId)).pipe(Match.when(true, () => false), Match.when(false, () => child.status !== "stopping"), Match.exhaustive);
1210
+ const stoppingContinue = (core, child, requestId) => {
1211
+ const next = stoppingOf(child);
1212
+ return new Continue({
1213
+ core: withChildren(core, Array.map(core.children, replacing(next))),
1214
+ commands: commandsIn({
1215
+ stops: [stopCommandOf(core.policy, next)],
1216
+ replies: [replyStoppedOf(requestId)]
1217
+ })
910
1218
  });
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
- });
1219
+ };
1220
+ 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);
1221
+ 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);
1222
+ 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);
1223
+ const onChildTerminated = (state, termination) => Match.value(state).pipe(Match.tag("Running", ({ core }) => terminatedRunning(core, {
1224
+ childId: termination.childId,
1225
+ generation: termination.generation,
1226
+ reason: termination.reason,
1227
+ at: termination.at
1228
+ })), 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);
1229
+ const ShuttingDownReasonOf = (state) => Match.value(state).pipe(Match.tag("ShuttingDown", ({ reason }) => reason), Match.orElse(() => terminatedReason));
1230
+ const ShuttingDownExitOf = (state) => Match.value(state).pipe(Match.tag("ShuttingDown", ({ exit }) => exit), Match.orElse(() => requestedExit));
1231
+ const terminatedShuttingDown = (core, reason, exit, termination) => stoppedInShuttingDown(core, reason, exit, termination.childId, termination.generation);
1232
+ 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);
1233
+ 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);
1234
+ 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);
1235
+ 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);
1236
+ const coolDownElapsedOf = (core, kind, at) => Match.value(kind).pipe(Match.when("cool_down", () => cooledRestartOf(core, at)), Match.orElse(() => new Stale({})));
1237
+ 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);
1238
+ 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);
1239
+ 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);
1240
+ const bootedChildrenOf = (core, at) => {
1241
+ const incarnationOf = (child) => ({
1242
+ childId: child.childId,
1243
+ generation: child.generation
918
1244
  });
919
- const runStrategy = superviseTree(sup.strategy, {
920
- name: sup.name,
921
- booted,
922
- health,
923
- policy,
924
- reportRestart,
925
- reportExhausted,
926
- intensityEff
1245
+ const deadlineOf = (child) => deadlineCommandOf(incarnationOf(child), at + kindOfPolicy(core.policy, child.childId).startTimeoutMillis);
1246
+ return new StartChildren({
1247
+ core,
1248
+ commands: commandsIn({
1249
+ starts: Array.map(core.children, (child) => startCommandOf(incarnationOf(child))),
1250
+ arms: Array.map(core.children, deadlineOf)
1251
+ })
927
1252
  });
928
- yield* Effect.andThen(health.paused.await, runStrategy);
1253
+ };
1254
+ 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);
1255
+ 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);
1256
+ const interpretSupervisionEvent = Workflow.make({
1257
+ command: SupervisionStep,
1258
+ decision: SupervisionDecision,
1259
+ error: Schema.Never,
1260
+ decide: (step) => Result.succeed(decided(step.state, step.event))
929
1261
  });
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
- };
1262
+ //#endregion
1263
+ //#region src/kernel/evolve-supervisor.workflow.ts
1264
+ var Running = class extends Schema.TaggedClass()("Running", { core: SupervisorCore }) {
1265
+ [StateTypeId] = StateTypeId;
1266
+ };
1267
+ var Restarting = class extends Schema.TaggedClass()("Restarting", {
1268
+ core: SupervisorCore,
1269
+ pending: Schema.Array(ChildStart)
1270
+ }) {
1271
+ [StateTypeId] = StateTypeId;
1272
+ };
1273
+ var CoolingDown = class extends Schema.TaggedClass()("CoolingDown", {
1274
+ core: SupervisorCore,
1275
+ millis: PositiveMillis
1276
+ }) {
1277
+ [StateTypeId] = StateTypeId;
1278
+ };
1279
+ var ShuttingDown = class extends Schema.TaggedClass()("ShuttingDown", {
1280
+ core: SupervisorCore,
1281
+ reason: TerminationReason,
1282
+ exit: SupervisorExit
1283
+ }) {
1284
+ [StateTypeId] = StateTypeId;
1285
+ };
1286
+ var Terminated = class extends Schema.TaggedClass()("Terminated", { reason: TerminationReason }) {
1287
+ [StateTypeId] = StateTypeId;
1288
+ };
1289
+ const SupervisorState = Schema.Union([
1290
+ Running,
1291
+ Restarting,
1292
+ CoolingDown,
1293
+ ShuttingDown,
1294
+ Terminated
1295
+ ]);
1296
+ var SupervisionEvolution = class extends Schema.TaggedClass()("SupervisionEvolution", {
1297
+ state: SupervisorState,
1298
+ decision: SupervisionDecision
1299
+ }) {
1300
+ static [Workflow.InstrumentationBrand] = {};
1301
+ };
1302
+ const withCore = (state, core) => Match.value(state).pipe(Match.tag("Running", () => new Running({ core })), Match.tag("Restarting", (restarting) => new Restarting({
1303
+ core,
1304
+ pending: restarting.pending
1305
+ })), Match.tag("CoolingDown", (cooling) => new CoolingDown({
1306
+ core,
1307
+ millis: cooling.millis
1308
+ })), Match.tag("ShuttingDown", (shutting) => new ShuttingDown({
1309
+ core,
1310
+ reason: shutting.reason,
1311
+ exit: shutting.exit
1312
+ })), Match.tag("Terminated", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive);
1313
+ 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({
1314
+ core: restarting.core,
1315
+ pending: restarting.pending
1316
+ })), Match.tag("StartChildren", (started) => new Running({ core: started.core })), Match.tag("CoolDown", (cooling) => new CoolingDown({
1317
+ core: cooling.core,
1318
+ millis: cooling.millis
1319
+ })), Match.tag("StopChildren", (stopping) => new ShuttingDown({
1320
+ core: stopping.core,
1321
+ reason: stopping.reason,
1322
+ exit: stopping.exit
1323
+ })), Match.tag("Terminate", (terminated) => new Terminated({ reason: terminated.reason })), Match.exhaustive);
1324
+ const evolveSupervisor = Workflow.make({
1325
+ command: SupervisionEvolution,
1326
+ decision: SupervisorState,
1327
+ error: Schema.Never,
1328
+ decide: (step) => Result.succeed(evolved(step.state, step.decision))
951
1329
  });
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
1330
  //#endregion
962
- //#region src/LeaderLock.ts
963
- const isModeNone = (lock) => lock.mode === "none";
1331
+ //#region src/Supervisor/SupervisorTerminated.schema.ts
1332
+ var SupervisorTerminated = class extends Schema.TaggedError()("SupervisorTerminated", {
1333
+ name: Schema.String,
1334
+ reason: TerminationReason,
1335
+ cause: Schema.Cause(Schema.Unknown, Schema.Unknown)
1336
+ }) {};
964
1337
  //#endregion
965
- //#region src/RunSupervisor.ts
1338
+ //#region src/Supervisor/supervisor-commands.ts
1339
+ const stampedNow = (handle, event) => Effect.flatMap(Clock.currentTimeMillis, (now) => offerEvent(handle, {
1340
+ ...event,
1341
+ at: now
1342
+ }));
1343
+ const startedEventOf = (childId, generation) => ({
1344
+ _tag: "ChildStarted",
1345
+ at: 0,
1346
+ childId,
1347
+ generation
1348
+ });
1349
+ const readyEventOf = (childId, generation) => ({
1350
+ _tag: "ChildReady",
1351
+ at: 0,
1352
+ childId,
1353
+ generation
1354
+ });
1355
+ const terminatedEventOf = (childId, generation, reason) => ({
1356
+ _tag: "ChildTerminated",
1357
+ at: 0,
1358
+ childId,
1359
+ generation,
1360
+ reason
1361
+ });
1362
+ const stoppedEventOf = (childId, generation) => ({
1363
+ _tag: "ChildStopped",
1364
+ at: 0,
1365
+ childId,
1366
+ generation
1367
+ });
1368
+ const probeEventOf = (childId, generation, alive) => ({
1369
+ _tag: "ProbeResult",
1370
+ at: 0,
1371
+ childId,
1372
+ generation,
1373
+ alive
1374
+ });
1375
+ const timerEventOf = (kind, childId, generation) => ({
1376
+ _tag: "TimerElapsed",
1377
+ at: 0,
1378
+ kind,
1379
+ target: {
1380
+ _tag: "ChildTimer",
1381
+ childId,
1382
+ generation
1383
+ }
1384
+ });
1385
+ const supervisorTimerEventOf = (kind) => ({
1386
+ _tag: "TimerElapsed",
1387
+ at: 0,
1388
+ kind,
1389
+ target: { _tag: "SupervisorTimer" }
1390
+ });
1391
+ const evidenceKeyOf = (childId, generation) => `${childId}#${generation}`;
1392
+ const registerStarted = (handle, childId, generation, evidence) => Ref.update(evidenceOf(handle), (known) => HashMap.set(known, evidenceKeyOf(childId, generation), evidence));
1393
+ const knownStarted = (handle, childId, generation) => Effect.map(Ref.get(evidenceOf(handle)), (known) => HashMap.get(known, evidenceKeyOf(childId, generation)));
1394
+ const watchReadiness = (handle, evidence, childId, generation) => Effect.asVoid(Effect.forkIn(Effect.asVoid(Effect.andThen(evidence.ready, stampedNow(handle, readyEventOf(childId, generation)))), ownerScopeOf(handle)));
1395
+ 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
1396
  /**
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.
1397
+ * The child bound to an id. Declared children are bound at acquisition and dynamic
1398
+ * ones by `bindDynamicPrograms` before their start runs, so a missing binding is a
1399
+ * broken invariant and dies rather than reporting a start that never ran.
971
1400
  */
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
- };
1401
+ const boundChildFor = (handle, childId) => Effect.flatMap(Ref.get(boundChildrenOf(handle)), (children) => Effect.orDie(Effect.fromOption(HashMap.get(children, childId))));
1402
+ const failureReasonOf = (cause) => Option.getOrElse(Cause.findErrorOption(cause), () => ({
1403
+ _tag: "Abnormal",
1404
+ report: {
1405
+ _tag: "CauseReport",
1406
+ cause: Cause.pretty(cause)
983
1407
  }
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
1408
  }));
995
- //#endregion
996
- //#region src/RunWorker.ts
1409
+ const executeStart = (acquired, command) => Effect.gen(function* () {
1410
+ const child = yield* boundChildFor(acquired.handle, command.childId);
1411
+ const outcome = yield* Effect.exit(child.start);
1412
+ yield* Exit.match(outcome, {
1413
+ 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)))),
1414
+ onFailure: (cause) => stampedNow(acquired.handle, terminatedEventOf(command.childId, command.generation, failureReasonOf(cause)))
1415
+ });
1416
+ });
997
1417
  /**
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.
1418
+ * Moves each answered request's pending child: an accepted start binds it to the
1419
+ * child the kernel allocated, and every answered request drops its pending entry.
1002
1420
  */
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);
1421
+ 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))));
1422
+ const executeStop = (acquired, command) => Effect.gen(function* () {
1423
+ const child = yield* boundChildFor(acquired.handle, command.childId);
1424
+ const found = yield* knownStarted(acquired.handle, command.childId, command.generation);
1425
+ yield* Option.match(found, {
1426
+ onNone: () => Effect.void,
1427
+ onSome: (evidence) => Effect.asVoid(child.stop(evidence, command.shutdown))
1428
+ });
1429
+ yield* stampedNow(acquired.handle, stoppedEventOf(command.childId, command.generation));
1015
1430
  });
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
1431
+ 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))));
1432
+ 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);
1433
+ const outcomeOf = (reply) => Match.value(reply).pipe(Match.tag("ReplyStartAccepted", (accepted) => ({
1434
+ outcome: "accepted",
1435
+ childId: accepted.childId,
1436
+ generation: accepted.generation
1437
+ })), Match.tag("ReplyStartRefused", () => ({ outcome: "refused" })), Match.tag("ReplyStopped", () => ({ outcome: "stopped" })), Match.exhaustive);
1438
+ const executeReply = (acquired, reply) => Ops.resolveWaiting(repliesOf(acquired.handle), reply.requestId, outcomeOf(reply));
1439
+ const giveUpCauseOf = (handle, exit, reason) => Effect.flatMap(Ref.get(evidenceOf(handle)), (evidence) => Option.match(HashMap.get(evidence, evidenceKeyOf(exit.childId, exit.generation)), {
1440
+ onNone: () => Effect.succeed(Cause.fail(reason)),
1441
+ onSome: (started) => Option.match(failureCauseOf(started), {
1442
+ onNone: () => Effect.succeed(Cause.fail(reason)),
1443
+ onSome: (awaited) => Effect.map(awaited, (cause) => Option.getOrElse(cause, () => Cause.fail(reason)))
1444
+ })
1030
1445
  }));
1446
+ const clearEvidence = (handle) => Ref.update(evidenceOf(handle), () => HashMap.empty());
1447
+ 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({
1448
+ name: acquired.handle.name,
1449
+ reason: command.reason,
1450
+ cause
1451
+ })))))), Match.exhaustive);
1452
+ const bucketRunnerOf = (acquired) => ({
1453
+ stops: (commands) => Effect.forEach(commands.stops, (command) => executeStop(acquired, command), { discard: true }),
1454
+ starts: (commands) => Effect.forEach(commands.starts, (command) => executeStart(acquired, command), { discard: true }),
1455
+ arms: (commands) => Effect.forEach(commands.arms, (command) => executeArm(acquired, command), { discard: true }),
1456
+ replies: (commands) => Effect.forEach(commands.replies, (reply) => executeReply(acquired, reply), { discard: true }),
1457
+ terminates: (commands) => Effect.forEach(commands.terminates, (command) => executeTerminate(acquired, command), { discard: true })
1458
+ });
1459
+ const Commands = {
1460
+ runBuckets: (acquired, commands) => runBuckets(acquired, commands),
1461
+ probeOnce: (acquired, childId, generation) => probeOnce(acquired, childId, generation),
1462
+ answerStale: (acquired, event) => answerStale(acquired, event),
1463
+ requestIdOf: (event) => requestIdOf(event)
1464
+ };
1465
+ const runBuckets = (acquired, commands) => {
1466
+ const buckets = bucketRunnerOf(acquired);
1467
+ 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)))));
1468
+ };
1469
+ const probeOnce = (acquired, childId, generation) => Effect.gen(function* () {
1470
+ const child = yield* boundChildFor(acquired.handle, childId);
1471
+ const found = yield* knownStarted(acquired.handle, childId, generation);
1472
+ const alive = yield* Option.match(found, {
1473
+ onNone: () => Effect.succeed(false),
1474
+ onSome: (evidence) => child.probe(evidence)
1475
+ });
1476
+ yield* stampedNow(acquired.handle, probeEventOf(childId, generation, alive));
1477
+ });
1478
+ 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));
1479
+ const answerStale = (acquired, event) => {
1480
+ const requestId = requestIdOf(event);
1481
+ return requestId === void 0 ? Effect.void : Ops.resolveWaiting(repliesOf(acquired.handle), requestId, Ops.staleOf(event));
1482
+ };
1031
1483
  //#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
- }));
1484
+ //#region src/Supervisor/supervisor-step.cell.ts
1485
+ const readStep = (runtime, event) => Effect.map(Effect.zip(Clock.currentTimeMillis, Ref.get(stateOf(runtime.acquired.handle))), ([now, state]) => new SupervisionStep({
1486
+ state,
1487
+ event: {
1488
+ ...event,
1489
+ at: now
1490
+ }
1491
+ }, { disableChecks: true }));
1492
+ const persistedOf = (previous, decision) => Result.getOrThrow(evolveSupervisor(new SupervisionEvolution({
1493
+ state: previous,
1494
+ decision: Result.getOrThrow(Schema.decodeResult(SupervisionDecision)(decision))
1495
+ })));
1496
+ 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), {
1497
+ event,
1498
+ decision
1499
+ })));
1500
+ const runBucketsOf = (runtime, commands) => Commands.runBuckets(runtime.acquired, commands);
1501
+ const Steps = { runtimeOf: (acquired) => ({ acquired }) };
1502
+ const supervisorStepFor = (runtime) => Sandwich.named("supervisor.step")((event) => readStep(runtime, event)).decide(interpretSupervisionEvent).write({
1503
+ Stale: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), Commands.answerStale(runtime.acquired, command.event)),
1504
+ Continue: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1505
+ RestartChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1506
+ StartChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1507
+ CoolDown: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1508
+ StopChildren: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1509
+ Terminate: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1510
+ RefuseDynamicStart: (decision, command) => Effect.andThen(persistStep(runtime, command.event, command.state, decision), runBucketsOf(runtime, decision.commands)),
1511
+ CommandRejected: (_rejected, command) => Effect.andThen(persistCommandRejection(runtime, command.event), Commands.answerStale(runtime.acquired, command.event))
1512
+ });
1513
+ const persistCommandRejection = (runtime, event) => PubSub.publish(tracePubSubOf(runtime.acquired.handle), {
1514
+ event,
1515
+ decision: new Stale({})
1516
+ }).pipe(Effect.asVoid);
1043
1517
  //#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
1518
+ //#region src/Supervisor/Supervisor.ts
1519
+ const SpecTypeId = Symbol.for("@systemfsoftware/effect-daemon-spec/SupervisorSpec");
1520
+ const hasSpecTag = Predicate.hasProperty(SpecTypeId);
1521
+ const isSupervisorSpec = (value) => hasSpecTag(value) && value[SpecTypeId] === SpecTypeId;
1522
+ const WORKER_SHUTDOWN = {
1523
+ _tag: "Graceful",
1524
+ millis: 5e3
1525
+ };
1526
+ const SUPERVISOR_SHUTDOWN = { _tag: "Infinity" };
1527
+ const LIVENESS_TICK_MILLIS = 1e3;
1528
+ const policyOfParts = (parts) => new SupervisionPolicy({
1529
+ strategy: parts.strategy,
1530
+ intensity: parts.intensity,
1531
+ periodMillis: parts.periodMillis,
1532
+ autoShutdown: parts.autoShutdown,
1533
+ coolDown: parts.coolDownMillis === void 0 ? { _tag: "NoCoolDown" } : {
1534
+ _tag: "CoolDownAfter",
1535
+ millis: parts.coolDownMillis
1536
+ },
1537
+ backoff: parts.backoff,
1538
+ dynamic: parts.dynamic,
1539
+ livenessTickMillis: parts.livenessTickMillis,
1540
+ childDeclarations: parts.declarations
1541
+ });
1542
+ 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))))));
1543
+ const fiberMediumOf = () => Effect.map(Effect.serviceOption(fiberPort), (found) => Option.match(found, {
1544
+ onNone: () => mediumFor(),
1545
+ onSome: (port) => port.medium
1057
1546
  }));
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 ?? {}
1547
+ const scopedOf = (parts) => Effect.gen(function* () {
1548
+ const supervisorScope = yield* Effect.scope;
1549
+ const initial = new Running$1({ core: initialStateOf(policyOfParts(parts)) });
1550
+ const bound = yield* Effect.forEach(parts.bindings, (entry) => Effect.map(entry.binding, (child) => [entry.declaration.childId, child]), { concurrency: 1 });
1551
+ const context = yield* Effect.context();
1552
+ const fiber = yield* fiberMediumOf();
1553
+ const handle = yield* RunningSupervisorHandle.make(parts.name, initial, HashMap.fromIterable(bound), context, fiber);
1554
+ const step = supervisorStepFor(Steps.runtimeOf({ handle }));
1555
+ yield* Effect.forkIn(drainOf(handle, step), supervisorScope);
1556
+ yield* offerEvent(handle, {
1557
+ _tag: "SupervisorStarted",
1558
+ at: 0
1559
+ });
1560
+ yield* Effect.addFinalizer(() => Effect.catchTag(shutdown(handle), "SupervisorTerminated", () => Effect.void));
1561
+ return handle;
1068
1562
  });
1069
- //#endregion
1070
- //#region src/SupervisorOneForOne.ts
1071
- const oneForOne$1 = (opts) => ({
1072
- [SupervisorTypeId]: SupervisorTypeId,
1073
- name: opts.name,
1563
+ const specOf = (parts) => {
1564
+ const scoped = scopedOf(parts);
1565
+ return {
1566
+ [SpecTypeId]: SpecTypeId,
1567
+ ...parts,
1568
+ scoped,
1569
+ layer: Layer.effectDiscard(Effect.asVoid(scoped)),
1570
+ ...Prototype
1571
+ };
1572
+ };
1573
+ const partsOf = (self) => ({
1574
+ name: self.name,
1575
+ strategy: self.strategy,
1576
+ intensity: self.intensity,
1577
+ periodMillis: self.periodMillis,
1578
+ autoShutdown: self.autoShutdown,
1579
+ coolDownMillis: self.coolDownMillis,
1580
+ backoff: self.backoff,
1581
+ livenessTickMillis: self.livenessTickMillis,
1582
+ declarations: self.declarations,
1583
+ bindings: self.bindings,
1584
+ dynamic: self.dynamic
1585
+ });
1586
+ const make = (name) => specOf({
1587
+ name,
1074
1588
  strategy: "one_for_one",
1075
- children: opts.children,
1076
- supervision: opts.supervision,
1077
- lock: opts.lock,
1078
- reporter: opts.reporter ?? {}
1589
+ intensity: 1,
1590
+ periodMillis: 5e3,
1591
+ autoShutdown: "never",
1592
+ coolDownMillis: void 0,
1593
+ backoff: {
1594
+ baseMillis: 0,
1595
+ multiplier: 1,
1596
+ capMillis: 0
1597
+ },
1598
+ livenessTickMillis: LIVENESS_TICK_MILLIS,
1599
+ declarations: [],
1600
+ bindings: [],
1601
+ dynamic: { _tag: "NoDynamicChildren" }
1079
1602
  });
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 ?? {}
1603
+ const strategy = dual(2, (self, strategy) => specOf({
1604
+ ...partsOf(self),
1605
+ strategy
1606
+ }));
1607
+ const intensity = dual(3, (self, intensity, periodMillis) => specOf({
1608
+ ...partsOf(self),
1609
+ intensity,
1610
+ periodMillis
1611
+ }));
1612
+ const autoShutdown = dual(2, (self, autoShutdown) => specOf({
1613
+ ...partsOf(self),
1614
+ autoShutdown
1615
+ }));
1616
+ const coolDown = dual(2, (self, millis) => specOf({
1617
+ ...partsOf(self),
1618
+ coolDownMillis: millis
1619
+ }));
1620
+ const backoff = dual(2, (self, schedule) => specOf({
1621
+ ...partsOf(self),
1622
+ backoff: schedule
1623
+ }));
1624
+ const livenessTick = dual(2, (self, millis) => specOf({
1625
+ ...partsOf(self),
1626
+ livenessTickMillis: millis
1627
+ }));
1628
+ const dynamicKindOf = (options) => ({
1629
+ _tag: "DynamicChildren",
1630
+ restartType: "permanent",
1631
+ shutdown: WORKER_SHUTDOWN,
1632
+ startTimeoutMillis: 5e3,
1633
+ probeFailureThreshold: 2,
1634
+ ...options
1090
1635
  });
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
1636
+ const dynamic = dual(2, (self, options) => specOf({
1637
+ ...partsOf(self),
1638
+ dynamic: dynamicKindOf(options)
1639
+ }));
1640
+ const declarationOf = (childId, nested, options) => ({
1641
+ childId,
1642
+ restartType: "permanent",
1643
+ shutdown: nested ? SUPERVISOR_SHUTDOWN : WORKER_SHUTDOWN,
1644
+ significant: false,
1645
+ startTimeoutMillis: 5e3,
1646
+ probeFailureThreshold: 2,
1647
+ ...options
1648
+ });
1649
+ const isNestedSpec = (value) => hasSpecTag(value) && value[SpecTypeId] === SpecTypeId;
1650
+ const nestedProgramOf = (nested) => (ready) => Effect.flatMap(nested.scoped, (handle) => Effect.andThen(ready, Effect.andThen(awaitTerminated(handle), Effect.interrupt)));
1651
+ const fiberMediumForChild = () => mediumFor();
1652
+ const bindFiberChild = (program) => Effect.gen(function* () {
1653
+ const context = yield* Effect.context();
1654
+ const runnable = typeof program === "function" ? program : readyOnStart(program);
1655
+ return Binder.bind(runnable, fiberMediumForChild(), context);
1656
+ });
1657
+ const bindNestedChild = (nested) => Effect.gen(function* () {
1658
+ const context = yield* Effect.context();
1659
+ return Binder.bind(nestedProgramOf(nested), fiberMediumForChild(), context);
1660
+ });
1661
+ const childSpecMake = (childId, program, options) => isNestedSpec(program) ? {
1662
+ childId,
1663
+ declaration: declarationOf(childId, true, options),
1664
+ binding: bindNestedChild(program),
1665
+ ...Prototype
1666
+ } : {
1667
+ childId,
1668
+ declaration: declarationOf(childId, false, options),
1669
+ binding: bindFiberChild(program),
1670
+ ...Prototype
1105
1671
  };
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
1672
+ const childSpecOn = (port) => (childId, program, options) => ({
1673
+ childId,
1674
+ declaration: declarationOf(childId, false, options),
1675
+ binding: Effect.gen(function* () {
1676
+ const shape = yield* port;
1677
+ const context = yield* Effect.context();
1678
+ return Binder.bind(program, shape.medium, context);
1679
+ }),
1680
+ ...Prototype
1681
+ });
1682
+ /**
1683
+ * The two ways to declare a child: `make`, which binds to the fiber medium (and
1684
+ * to the `FiberMedium` port when one is provided), and `on`, which binds to a
1685
+ * named medium port (KTD9).
1686
+ */
1687
+ const ChildSpecs = {
1688
+ make: childSpecMake,
1689
+ on: childSpecOn
1114
1690
  };
1115
- const dynamic = (opts) => dynamic$2({
1116
- ...opts,
1117
- maxChildren: opts.maxChildren ?? MaxChildren.make(1e3)
1691
+ const children = dual(2, (self, specs) => specOf({
1692
+ ...partsOf(self),
1693
+ declarations: [...self.declarations, ...specs.map((spec) => spec.declaration)],
1694
+ bindings: [...self.bindings, ...specs.map((spec) => ({
1695
+ declaration: spec.declaration,
1696
+ binding: spec.binding
1697
+ }))]
1698
+ }));
1699
+ const child = dual((args) => isSupervisorSpec(args[0]), (self, childId, program, options) => children(self, [childSpecMake(childId, program, options)]));
1700
+ //#endregion
1701
+ //#region src/Supervisor/mod.ts
1702
+ var Supervisor_exports = /* @__PURE__ */ __exportAll({
1703
+ ChildSpecs: () => ChildSpecs,
1704
+ FiberMedium: () => FiberMedium_exports,
1705
+ Medium: () => Medium_exports,
1706
+ SpecTypeId: () => SpecTypeId,
1707
+ SupervisorTerminated: () => SupervisorTerminated,
1708
+ TypeId: () => TypeId,
1709
+ autoShutdown: () => autoShutdown,
1710
+ awaitTerminated: () => awaitTerminated,
1711
+ backoff: () => backoff,
1712
+ child: () => child,
1713
+ children: () => children,
1714
+ coolDown: () => coolDown,
1715
+ dynamic: () => dynamic,
1716
+ intensity: () => intensity,
1717
+ isRunningSupervisor: () => isRunningSupervisor,
1718
+ isSupervisorSpec: () => isSupervisorSpec,
1719
+ livenessTick: () => livenessTick,
1720
+ make: () => make,
1721
+ readyOnStart: () => readyOnStart,
1722
+ shutdown: () => shutdown,
1723
+ startChild: () => startChild,
1724
+ statusOf: () => statusOf,
1725
+ stopChild: () => stopChild,
1726
+ strategy: () => strategy,
1727
+ traceOf: () => traceOf
1118
1728
  });
1119
- const oneForAll = (opts) => oneForAll$1(opts);
1120
- const oneForOne = (opts) => oneForOne$1(opts);
1121
- const restForOne = (opts) => restForOne$1(opts);
1122
1729
  //#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 };
1730
+ export { Supervisor_exports as Supervisor };