@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.3

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/src/serve.ts ADDED
@@ -0,0 +1,1665 @@
1
+ /**
2
+ * @module serve
3
+ * @package @hop-top/kit
4
+ *
5
+ * Serve hierarchy and service lifecycle — the TypeScript port of the
6
+ * contract in `docs/contracts/serve-lifecycle.md`, §"Cross-language
7
+ * parity".
8
+ *
9
+ * `<tool> serve` supervises every configured and enabled service;
10
+ * `<tool> serve <service>` selects exactly one and overrides aggregate
11
+ * enablement. Both forms share one lifecycle implementation, so a
12
+ * service started by the selector observes the same readiness,
13
+ * shutdown, and exit semantics as the same service started by the
14
+ * supervisor.
15
+ *
16
+ * The Go reference is `go/console/serve`. This module mirrors the
17
+ * behavior the contract makes cross-language, and deliberately does
18
+ * not mirror what the contract rules out — there is no REST/OpenAPI
19
+ * projection, no socket service, no command-tree reflection, and no
20
+ * permission/provenance/audit surface here, because those depend on
21
+ * Go-only machinery.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { createCLI } from '@hop-top/kit/cli';
26
+ * import { ServiceRegistry, registerServe } from '@hop-top/kit/serve';
27
+ *
28
+ * const registry = new ServiceRegistry();
29
+ * registry.register({
30
+ * name: 'api',
31
+ * async start(signal, ready) {
32
+ * ready();
33
+ * await new Promise<void>(r => signal.addEventListener('abort', () => r(), { once: true }));
34
+ * },
35
+ * ready: () => true,
36
+ * async stop() {},
37
+ * });
38
+ *
39
+ * const { program } = createCLI({ name: 'mytool', version: '1.0.0', description: 'My tool' });
40
+ * registerServe(program, { registry, configs: { api: { enabled: true } } });
41
+ * program.parse();
42
+ * ```
43
+ */
44
+
45
+ import type { Command } from 'commander';
46
+
47
+ import {
48
+ CODE_GENERIC,
49
+ CODE_NOT_FOUND,
50
+ CODE_OK,
51
+ CODE_TRANSIENT,
52
+ CODE_UNAUTHORIZED,
53
+ CODE_USAGE,
54
+ type CliError,
55
+ notFoundError,
56
+ unauthorizedError,
57
+ usageError,
58
+ } from './output/error.js';
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Naming
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /**
65
+ * Service identifier grammar: lowercase ASCII, digits, and internal
66
+ * hyphens. An identifier is a CLI word, a config key segment, and an
67
+ * event payload value at once, which is why the grammar is contract
68
+ * rather than a local convention.
69
+ */
70
+ export const NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
71
+
72
+ /**
73
+ * Names reserved for selector vocabulary. Registering one would make
74
+ * `serve <name>` ambiguous with a future aggregate form, and is why
75
+ * `--list` is a flag rather than a `serve list` child.
76
+ */
77
+ export const RESERVED_NAMES: readonly string[] = ['all', 'none', 'list'];
78
+
79
+ /** Reports whether `name` is one of the reserved selector words. */
80
+ export function isReservedName(name: string): boolean {
81
+ return RESERVED_NAMES.includes(name);
82
+ }
83
+
84
+ /**
85
+ * Validates a service identifier, returning an error message or
86
+ * `null`. Mirrors Go's `serve.ValidateName`.
87
+ */
88
+ export function validateName(name: string): string | null {
89
+ if (name === '') return 'serve: service name is empty';
90
+ if (!NAME_PATTERN.test(name)) {
91
+ return `serve: service name "${name}" must be lowercase letters, ` +
92
+ 'digits, or hyphens, starting with a letter';
93
+ }
94
+ if (isReservedName(name)) return `serve: service name "${name}" is reserved`;
95
+ return null;
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Registration seam
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /**
103
+ * One long-running thing a tool can serve.
104
+ *
105
+ * The four required capabilities are the contract's minimum: a name, a
106
+ * start that runs until aborted or failed, a readiness report, and a
107
+ * stop. Go expresses them as an interface; here they are properties on
108
+ * a plain object, which the contract explicitly permits — what is
109
+ * fixed is the capability set and each one's behavior, not a method
110
+ * table.
111
+ */
112
+ export interface Service {
113
+ /**
114
+ * Stable service identifier. Must satisfy {@link validateName} and
115
+ * must not change across releases: renaming one is a breaking change
116
+ * to the command surface, the config file, and any subscriber.
117
+ */
118
+ name: string;
119
+
120
+ /**
121
+ * Begins serving. Resolves when `signal` aborts (a clean stop) and
122
+ * rejects when the service fails.
123
+ *
124
+ * `ready` must be called exactly once, after every acquisition that
125
+ * can fail deterministically has succeeded — the listener bound, the
126
+ * file created, the subscription attached. Calling it more than once
127
+ * is ignored rather than an error; the supervisor reports ready at
128
+ * most once per start either way.
129
+ */
130
+ start(signal: AbortSignal, ready: () => void): Promise<void>;
131
+
132
+ /**
133
+ * Whether the service is currently accepting work. Readiness, not
134
+ * liveness: a ready service may be idle, and may later fail.
135
+ */
136
+ ready(): boolean;
137
+
138
+ /**
139
+ * Drains in-flight work and releases resources. The supervisor
140
+ * bounds it by the stop timeout and abandons a stop that exceeds it,
141
+ * so an implementation must respect `signal` rather than assume it
142
+ * will be allowed to finish.
143
+ */
144
+ stop(signal: AbortSignal): Promise<void>;
145
+
146
+ /**
147
+ * Optional configuration gate — the second of the three validation
148
+ * gates. Returns an error message, or `null` when the resolved
149
+ * configuration is complete and usable.
150
+ */
151
+ validate?(): string | null;
152
+
153
+ /**
154
+ * Optional ordering declaration. Start order is topological over
155
+ * these, ties broken by registration order; stop order is the exact
156
+ * reverse of the order services actually started.
157
+ */
158
+ dependsOn?(): string[];
159
+
160
+ /**
161
+ * Optional address declaration. Read once the service reports ready
162
+ * and carried into the readiness event, so an operator learns where
163
+ * the service actually bound — including a port the kernel picked
164
+ * for a wildcard address, which configuration cannot reveal.
165
+ */
166
+ addr?(): string;
167
+
168
+ /**
169
+ * Optional policy declaration: the `kit/side-effect` and
170
+ * `kit/network` classes, in that order. A service that omits it is
171
+ * unclassified and passes the policy gate.
172
+ */
173
+ class?(): [sideEffect: string, network: string];
174
+ }
175
+
176
+ /**
177
+ * The third validation gate. A service whose declared class the gate
178
+ * denies is refused at `UNAUTHORIZED`, exit 5.
179
+ *
180
+ * The contract requires the gate, not Go's YAML-driven
181
+ * side-effect × network table: a two-argument predicate satisfies it.
182
+ * A registry with no gate passes every service, because a tool that
183
+ * has wired no policy has expressed no restriction.
184
+ */
185
+ export interface PolicyGate {
186
+ allow(sideEffect: string, network: string): { ok: boolean; reason?: string };
187
+ }
188
+
189
+ /**
190
+ * Thrown when a registration is rejected at construction time.
191
+ *
192
+ * A duplicate name or an invalid one is a wiring bug in the tool's
193
+ * entry point, not a runtime condition: it surfaces on the first run
194
+ * rather than at the first `serve`, and there is no last-writer-wins
195
+ * path. Go panics; throwing is this port's equivalent. What the
196
+ * contract forbids is letting execution survive it as a warning.
197
+ */
198
+ export class ServiceRegistrationError extends Error {
199
+ constructor(message: string) {
200
+ super(message);
201
+ this.name = 'ServiceRegistrationError';
202
+ }
203
+ }
204
+
205
+ /**
206
+ * The seam kit-owned and adopter-owned services register into. A tool
207
+ * builds one before the root command parses; the supervisor reads it.
208
+ */
209
+ export class ServiceRegistry {
210
+ private readonly byName = new Map<string, Service>();
211
+ private readonly order: string[] = [];
212
+
213
+ /**
214
+ * Adds `svc` under its name.
215
+ *
216
+ * Throws on an invalid name and on a duplicate. An adopter
217
+ * deliberately replacing a kit-shipped service calls
218
+ * {@link ServiceRegistry.override} instead — the documented escape
219
+ * hatch, and the only path that accepts a duplicate name.
220
+ */
221
+ register(svc: Service): void {
222
+ const invalid = validateName(svc.name);
223
+ if (invalid) throw new ServiceRegistrationError(invalid);
224
+ if (this.byName.has(svc.name)) {
225
+ throw new ServiceRegistrationError(
226
+ `serve: service "${svc.name}" already registered (use override to replace)`,
227
+ );
228
+ }
229
+ this.byName.set(svc.name, svc);
230
+ this.order.push(svc.name);
231
+ }
232
+
233
+ /**
234
+ * Registers `svc`, replacing any service already under its name and
235
+ * keeping that name's original position in {@link list}.
236
+ *
237
+ * Still throws on an invalid name: override lifts the collision
238
+ * rule, not the grammar.
239
+ */
240
+ override(svc: Service): void {
241
+ const invalid = validateName(svc.name);
242
+ if (invalid) throw new ServiceRegistrationError(invalid);
243
+ if (!this.byName.has(svc.name)) this.order.push(svc.name);
244
+ this.byName.set(svc.name, svc);
245
+ }
246
+
247
+ /** The service registered under `name`, if any. */
248
+ lookup(name: string): Service | undefined {
249
+ return this.byName.get(name);
250
+ }
251
+
252
+ /** Every registered identifier, in registration order. */
253
+ names(): string[] {
254
+ return [...this.order];
255
+ }
256
+
257
+ /** Every registered service, in registration order. */
258
+ list(): Service[] {
259
+ return this.order.map((n) => this.byName.get(n)!);
260
+ }
261
+
262
+ /** Number of registered services. */
263
+ get size(): number {
264
+ return this.byName.size;
265
+ }
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Configuration
270
+ // ---------------------------------------------------------------------------
271
+
272
+ /** Default budget from start to readiness. `services.<name>.ready_timeout`. */
273
+ export const DEFAULT_READY_TIMEOUT_MS = 30_000;
274
+ /** Default budget for one stop. `services.<name>.stop_timeout`. */
275
+ export const DEFAULT_STOP_TIMEOUT_MS = 30_000;
276
+ /** Default total shutdown budget. `services.shutdown_timeout`. */
277
+ export const DEFAULT_SHUTDOWN_TIMEOUT_MS = 60_000;
278
+
279
+ /**
280
+ * The resolved `services.<name>` block for one service. Only the
281
+ * lifecycle keys are modeled; service-specific keys live in the same
282
+ * block and are read by the service itself.
283
+ */
284
+ export interface ServiceConfig {
285
+ /**
286
+ * `services.<name>.enabled`. Decides whether the supervisor form
287
+ * starts this service. Defaults to `false`: a service that starts
288
+ * listening because a dependency upgrade added it to the registry is
289
+ * an unrequested open port.
290
+ */
291
+ enabled?: boolean;
292
+ /** `services.<name>.ready_timeout`, in milliseconds. */
293
+ readyTimeoutMs?: number;
294
+ /** `services.<name>.stop_timeout`, in milliseconds. */
295
+ stopTimeoutMs?: number;
296
+ }
297
+
298
+ /** The supervisor's answer to "one service failed while others run". */
299
+ export type FailurePolicy = 'fail-fast' | 'isolate';
300
+
301
+ /** `services.failure_policy` default. */
302
+ export const DEFAULT_FAILURE_POLICY: FailurePolicy = 'fail-fast';
303
+
304
+ /** Reports whether `p` is a declared failure policy. */
305
+ export function isFailurePolicy(p: string): p is FailurePolicy {
306
+ return p === 'fail-fast' || p === 'isolate';
307
+ }
308
+
309
+ /** The supervisor-scoped half of the `services` block. */
310
+ export interface SupervisorConfig {
311
+ failurePolicy?: FailurePolicy;
312
+ shutdownTimeoutMs?: number;
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Outcomes and exit codes
317
+ // ---------------------------------------------------------------------------
318
+
319
+ /** The kinds of ending a serve run can have. */
320
+ export type LifecycleOutcome =
321
+ | 'clean-stop'
322
+ | 'invalid-selection'
323
+ | 'config-invalid'
324
+ | 'no-services'
325
+ | 'unknown-service'
326
+ | 'policy-denied'
327
+ | 'start-failed'
328
+ | 'runtime-crash'
329
+ | 'shutdown-timeout';
330
+
331
+ /**
332
+ * The contract's exit-behavior table, verbatim. Codes come from the
333
+ * shared taxonomy in `output/error`; this module allocates no new
334
+ * numbers.
335
+ *
336
+ * `start-failed` and `runtime-crash` share exit 1 deliberately: they
337
+ * differ in *when*, not in what an operator does next, and the
338
+ * distinguishing detail belongs in the message and the failed event
339
+ * rather than in a second numeric code.
340
+ */
341
+ const EXIT_TABLE: Record<LifecycleOutcome, { code: string; exit: number }> = {
342
+ 'clean-stop': { code: CODE_OK, exit: 0 },
343
+ 'invalid-selection': { code: CODE_USAGE, exit: 2 },
344
+ 'config-invalid': { code: CODE_USAGE, exit: 2 },
345
+ 'no-services': { code: CODE_USAGE, exit: 2 },
346
+ 'unknown-service': { code: CODE_NOT_FOUND, exit: 3 },
347
+ 'policy-denied': { code: CODE_UNAUTHORIZED, exit: 5 },
348
+ 'start-failed': { code: CODE_GENERIC, exit: 1 },
349
+ 'runtime-crash': { code: CODE_GENERIC, exit: 1 },
350
+ 'shutdown-timeout': { code: CODE_GENERIC, exit: 1 },
351
+ };
352
+
353
+ /**
354
+ * Process exit code for `o`. An outcome with no table row is treated
355
+ * as a generic failure rather than a success, so a kind added without
356
+ * a row fails loudly instead of silently exiting 0.
357
+ */
358
+ export function exitCodeFor(o: LifecycleOutcome): number {
359
+ return EXIT_TABLE[o]?.exit ?? 1;
360
+ }
361
+
362
+ /** The `CODE_*` string for `o`, for the rendered error envelope. */
363
+ export function codeFor(o: LifecycleOutcome): string {
364
+ return EXIT_TABLE[o]?.code ?? CODE_GENERIC;
365
+ }
366
+
367
+ /** Whether `o` exits non-zero. */
368
+ export function isFailure(o: LifecycleOutcome): boolean {
369
+ return exitCodeFor(o) !== 0;
370
+ }
371
+
372
+ /**
373
+ * The outcome the process should exit on given everything observed.
374
+ *
375
+ * "Worst" is severity, not exit-code magnitude: any failure beats a
376
+ * clean stop, and among failures the first observed wins, because it
377
+ * is the one that explains the rest. Under `isolate` a process may
378
+ * survive several failures, and the exit code must reflect the worst
379
+ * outcome across the whole run rather than the last one.
380
+ */
381
+ export function worstOutcome(observed: readonly LifecycleOutcome[]): LifecycleOutcome {
382
+ let worst: LifecycleOutcome = 'clean-stop';
383
+ for (const o of observed) {
384
+ if (isFailure(o) && !isFailure(worst)) worst = o;
385
+ }
386
+ return worst;
387
+ }
388
+
389
+ // ---------------------------------------------------------------------------
390
+ // Resolution — the hierarchy and the override rule
391
+ // ---------------------------------------------------------------------------
392
+
393
+ /** A parsed `serve` invocation. */
394
+ export interface ResolveRequest {
395
+ /**
396
+ * Positional arguments after the `serve` word. Empty is the
397
+ * supervisor form, exactly one the selector form, two or more a
398
+ * usage error.
399
+ */
400
+ args: readonly string[];
401
+ /**
402
+ * Resolved `services.<name>` block per service. A service with no
403
+ * entry is not configured, and the supervisor form skips it.
404
+ */
405
+ configs?: Readonly<Record<string, ServiceConfig>>;
406
+ /** The third validation gate. Omitted passes everything. */
407
+ policy?: PolicyGate;
408
+ }
409
+
410
+ /** The result of resolving a request against a registry. */
411
+ export interface ResolveOutcome {
412
+ /** Identifiers to run, in registration order. Empty when `error` is set. */
413
+ selected: string[];
414
+ /**
415
+ * True when the selector form was used. Under it `selected` holds
416
+ * exactly one name and aggregate enablement was overridden rather
417
+ * than consulted.
418
+ */
419
+ explicit: boolean;
420
+ /**
421
+ * Configured-but-disabled services the supervisor form passed over.
422
+ * Skipping is not an error and must not affect the exit code.
423
+ */
424
+ skipped: string[];
425
+ /** The refusal, already carrying its code and exit code. */
426
+ error?: CliError;
427
+ /** The outcome the refusal corresponds to. */
428
+ outcome?: LifecycleOutcome;
429
+ }
430
+
431
+ /**
432
+ * Turns a `serve` invocation into a runnable set, applying the
433
+ * hierarchy and the override rule. Pure: nothing is started, nothing
434
+ * binds, nothing is written.
435
+ *
436
+ * Selector form runs the named service **even when
437
+ * `services.<name>.enabled` is false**, provided all three gates pass
438
+ * in order — registration, then configuration, then policy.
439
+ * Enablement is not a gate there: an operator naming a service on the
440
+ * command line has already made the decision the flag exists to
441
+ * automate.
442
+ *
443
+ * Supervisor form runs every service that is both configured and
444
+ * enabled, in registration order, skipping a disabled one silently.
445
+ * Resolving to zero services is a usage error, not a clean exit: a
446
+ * process that exits 0 without listening is indistinguishable from a
447
+ * successful start to systemd or a container runtime.
448
+ */
449
+ export function resolve(
450
+ registry: ServiceRegistry,
451
+ req: ResolveRequest,
452
+ ): ResolveOutcome {
453
+ const base: ResolveOutcome = { selected: [], explicit: false, skipped: [] };
454
+
455
+ if (req.args.length > 1) {
456
+ return {
457
+ ...base,
458
+ outcome: 'invalid-selection',
459
+ error: usageError(
460
+ `serve accepts at most one service name, got ${req.args.length}`,
461
+ ),
462
+ };
463
+ }
464
+ if (req.args.length === 1) {
465
+ return resolveExplicit(registry, req, req.args[0]!);
466
+ }
467
+ return resolveAggregate(registry, req);
468
+ }
469
+
470
+ /** The selector form and its override rule. */
471
+ function resolveExplicit(
472
+ registry: ServiceRegistry,
473
+ req: ResolveRequest,
474
+ name: string,
475
+ ): ResolveOutcome {
476
+ const base: ResolveOutcome = { selected: [], explicit: true, skipped: [] };
477
+
478
+ // Gate 1: registration.
479
+ const svc = registry.lookup(name);
480
+ if (!svc) {
481
+ const known = registry.names();
482
+ const err = notFoundError(
483
+ `unknown service "${name}"; known: ${known.join(', ')}`,
484
+ );
485
+ const fix = nearestName(name, known);
486
+ if (fix) err.suggested_fix = `did you mean "${fix}"?`;
487
+ return { ...base, outcome: 'unknown-service', error: err };
488
+ }
489
+
490
+ // Gate 2: configuration.
491
+ const invalid = validateConfig(svc);
492
+ if (invalid) {
493
+ return {
494
+ ...base,
495
+ outcome: 'config-invalid',
496
+ error: usageError(`service "${name}": ${invalid}`),
497
+ };
498
+ }
499
+
500
+ // Gate 3: policy.
501
+ const denied = checkPolicy(req.policy, svc);
502
+ if (denied) return { ...base, outcome: 'policy-denied', error: denied };
503
+
504
+ // Enablement is deliberately not consulted here.
505
+ return { selected: [name], explicit: true, skipped: [] };
506
+ }
507
+
508
+ /** The supervisor form. */
509
+ function resolveAggregate(
510
+ registry: ServiceRegistry,
511
+ req: ResolveRequest,
512
+ ): ResolveOutcome {
513
+ const out: ResolveOutcome = { selected: [], explicit: false, skipped: [] };
514
+ const configs = req.configs ?? {};
515
+
516
+ for (const name of registry.names()) {
517
+ const cfg = configs[name];
518
+ if (cfg === undefined) continue; // not configured
519
+ if (cfg.enabled !== true) {
520
+ out.skipped.push(name);
521
+ continue;
522
+ }
523
+ const svc = registry.lookup(name);
524
+ if (!svc) continue;
525
+
526
+ const invalid = validateConfig(svc);
527
+ if (invalid) {
528
+ return {
529
+ selected: [], explicit: false, skipped: out.skipped,
530
+ outcome: 'config-invalid',
531
+ error: usageError(`service "${name}": ${invalid}`),
532
+ };
533
+ }
534
+ const denied = checkPolicy(req.policy, svc);
535
+ if (denied) {
536
+ return {
537
+ selected: [], explicit: false, skipped: out.skipped,
538
+ outcome: 'policy-denied', error: denied,
539
+ };
540
+ }
541
+ out.selected.push(name);
542
+ }
543
+
544
+ if (out.selected.length === 0) {
545
+ const err = usageError(
546
+ 'no services configured and enabled; enable one under services.* ' +
547
+ 'or name one explicitly',
548
+ );
549
+ err.suggested_fix = 'set services.<name>.enabled: true, or run: serve <service>';
550
+ out.error = err;
551
+ out.outcome = 'no-services';
552
+ }
553
+ return out;
554
+ }
555
+
556
+ function validateConfig(svc: Service): string | null {
557
+ return svc.validate ? svc.validate() : null;
558
+ }
559
+
560
+ function checkPolicy(
561
+ gate: PolicyGate | undefined,
562
+ svc: Service,
563
+ ): CliError | null {
564
+ if (!gate || !svc.class) return null;
565
+ const [sideEffect, network] = svc.class();
566
+ const verdict = gate.allow(sideEffect, network);
567
+ if (verdict.ok) return null;
568
+ let msg =
569
+ `service "${svc.name}" denied by policy ` +
570
+ `(side_effect=${sideEffect}, network=${network})`;
571
+ if (verdict.reason) msg += `: ${verdict.reason}`;
572
+ return unauthorizedError(msg);
573
+ }
574
+
575
+ /**
576
+ * The registered name closest to `want` by edit distance, or `null`
577
+ * when nothing is close enough to suggest. The threshold scales with
578
+ * the typed word's length so a short name does not attract an
579
+ * unrelated suggestion.
580
+ */
581
+ function nearestName(want: string, known: readonly string[]): string | null {
582
+ let best: string | null = null;
583
+ let bestDist = -1;
584
+ const limit = Math.floor(want.length / 2) + 1;
585
+ for (const k of [...known].sort()) {
586
+ const d = editDistance(want, k);
587
+ if (d > limit) continue;
588
+ if (bestDist === -1 || d < bestDist) {
589
+ best = k;
590
+ bestDist = d;
591
+ }
592
+ }
593
+ return best;
594
+ }
595
+
596
+ function editDistance(a: string, b: string): number {
597
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
598
+ let cur = new Array<number>(b.length + 1).fill(0);
599
+ for (let i = 1; i <= a.length; i++) {
600
+ cur[0] = i;
601
+ for (let j = 1; j <= b.length; j++) {
602
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
603
+ cur[j] = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + cost);
604
+ }
605
+ [prev, cur] = [cur, prev];
606
+ }
607
+ return prev[b.length]!;
608
+ }
609
+
610
+ // ---------------------------------------------------------------------------
611
+ // Ordering
612
+ // ---------------------------------------------------------------------------
613
+
614
+ /**
615
+ * `selected` in topological order over the optional `dependsOn`
616
+ * declarations, ties broken by the order in `selected` (which
617
+ * {@link resolve} returns in registration order).
618
+ *
619
+ * A dependency naming a service outside `selected` is ignored rather
620
+ * than an error: under the selector form exactly one service runs, and
621
+ * its dependencies are the operator's business, not a reason to refuse
622
+ * a deliberate single-service start.
623
+ *
624
+ * A dependency cycle throws, in the same class as a name collision: it
625
+ * is a wiring bug that can only be fixed by editing the registrations,
626
+ * and there is no order the supervisor could pick that would be right.
627
+ */
628
+ export function startOrder(
629
+ registry: ServiceRegistry,
630
+ selected: readonly string[],
631
+ ): string[] {
632
+ const inSet = new Set(selected);
633
+ const deps = new Map<string, string[]>();
634
+
635
+ for (const name of selected) {
636
+ const svc = registry.lookup(name);
637
+ if (!svc?.dependsOn) continue;
638
+ const want = svc.dependsOn().filter((d) => inSet.has(d) && d !== name);
639
+ if (want.length > 0) deps.set(name, want);
640
+ }
641
+
642
+ const WHITE = 0, GREY = 1, BLACK = 2;
643
+ const mark = new Map<string, number>();
644
+ const out: string[] = [];
645
+
646
+ const visit = (name: string, path: string[]): void => {
647
+ const state = mark.get(name) ?? WHITE;
648
+ if (state === BLACK) return;
649
+ if (state === GREY) {
650
+ throw new ServiceRegistrationError(
651
+ `serve: dependency cycle: ${[...path, name].join(' -> ')}`,
652
+ );
653
+ }
654
+ mark.set(name, GREY);
655
+ for (const want of deps.get(name) ?? []) visit(want, [...path, name]);
656
+ mark.set(name, BLACK);
657
+ out.push(name);
658
+ };
659
+
660
+ for (const name of selected) visit(name, []);
661
+ return out;
662
+ }
663
+
664
+ // ---------------------------------------------------------------------------
665
+ // Lifecycle events
666
+ // ---------------------------------------------------------------------------
667
+
668
+ /** The 2-segment source.category prefix serve events publish under. */
669
+ export const DEFAULT_TOPIC_PREFIX = 'kit.serve';
670
+
671
+ /** Action segments. A bare `ready` does not validate; do not use one. */
672
+ export const ACTION_STARTED = 'started';
673
+ export const ACTION_READY_REPORTED = 'ready_reported';
674
+ export const ACTION_FAILED = 'failed';
675
+ export const ACTION_STOPPED = 'stopped';
676
+
677
+ /**
678
+ * Object segments. The service identifier travels in the payload, not
679
+ * the topic, so subscribers are not forced to re-bind when a tool
680
+ * gains a service.
681
+ */
682
+ export const OBJECT_SERVICE = 'service';
683
+ export const OBJECT_SUPERVISOR = 'supervisor';
684
+
685
+ /**
686
+ * The conformant topic set for `prefix`, keyed `<object>.<action>`.
687
+ * These strings are contract: a subscriber is written against them and
688
+ * does not know which language published.
689
+ */
690
+ export function defaultTopics(
691
+ prefix: string = DEFAULT_TOPIC_PREFIX,
692
+ ): Record<string, string> {
693
+ const p = prefix === '' ? DEFAULT_TOPIC_PREFIX : prefix;
694
+ const out: Record<string, string> = {};
695
+ for (const [object, action] of [
696
+ [OBJECT_SERVICE, ACTION_STARTED],
697
+ [OBJECT_SERVICE, ACTION_READY_REPORTED],
698
+ [OBJECT_SERVICE, ACTION_FAILED],
699
+ [OBJECT_SERVICE, ACTION_STOPPED],
700
+ [OBJECT_SUPERVISOR, ACTION_READY_REPORTED],
701
+ [OBJECT_SUPERVISOR, ACTION_STOPPED],
702
+ ] as const) {
703
+ out[`${object}.${action}`] = `${p}.${object}.${action}`;
704
+ }
705
+ return out;
706
+ }
707
+
708
+ /** The body of every serve lifecycle event. */
709
+ export interface EventPayload {
710
+ /** Service the event concerns. Absent for supervisor-scoped events. */
711
+ service?: string;
712
+ /** Failure text for a `failed` event. Never in the topic. */
713
+ error?: string;
714
+ /** Why, for events that have a reason. */
715
+ reason?: string;
716
+ /** Milliseconds since the supervisor began the run. */
717
+ elapsed_ms: number;
718
+ /** Where the service accepts work, on `ready_reported` only. */
719
+ address?: string;
720
+ }
721
+
722
+ /**
723
+ * The narrow slice of a bus the supervisor needs. Omitting one means
724
+ * events are not published; the log counterpart still runs, so a tool
725
+ * with no bus still produces an operator-legible startup trace.
726
+ */
727
+ export interface Publisher {
728
+ publish(event: { topic: string; source: string; payload: EventPayload }): void;
729
+ }
730
+
731
+ /**
732
+ * The narrow slice of a structured logger the supervisor needs. It
733
+ * matches the shape `@hop-top/kit/log` returns, so a kit logger
734
+ * satisfies it without an adapter.
735
+ */
736
+ export interface ServeLogger {
737
+ info(msg: string, ...keyvals: unknown[]): void;
738
+ error(msg: string, ...keyvals: unknown[]): void;
739
+ }
740
+
741
+ /** Publishes one lifecycle transition to both sinks. */
742
+ class Emitter {
743
+ constructor(
744
+ private readonly topics: Record<string, string>,
745
+ private readonly source: string,
746
+ private readonly pub?: Publisher,
747
+ private readonly log?: ServeLogger,
748
+ ) {}
749
+
750
+ emit(object: string, action: string, payload: EventPayload): void {
751
+ this.logEvent(object, action, payload);
752
+ if (!this.pub) return;
753
+ const topic = this.topics[`${object}.${action}`];
754
+ if (!topic) return;
755
+ try {
756
+ this.pub.publish({ topic, source: this.source, payload });
757
+ } catch {
758
+ // An event sink is observability, not correctness: a publish
759
+ // failure never fails the lifecycle.
760
+ }
761
+ }
762
+
763
+ private logEvent(object: string, action: string, payload: EventPayload): void {
764
+ if (!this.log) return;
765
+ const kv: unknown[] = ['object', object, 'elapsed_ms', payload.elapsed_ms];
766
+ if (payload.service) kv.push('service', payload.service);
767
+ if (payload.address) kv.push('address', payload.address);
768
+ if (payload.reason) kv.push('reason', payload.reason);
769
+ if (action === ACTION_FAILED) {
770
+ if (payload.error) kv.push('error', payload.error);
771
+ this.log.error(`serve: ${action}`, ...kv);
772
+ return;
773
+ }
774
+ this.log.info(`serve: ${action}`, ...kv);
775
+ }
776
+ }
777
+
778
+ // ---------------------------------------------------------------------------
779
+ // Supervisor
780
+ // ---------------------------------------------------------------------------
781
+
782
+ /** What one supervised run produced. */
783
+ export interface RunResult {
784
+ /** The worst outcome observed, which is what the process exits on. */
785
+ outcome: LifecycleOutcome;
786
+ /** The rendered failure carrying code and exit code; absent on a clean stop. */
787
+ error?: CliError;
788
+ /** Identifiers whose start was invoked, in invocation order. */
789
+ started: string[];
790
+ /** Identifiers that reported ready, in report order. */
791
+ ready: string[];
792
+ /** Identifier to the error it failed with. */
793
+ failed: Record<string, string>;
794
+ /** The process exit code for this run. */
795
+ exitCode: number;
796
+ }
797
+
798
+ /** Options for {@link Supervisor}. */
799
+ export interface SupervisorOptions {
800
+ config?: SupervisorConfig;
801
+ publisher?: Publisher;
802
+ logger?: ServeLogger;
803
+ topics?: Record<string, string>;
804
+ eventSource?: string;
805
+ /** Replaces the notion of elapsed time. Tests use it; production does not. */
806
+ now?: () => number;
807
+ /**
808
+ * Aborts the drain. A second signal fires this, so an operator can
809
+ * escalate without reaching for SIGKILL.
810
+ */
811
+ escalate?: AbortSignal;
812
+ }
813
+
814
+ /**
815
+ * Runs a resolved set of services under one lifecycle: ordered start,
816
+ * per-service readiness, policy-driven reaction to failure, and
817
+ * ordered stop bounded by the configured budgets.
818
+ *
819
+ * A Supervisor holds no module-level state, so two can run
820
+ * concurrently in one process — which is exactly what a test does.
821
+ */
822
+ export class Supervisor {
823
+ private readonly failurePolicy: FailurePolicy;
824
+ private readonly shutdownTimeoutMs: number;
825
+ private readonly emitter: Emitter;
826
+ private readonly now: () => number;
827
+ private readonly escalate?: AbortSignal;
828
+
829
+ constructor(
830
+ private readonly registry: ServiceRegistry,
831
+ opts: SupervisorOptions = {},
832
+ ) {
833
+ this.failurePolicy = opts.config?.failurePolicy ?? DEFAULT_FAILURE_POLICY;
834
+ this.shutdownTimeoutMs =
835
+ opts.config?.shutdownTimeoutMs && opts.config.shutdownTimeoutMs > 0
836
+ ? opts.config.shutdownTimeoutMs
837
+ : DEFAULT_SHUTDOWN_TIMEOUT_MS;
838
+ this.emitter = new Emitter(
839
+ opts.topics ?? defaultTopics(),
840
+ opts.eventSource ?? DEFAULT_TOPIC_PREFIX,
841
+ opts.publisher,
842
+ opts.logger,
843
+ );
844
+ this.now = opts.now ?? (() => Date.now());
845
+ this.escalate = opts.escalate;
846
+ }
847
+
848
+ /**
849
+ * Starts every service in `selected`, waits for the run to end, and
850
+ * stops everything in reverse start order.
851
+ *
852
+ * The run ends when `signal` aborts (the clean path: a signal, or
853
+ * the caller's own shutdown), when a failure trips the failure
854
+ * policy, or when every started service has returned. Run always
855
+ * performs the ordered stop before returning, so a caller never has
856
+ * to clean up after it.
857
+ *
858
+ * `selected` is normally {@link ResolveOutcome.selected}; run does
859
+ * not re-resolve and does not consult enablement, because the
860
+ * decision the caller already made is the one to honor.
861
+ */
862
+ async run(
863
+ signal: AbortSignal,
864
+ selected: readonly string[],
865
+ configs: Readonly<Record<string, ServiceConfig>> = {},
866
+ ): Promise<RunResult> {
867
+ const st = new RunState(this.now);
868
+
869
+ if (selected.length === 0) {
870
+ const err = usageError(
871
+ 'no services configured and enabled; enable one under services.* ' +
872
+ 'or name one explicitly',
873
+ );
874
+ return this.finish(st, 'no-services', err);
875
+ }
876
+
877
+ const order = startOrder(this.registry, selected);
878
+
879
+ // The run controller is the caller's signal plus a cancel the
880
+ // supervisor itself trips when the failure policy says to bring
881
+ // everything down. Every service observes cancellation at the same
882
+ // instant; nothing is queued behind another service's drain.
883
+ const runAC = new AbortController();
884
+ const onOuterAbort = (): void => runAC.abort();
885
+ if (signal.aborted) runAC.abort();
886
+ else signal.addEventListener('abort', onOuterAbort, { once: true });
887
+
888
+ // Serving is the process's reason to stay alive, and nothing else
889
+ // here refs the event loop. Held for the whole run, released in the
890
+ // finally so it never outlives one.
891
+ const keepAlive = new LoopKeepAlive();
892
+ keepAlive.hold();
893
+
894
+ try {
895
+ const startFailed = await this.startAll(runAC, order, configs, st);
896
+ if (!startFailed) {
897
+ this.emitAggregateReady(st);
898
+ await this.await_(runAC, st);
899
+ }
900
+ runAC.abort();
901
+ await this.stopAll(st, configs);
902
+ return this.finish(st, worstOutcome(st.observed));
903
+ } finally {
904
+ keepAlive.release();
905
+ signal.removeEventListener('abort', onOuterAbort);
906
+ }
907
+ }
908
+
909
+ /**
910
+ * Starts each service in order, waiting for each to report ready
911
+ * (or fail, or exhaust its budget) before starting the next.
912
+ *
913
+ * Serial start is what makes `dependsOn` mean anything: a dependent
914
+ * must not begin acquiring before its dependency is accepting work.
915
+ * Returns true when a start failure short-circuits the sequence.
916
+ */
917
+ private async startAll(
918
+ runAC: AbortController,
919
+ order: readonly string[],
920
+ configs: Readonly<Record<string, ServiceConfig>>,
921
+ st: RunState,
922
+ ): Promise<boolean> {
923
+ for (const name of order) {
924
+ const svc = this.registry.lookup(name);
925
+ if (!svc) {
926
+ const msg = `service "${name}" disappeared from the registry`;
927
+ st.noteFailure(name, msg, 'start-failed');
928
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
929
+ service: name, error: msg, reason: 'unregistered',
930
+ elapsed_ms: st.elapsedMs(),
931
+ });
932
+ return true;
933
+ }
934
+
935
+ let reportReady!: () => void;
936
+ const readyPromise = new Promise<void>((res) => { reportReady = res; });
937
+ st.started.push(name);
938
+ this.emitter.emit(OBJECT_SERVICE, ACTION_STARTED, {
939
+ service: name, elapsed_ms: st.elapsedMs(),
940
+ });
941
+
942
+ const running = svc
943
+ .start(runAC.signal, reportReady)
944
+ .then(() => ({ name, error: null as string | null }))
945
+ .catch((e: unknown) => ({ name, error: errText(e) }));
946
+ st.live.set(name, running);
947
+
948
+ const failed = await this.awaitReady(name, readyPromise, configs, st);
949
+ if (failed) return true;
950
+ }
951
+ return false;
952
+ }
953
+
954
+ /**
955
+ * Blocks until `name` reports ready, fails, or exhausts its
956
+ * readiness budget. A service that has not reported ready within the
957
+ * budget is a start failure.
958
+ */
959
+ private async awaitReady(
960
+ name: string,
961
+ readyPromise: Promise<void>,
962
+ configs: Readonly<Record<string, ServiceConfig>>,
963
+ st: RunState,
964
+ ): Promise<boolean> {
965
+ const budget = configs[name]?.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
966
+ const timer = new Timer(budget);
967
+ const running = st.live.get(name)!;
968
+
969
+ try {
970
+ const winner = await Promise.race([
971
+ readyPromise.then(() => 'ready' as const),
972
+ running.then((e) => ({ exit: e })),
973
+ timer.promise.then(() => 'timeout' as const),
974
+ ]);
975
+
976
+ if (winner === 'ready') {
977
+ st.ready.push(name);
978
+ this.emitter.emit(OBJECT_SERVICE, ACTION_READY_REPORTED, {
979
+ service: name,
980
+ address: this.addrOf(name),
981
+ elapsed_ms: st.elapsedMs(),
982
+ });
983
+ return false;
984
+ }
985
+
986
+ if (winner === 'timeout') {
987
+ const msg = `not ready within ${budget}ms`;
988
+ st.noteFailure(name, msg, 'start-failed');
989
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
990
+ service: name, error: msg, reason: 'ready_timeout',
991
+ elapsed_ms: st.elapsedMs(),
992
+ });
993
+ return true;
994
+ }
995
+
996
+ // The service returned before reporting ready. That is a start
997
+ // failure even when it returned cleanly: it was asked to serve
998
+ // and it did not.
999
+ st.live.delete(name);
1000
+ const msg = winner.exit.error ?? 'returned before reporting ready';
1001
+ st.noteFailure(name, msg, 'start-failed');
1002
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1003
+ service: name, error: msg, reason: 'start',
1004
+ elapsed_ms: st.elapsedMs(),
1005
+ });
1006
+ return true;
1007
+ } finally {
1008
+ timer.cancel();
1009
+ }
1010
+ }
1011
+
1012
+ /**
1013
+ * Publishes the supervisor-scoped readiness event once every started
1014
+ * service is ready.
1015
+ */
1016
+ private emitAggregateReady(st: RunState): void {
1017
+ if (st.started.length > 0 && st.ready.length === st.started.length) {
1018
+ this.emitter.emit(OBJECT_SUPERVISOR, ACTION_READY_REPORTED, {
1019
+ elapsed_ms: st.elapsedMs(),
1020
+ });
1021
+ }
1022
+ }
1023
+
1024
+ /**
1025
+ * Blocks while the services run. Returns when the run signal aborts,
1026
+ * when the failure policy trips, or when the last running service
1027
+ * has exited.
1028
+ */
1029
+ private async await_(runAC: AbortController, st: RunState): Promise<void> {
1030
+ const aborted = new Promise<'aborted'>((res) => {
1031
+ if (runAC.signal.aborted) { res('aborted'); return; }
1032
+ runAC.signal.addEventListener('abort', () => res('aborted'), { once: true });
1033
+ });
1034
+
1035
+ while (st.live.size > 0) {
1036
+ const races = [...st.live.entries()].map(([, p]) => p);
1037
+ const winner = await Promise.race([aborted, ...races]);
1038
+ if (winner === 'aborted') return;
1039
+
1040
+ st.live.delete(winner.name);
1041
+ if (winner.error !== null) {
1042
+ st.noteFailure(winner.name, winner.error, 'runtime-crash');
1043
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1044
+ service: winner.name, error: winner.error, reason: 'runtime',
1045
+ elapsed_ms: st.elapsedMs(),
1046
+ });
1047
+ if (this.failurePolicy === 'fail-fast') {
1048
+ runAC.abort();
1049
+ return;
1050
+ }
1051
+ continue;
1052
+ }
1053
+ // A clean return under isolate is not a failure of that service,
1054
+ // but the process must not survive as an empty shell: when the
1055
+ // last one is gone the run is over.
1056
+ if (!st.markStopped(winner.name)) {
1057
+ this.emitter.emit(OBJECT_SERVICE, ACTION_STOPPED, {
1058
+ service: winner.name, elapsed_ms: st.elapsedMs(),
1059
+ });
1060
+ }
1061
+ }
1062
+
1063
+ if (Object.keys(st.failed).length > 0 && this.failurePolicy === 'isolate') {
1064
+ st.observed.push('runtime-crash');
1065
+ }
1066
+ }
1067
+
1068
+ /**
1069
+ * Invokes stop in the exact reverse of the order services actually
1070
+ * started, one at a time, so a dependent is always fully stopped
1071
+ * before its dependency.
1072
+ *
1073
+ * Each stop is bounded by that service's budget. One that exceeds it
1074
+ * is abandoned — logged, emitted as failed, and the supervisor
1075
+ * proceeds to the next rather than blocking the whole shutdown on
1076
+ * one straggler. Exceeding the total budget ends the sequence with
1077
+ * `shutdown-timeout`.
1078
+ */
1079
+ private async stopAll(
1080
+ st: RunState,
1081
+ configs: Readonly<Record<string, ServiceConfig>>,
1082
+ ): Promise<void> {
1083
+ const order = [...st.started];
1084
+ const deadline = this.now() + this.shutdownTimeoutMs;
1085
+
1086
+ for (let i = order.length - 1; i >= 0; i--) {
1087
+ const name = order[i]!;
1088
+
1089
+ // A second signal aborts the drain: the remaining services are
1090
+ // abandoned and the run exits with the crash code.
1091
+ if (this.escalate?.aborted) {
1092
+ const msg = 'drain aborted by second signal';
1093
+ st.observed.push('runtime-crash');
1094
+ for (const abandoned of order.slice(0, i + 1)) {
1095
+ st.failed[abandoned] = msg;
1096
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1097
+ service: abandoned, error: msg, reason: 'escalated',
1098
+ elapsed_ms: st.elapsedMs(),
1099
+ });
1100
+ }
1101
+ return;
1102
+ }
1103
+
1104
+ if (this.now() >= deadline) {
1105
+ st.observed.push('shutdown-timeout');
1106
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1107
+ service: name, reason: 'shutdown_timeout',
1108
+ error: `shutdown budget ${this.shutdownTimeoutMs}ms exhausted before stopping`,
1109
+ elapsed_ms: st.elapsedMs(),
1110
+ });
1111
+ continue;
1112
+ }
1113
+
1114
+ const svc = this.registry.lookup(name);
1115
+ if (!svc) continue;
1116
+
1117
+ const budget = Math.min(
1118
+ configs[name]?.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS,
1119
+ Math.max(0, deadline - this.now()),
1120
+ );
1121
+ await this.stopOne(svc, name, budget, deadline, st);
1122
+ }
1123
+ }
1124
+
1125
+ /** Bounds one stop by its budget and by whatever remains of the total. */
1126
+ private async stopOne(
1127
+ svc: Service,
1128
+ name: string,
1129
+ budget: number,
1130
+ deadline: number,
1131
+ st: RunState,
1132
+ ): Promise<void> {
1133
+ const stopAC = new AbortController();
1134
+ const timer = new Timer(budget);
1135
+ try {
1136
+ const winner = await Promise.race([
1137
+ svc.stop(stopAC.signal).then(() => 'ok' as const, (e: unknown) => ({ err: errText(e) })),
1138
+ timer.promise.then(() => 'timeout' as const),
1139
+ ]);
1140
+
1141
+ if (winner === 'timeout') {
1142
+ // Abandoned, not awaited: the promise is left to settle on its
1143
+ // own so one straggler cannot hold the whole shutdown.
1144
+ stopAC.abort();
1145
+ const overTotal = this.now() >= deadline;
1146
+ st.noteFailure(
1147
+ name,
1148
+ `stop exceeded ${budget}ms`,
1149
+ overTotal ? 'shutdown-timeout' : 'runtime-crash',
1150
+ );
1151
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1152
+ service: name, error: `stop exceeded ${budget}ms`,
1153
+ reason: overTotal ? 'shutdown_timeout' : 'stop_timeout',
1154
+ elapsed_ms: st.elapsedMs(),
1155
+ });
1156
+ return;
1157
+ }
1158
+
1159
+ if (winner !== 'ok') {
1160
+ st.noteFailure(name, winner.err, 'runtime-crash');
1161
+ this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
1162
+ service: name, error: winner.err, reason: 'stop',
1163
+ elapsed_ms: st.elapsedMs(),
1164
+ });
1165
+ return;
1166
+ }
1167
+
1168
+ // A service that returned on its own already reported stopped
1169
+ // when it did; stop released its resources, and the event is not
1170
+ // repeated — one stopped per service per run.
1171
+ if (st.markStopped(name)) return;
1172
+ this.emitter.emit(OBJECT_SERVICE, ACTION_STOPPED, {
1173
+ service: name, elapsed_ms: st.elapsedMs(),
1174
+ });
1175
+ } finally {
1176
+ timer.cancel();
1177
+ }
1178
+ }
1179
+
1180
+ private addrOf(name: string): string | undefined {
1181
+ const a = this.registry.lookup(name)?.addr?.();
1182
+ return a === '' ? undefined : a;
1183
+ }
1184
+
1185
+ /** Assembles the result from everything the run observed. */
1186
+ private finish(
1187
+ st: RunState,
1188
+ outcome: LifecycleOutcome,
1189
+ err?: CliError,
1190
+ ): RunResult {
1191
+ const error = err ?? (isFailure(outcome) ? failureError(outcome, st.failed) : undefined);
1192
+ this.emitter.emit(OBJECT_SUPERVISOR, ACTION_STOPPED, {
1193
+ reason: outcome, elapsed_ms: st.elapsedMs(),
1194
+ });
1195
+ return {
1196
+ outcome,
1197
+ error,
1198
+ started: [...st.started],
1199
+ ready: [...st.ready],
1200
+ failed: { ...st.failed },
1201
+ exitCode: exitCodeFor(outcome),
1202
+ };
1203
+ }
1204
+ }
1205
+
1206
+ /** One service's start settling. */
1207
+ interface ServiceExit {
1208
+ name: string;
1209
+ error: string | null;
1210
+ }
1211
+
1212
+ /** The mutable half of one run, kept off the Supervisor. */
1213
+ class RunState {
1214
+ readonly started: string[] = [];
1215
+ readonly ready: string[] = [];
1216
+ readonly failed: Record<string, string> = {};
1217
+ readonly observed: LifecycleOutcome[] = [];
1218
+ readonly live = new Map<string, Promise<ServiceExit>>();
1219
+ private readonly stopped = new Set<string>();
1220
+ private readonly begin: number;
1221
+
1222
+ constructor(private readonly now: () => number) {
1223
+ this.begin = now();
1224
+ }
1225
+
1226
+ elapsedMs(): number {
1227
+ return this.now() - this.begin;
1228
+ }
1229
+
1230
+ noteFailure(name: string, error: string, outcome: LifecycleOutcome): void {
1231
+ this.failed[name] = error;
1232
+ this.observed.push(outcome);
1233
+ }
1234
+
1235
+ /**
1236
+ * Records that `name`'s stopped event has been emitted and reports
1237
+ * whether it had been already. A service reports stopped once per
1238
+ * run, whichever path noticed it first.
1239
+ */
1240
+ markStopped(name: string): boolean {
1241
+ const already = this.stopped.has(name);
1242
+ this.stopped.add(name);
1243
+ return already;
1244
+ }
1245
+ }
1246
+
1247
+ /**
1248
+ * Holds the Node event loop open for as long as a run is live.
1249
+ *
1250
+ * Neither a `process.on(signal)` listener nor an `AbortSignal` listener
1251
+ * refs the loop: a supervisor whose services are all parked on their
1252
+ * abort signal has no referenced handle, and Node exits 0 the moment
1253
+ * the synchronous part of `run` yields. That is the failure the
1254
+ * contract's zero-services rule exists to prevent, arriving by another
1255
+ * route — a process that exits 0 without listening is
1256
+ * indistinguishable from a successful start to systemd or a container
1257
+ * runtime.
1258
+ *
1259
+ * A long referenced interval is the cheapest handle that survives every
1260
+ * platform; it is cleared the moment the run ends, so it never delays
1261
+ * an exit.
1262
+ */
1263
+ export class LoopKeepAlive {
1264
+ private handle?: ReturnType<typeof setInterval>;
1265
+
1266
+ hold(): void {
1267
+ if (this.handle) return;
1268
+ this.handle = setInterval(() => { /* referenced handle only */ }, 2 ** 30);
1269
+ }
1270
+
1271
+ release(): void {
1272
+ if (!this.handle) return;
1273
+ clearInterval(this.handle);
1274
+ this.handle = undefined;
1275
+ }
1276
+
1277
+ /**
1278
+ * Whether a referenced handle is currently held.
1279
+ *
1280
+ * Node's `process._getActiveHandles()` does not report timers, so
1281
+ * this is the only honest way to observe the property that matters.
1282
+ */
1283
+ get held(): boolean {
1284
+ return this.handle !== undefined && this.handle.hasRef?.() !== false;
1285
+ }
1286
+ }
1287
+
1288
+ /** A cancellable timer whose promise resolves when the budget elapses. */
1289
+ class Timer {
1290
+ readonly promise: Promise<void>;
1291
+ private handle?: ReturnType<typeof setTimeout>;
1292
+
1293
+ constructor(ms: number) {
1294
+ this.promise = new Promise<void>((res) => {
1295
+ this.handle = setTimeout(res, Math.max(0, ms));
1296
+ // Never hold the process open on a budget nobody is waiting for.
1297
+ this.handle.unref?.();
1298
+ });
1299
+ }
1300
+
1301
+ cancel(): void {
1302
+ if (this.handle) clearTimeout(this.handle);
1303
+ }
1304
+ }
1305
+
1306
+ function errText(e: unknown): string {
1307
+ if (e instanceof Error) return e.message;
1308
+ return String(e);
1309
+ }
1310
+
1311
+ /**
1312
+ * Renders the outcome as the error envelope the command layer returns,
1313
+ * carrying the contract's code and exit code.
1314
+ */
1315
+ function failureError(
1316
+ outcome: LifecycleOutcome,
1317
+ failed: Readonly<Record<string, string>>,
1318
+ ): CliError {
1319
+ const names = Object.keys(failed).sort();
1320
+ let msg: string;
1321
+ switch (outcome) {
1322
+ case 'start-failed': msg = 'service failed to start'; break;
1323
+ case 'shutdown-timeout': msg = 'shutdown budget exceeded'; break;
1324
+ default: msg = 'service failed';
1325
+ }
1326
+ names.forEach((name, i) => {
1327
+ msg += `${i === 0 ? ': ' : '; '}${name}: ${failed[name]}`;
1328
+ });
1329
+ return {
1330
+ code: codeFor(outcome),
1331
+ message: msg,
1332
+ exit_code: exitCodeFor(outcome),
1333
+ transience: 'permanent',
1334
+ };
1335
+ }
1336
+
1337
+ // ---------------------------------------------------------------------------
1338
+ // Signals
1339
+ // ---------------------------------------------------------------------------
1340
+
1341
+ /** The signals the supervisor listens for. SIGKILL is not catchable. */
1342
+ export const SHUTDOWN_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM'];
1343
+
1344
+ /**
1345
+ * A signal handler pair: `signal` aborts on the first SIGINT/SIGTERM,
1346
+ * `escalate` on a second of either kind.
1347
+ *
1348
+ * The first signal begins graceful shutdown; a second aborts the
1349
+ * drain, so an operator can escalate without reaching for SIGKILL.
1350
+ * `stop` removes the process listeners and must be called, or the
1351
+ * handlers outlive the run.
1352
+ */
1353
+ export function signalController(): {
1354
+ signal: AbortSignal;
1355
+ escalate: AbortSignal;
1356
+ stop: () => void;
1357
+ } {
1358
+ const first = new AbortController();
1359
+ const second = new AbortController();
1360
+ let count = 0;
1361
+
1362
+ const onSignal = (): void => {
1363
+ count++;
1364
+ if (count === 1) first.abort();
1365
+ else second.abort();
1366
+ };
1367
+
1368
+ for (const sig of SHUTDOWN_SIGNALS) process.on(sig, onSignal);
1369
+
1370
+ let stopped = false;
1371
+ return {
1372
+ signal: first.signal,
1373
+ escalate: second.signal,
1374
+ stop: () => {
1375
+ if (stopped) return;
1376
+ stopped = true;
1377
+ for (const sig of SHUTDOWN_SIGNALS) process.removeListener(sig, onSignal);
1378
+ },
1379
+ };
1380
+ }
1381
+
1382
+ // ---------------------------------------------------------------------------
1383
+ // Flag overrides
1384
+ // ---------------------------------------------------------------------------
1385
+
1386
+ /**
1387
+ * Applies `--enable` / `--disable` on top of the resolved
1388
+ * `services.<name>` blocks, returning a new map.
1389
+ *
1390
+ * An unconfigured service becomes configured the moment an operator
1391
+ * names it in `--enable`: the flag is the aggregate equivalent of the
1392
+ * selector's override rule. `--disable` on a configured service clears
1393
+ * its enablement so the supervisor form skips it silently; on an
1394
+ * unconfigured service it is a no-op. Enable wins over disable for the
1395
+ * same name — the affirmative act is the more specific one.
1396
+ */
1397
+ export function applyEnableDisable(
1398
+ configs: Readonly<Record<string, ServiceConfig>>,
1399
+ enable: readonly string[],
1400
+ disable: readonly string[],
1401
+ ): Record<string, ServiceConfig> {
1402
+ const out: Record<string, ServiceConfig> = { ...configs };
1403
+ for (const name of disable) {
1404
+ if (out[name] !== undefined) out[name] = { ...out[name], enabled: false };
1405
+ }
1406
+ for (const name of enable) {
1407
+ out[name] = { ...(out[name] ?? {}), enabled: true };
1408
+ }
1409
+ return out;
1410
+ }
1411
+
1412
+ /**
1413
+ * Applies `--ready-timeout` / `--stop-timeout` across every resolved
1414
+ * service, returning a new map. The flags map onto the per-service
1415
+ * keys, so a flag set on the supervisor form applies the same budget
1416
+ * to every member of the set — which is what an operator tuning a
1417
+ * whole process, rather than one service, is asking for.
1418
+ */
1419
+ export function applyTimeoutOverrides(
1420
+ configs: Readonly<Record<string, ServiceConfig>>,
1421
+ readyTimeoutMs?: number,
1422
+ stopTimeoutMs?: number,
1423
+ ): Record<string, ServiceConfig> {
1424
+ const ready = readyTimeoutMs !== undefined && readyTimeoutMs > 0;
1425
+ const stop = stopTimeoutMs !== undefined && stopTimeoutMs > 0;
1426
+ if (!ready && !stop) return { ...configs };
1427
+ const out: Record<string, ServiceConfig> = {};
1428
+ for (const [name, cfg] of Object.entries(configs)) {
1429
+ out[name] = {
1430
+ ...cfg,
1431
+ ...(ready ? { readyTimeoutMs } : {}),
1432
+ ...(stop ? { stopTimeoutMs } : {}),
1433
+ };
1434
+ }
1435
+ return out;
1436
+ }
1437
+
1438
+ const DURATION_UNIT_MS: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
1439
+
1440
+ /**
1441
+ * Parses a duration flag value into milliseconds, or `null` when it
1442
+ * does not parse. Accepts Go's value+unit sequence (`30s`, `1m30s`,
1443
+ * `500ms`) and a bare number, read as seconds the way the config keys
1444
+ * are. The spelling accepted here is not contract; the flag names are.
1445
+ */
1446
+ export function parseDurationMs(raw: string): number | null {
1447
+ const s = raw.trim();
1448
+ if (s === '') return null;
1449
+ if (/^\d+(?:\.\d+)?$/.test(s)) return Number(s) * 1_000;
1450
+ const re = /(\d+(?:\.\d+)?)(ms|s|m|h)/g;
1451
+ let total = 0;
1452
+ let consumed = '';
1453
+ for (const m of s.matchAll(re)) {
1454
+ consumed += m[0];
1455
+ total += Number(m[1]) * DURATION_UNIT_MS[m[2]!]!;
1456
+ }
1457
+ // The matches must account for the whole string, or "30x" would
1458
+ // silently parse as 30s.
1459
+ return consumed === s ? total : null;
1460
+ }
1461
+
1462
+ // ---------------------------------------------------------------------------
1463
+ // Command wiring
1464
+ // ---------------------------------------------------------------------------
1465
+
1466
+ /** Options for {@link registerServe}. */
1467
+ export interface RegisterServeOptions {
1468
+ /** The seam services were registered into. */
1469
+ registry: ServiceRegistry;
1470
+ /** Resolved `services.<name>` blocks, keyed by identifier. */
1471
+ configs?: Readonly<Record<string, ServiceConfig>>;
1472
+ /** The supervisor-scoped half of the `services` block. */
1473
+ config?: SupervisorConfig;
1474
+ /** The third validation gate. */
1475
+ policy?: PolicyGate;
1476
+ publisher?: Publisher;
1477
+ logger?: ServeLogger;
1478
+ /** Where `--list` writes. Defaults to `process.stdout`. */
1479
+ stdout?: { write(s: string): unknown };
1480
+ /**
1481
+ * Called with the run's exit code instead of exiting the process.
1482
+ * Tests supply one; production omits it and the command sets
1483
+ * `process.exitCode`.
1484
+ */
1485
+ onExit?: (code: number, error?: CliError) => void;
1486
+ }
1487
+
1488
+ /**
1489
+ * Mounts the kit-owned `serve` command on `program`.
1490
+ *
1491
+ * With no positional argument it is the supervisor over every
1492
+ * configured and enabled service; with exactly one it is the selector,
1493
+ * which overrides aggregate enablement. Two or more is a usage error
1494
+ * at exit 2 — the arity refusal is owned here rather than left to
1495
+ * commander, whose own excess-argument error exits 1.
1496
+ *
1497
+ * The inspection form is the `--list` flag, not a `list` child:
1498
+ * `list` is reserved selector vocabulary, so a `serve list` child
1499
+ * would be indistinguishable from the selector form naming a service
1500
+ * called `list`.
1501
+ */
1502
+ export function registerServe(
1503
+ program: Command,
1504
+ opts: RegisterServeOptions,
1505
+ ): Command {
1506
+ const collect = (v: string, prev: string[]): string[] => prev.concat([v]);
1507
+ const cmd = program
1508
+ .command('serve [service...]')
1509
+ .description('Run configured services under one lifecycle')
1510
+ .option('--list', 'List registered services and their state')
1511
+ .option(
1512
+ '--enable <name>',
1513
+ 'Enable a service for this run (repeatable, supervisor form only)',
1514
+ collect, [],
1515
+ )
1516
+ .option(
1517
+ '--disable <name>',
1518
+ 'Disable a service for this run (repeatable, supervisor form only)',
1519
+ collect, [],
1520
+ )
1521
+ .option('--ready-timeout <duration>', 'Per-service budget from start to ready (default 30s)')
1522
+ .option('--stop-timeout <duration>', 'Per-service budget for one stop (default 30s)')
1523
+ .option('--shutdown-timeout <duration>', 'Total shutdown budget across all services (default 60s)')
1524
+ .action(async (services: string[], flags: ServeFlags) => {
1525
+ if (flags.list) {
1526
+ runList(opts);
1527
+ return;
1528
+ }
1529
+ await runServe(services ?? [], flags, opts);
1530
+ });
1531
+ return cmd;
1532
+ }
1533
+
1534
+ /** The parsed `serve` flags, as commander hands them to the action. */
1535
+ interface ServeFlags {
1536
+ list?: boolean;
1537
+ enable?: string[];
1538
+ disable?: string[];
1539
+ readyTimeout?: string;
1540
+ stopTimeout?: string;
1541
+ shutdownTimeout?: string;
1542
+ }
1543
+
1544
+ /**
1545
+ * Prints the registered services with their configured, enabled, and
1546
+ * ready state, in registration order so the listing mirrors the
1547
+ * adopter's wiring.
1548
+ *
1549
+ * The columns are not contract — a port renders them through its own
1550
+ * output layer — but the ordering is.
1551
+ */
1552
+ function runList(opts: RegisterServeOptions): void {
1553
+ const w = opts.stdout ?? process.stdout;
1554
+ const configs = opts.configs ?? {};
1555
+ w.write('SERVICE CONFIGURED ENABLED READY\n');
1556
+ for (const svc of opts.registry.list()) {
1557
+ const cfg = configs[svc.name];
1558
+ const configured = cfg !== undefined;
1559
+ const enabled = cfg?.enabled === true;
1560
+ w.write(
1561
+ `${svc.name.padEnd(20)} ${String(configured).padEnd(11)} ` +
1562
+ `${String(enabled).padEnd(8)} ${String(svc.ready())}\n`,
1563
+ );
1564
+ }
1565
+ }
1566
+
1567
+ /** Resolves the invocation and runs the resulting set. */
1568
+ async function runServe(
1569
+ args: readonly string[],
1570
+ flags: ServeFlags,
1571
+ opts: RegisterServeOptions,
1572
+ ): Promise<void> {
1573
+ const enable = flags.enable ?? [];
1574
+ const disable = flags.disable ?? [];
1575
+ if (args.length === 1 && (enable.length > 0 || disable.length > 0)) {
1576
+ // Under the selector form the override rule already decides
1577
+ // enablement; accepting the flags too would let one invocation
1578
+ // say two contradictory things.
1579
+ report(opts, exitCodeFor('invalid-selection'), usageError(
1580
+ '--enable/--disable apply to the supervisor form; drop the service name or drop the flags',
1581
+ ));
1582
+ return;
1583
+ }
1584
+
1585
+ const durations: Partial<Record<'readyTimeout' | 'stopTimeout' | 'shutdownTimeout', number>> = {};
1586
+ for (const [key, flag] of [
1587
+ ['readyTimeout', '--ready-timeout'],
1588
+ ['stopTimeout', '--stop-timeout'],
1589
+ ['shutdownTimeout', '--shutdown-timeout'],
1590
+ ] as const) {
1591
+ const raw = flags[key];
1592
+ if (raw === undefined) continue;
1593
+ const ms = parseDurationMs(raw);
1594
+ if (ms === null) {
1595
+ report(opts, exitCodeFor('config-invalid'), usageError(`${flag}: invalid duration "${raw}"`));
1596
+ return;
1597
+ }
1598
+ durations[key] = ms;
1599
+ }
1600
+
1601
+ const configs = applyTimeoutOverrides(
1602
+ applyEnableDisable(opts.configs ?? {}, enable, disable),
1603
+ durations.readyTimeout,
1604
+ durations.stopTimeout,
1605
+ );
1606
+ const config: SupervisorConfig = {
1607
+ ...opts.config,
1608
+ ...(durations.shutdownTimeout !== undefined
1609
+ ? { shutdownTimeoutMs: durations.shutdownTimeout }
1610
+ : {}),
1611
+ };
1612
+
1613
+ const outcome = resolve(opts.registry, {
1614
+ args,
1615
+ configs,
1616
+ policy: opts.policy,
1617
+ });
1618
+
1619
+ if (outcome.error) {
1620
+ report(opts, exitCodeFor(outcome.outcome ?? 'config-invalid'), outcome.error);
1621
+ return;
1622
+ }
1623
+
1624
+ // The supervisor owns the signals from here: the first begins the
1625
+ // drain, a second aborts it.
1626
+ const sig = signalController();
1627
+ try {
1628
+ const sup = new Supervisor(opts.registry, {
1629
+ config,
1630
+ publisher: opts.publisher,
1631
+ logger: opts.logger,
1632
+ escalate: sig.escalate,
1633
+ });
1634
+ const res = await sup.run(sig.signal, outcome.selected, configs);
1635
+ report(opts, res.exitCode, res.error);
1636
+ } finally {
1637
+ sig.stop();
1638
+ }
1639
+ }
1640
+
1641
+ function report(
1642
+ opts: RegisterServeOptions,
1643
+ code: number,
1644
+ error?: CliError,
1645
+ ): void {
1646
+ if (opts.onExit) {
1647
+ opts.onExit(code, error);
1648
+ return;
1649
+ }
1650
+ if (error) {
1651
+ process.stderr.write(
1652
+ error.code ? `${error.code}: ${error.message}\n` : `${error.message}\n`,
1653
+ );
1654
+ if (error.suggested_fix) process.stderr.write(`Fix: ${error.suggested_fix}\n`);
1655
+ }
1656
+ process.exitCode = code;
1657
+ }
1658
+
1659
+ /**
1660
+ * Re-exported so a caller can branch on a transient failure without
1661
+ * importing `output/error` separately. A serve failure wrapping a kit
1662
+ * transient error propagates exit 6 unchanged, so agents and retry
1663
+ * wrappers keep their existing branch.
1664
+ */
1665
+ export { CODE_TRANSIENT };