@mark1russell7/service 0.8.20 → 0.9.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.
@@ -35,7 +35,11 @@ export interface HeartbeatOptions {
35
35
  * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.
36
36
  */
37
37
  readonly turn?: (() => Promise<void>) | undefined;
38
- /** This clock gives the ticks and the timeouts. The default is `realClock`. */
38
+ /**
39
+ * This clock gives the ticks and the timeouts. The default is `realClock`, and its timers keep a
40
+ * Node process alive until `stop()`. A heartbeat only watches a connection, and the connection
41
+ * decides if the process stays alive. Thus the owner of a connection gives `unrefClock(clock)`.
42
+ */
39
43
  readonly clock?: Clock | undefined;
40
44
  }
41
45
  /** A heartbeat is a loop of pings that runs until `stop()`. */
@@ -1 +1 @@
1
- {"version":3,"file":"heartbeat.js","names":[],"sources":["../src/heartbeat.ts"],"sourcesContent":["// @mark1russell7/service/heartbeat: a heartbeat on a clock, with no other part of the package. A\n// ping starts each interval, each ping has a timeout, and a count of misses in sequence finds a\n// dead peer. The entry imports no `node:` module and no zod. Thus a client in a browser can use it.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a heartbeat. Each time is in milliseconds on the clock. */\nexport interface HeartbeatOptions {\n /**\n * This time is the interval of the ticks, from the start of one tick to the start of the next.\n * A time that is not finite starts no tick.\n */\n readonly interval: number;\n /** This time bounds each ping. A time that is not finite gives a ping without a timeout. */\n readonly timeout: number;\n /** This count is the number of misses in sequence that make the peer dead. It is a whole number above zero. */\n readonly misses: number;\n /**\n * This function sends one ping. The signal aborts at the timeout of the ping and at `stop()`.\n * - A promise gives the answer: true when the peer answered, and false when it did not.\n * - No value tells that the answer comes later through `answer()`, for example as a pong message.\n * - A throw or a rejection is a miss.\n */\n readonly ping: (signal: AbortSignal) => Promise<boolean> | void;\n /** This function receives the death of the peer: the last of `misses` misses in sequence. The count of misses is then zero again. */\n readonly onDead: () => void;\n /** This function receives each miss, with the count of misses in sequence. */\n readonly onMiss?: ((misses: number) => void) | undefined;\n /**\n * This function operates at each tick, before the ping. The tick sends a ping only when it gives\n * true. A client can also act at the tick, for example to connect again. Without it, each tick sends a ping.\n */\n readonly due?: (() => boolean) | undefined;\n /** This function tells if a miss counts. A miss does not count while it gives false. Without it, each miss counts. */\n readonly live?: (() => boolean) | undefined;\n /** True lets a tick send a ping while an earlier ping waits for its answer. The default is false: one ping at a time. */\n readonly overlap?: boolean | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts an\n * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n /** This clock gives the ticks and the timeouts. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n}\n\n/** A heartbeat is a loop of pings that runs until `stop()`. */\nexport interface Heartbeat {\n /** This method tells the heartbeat that the peer answered. Each ping that waits gets its answer, and the count of misses is zero. */\n answer(): void;\n /** This method stops the ticks and the timeouts, and it aborts each ping that waits. A second use does nothing. */\n stop(): void;\n /** This count is the number of misses in the current sequence. */\n readonly misses: number;\n /** This count is the number of pings that wait for their answer. */\n readonly waiting: number;\n readonly stopped: boolean;\n}\n\ninterface Waiting {\n readonly settle: (answered: boolean) => void;\n readonly controller: AbortController;\n timer: Cancel | null;\n}\n\n/**\n * This function starts a heartbeat. The first tick comes one interval after the start. Each tick\n * starts the next one first, thus the ticks keep their interval while a ping waits. A ping that has\n * no answer at its timeout is a miss. The last miss of `misses` in sequence starts `onDead`.\n */\nexport const heartbeat = (options: HeartbeatOptions): Heartbeat => {\n const { interval, timeout, misses: limit, clock = realClock } = options;\n if (!Number.isInteger(limit) || limit < 1)\n throw new RangeError(`a heartbeat needs a count of misses that is a whole number above zero, not ${limit}`);\n let misses = 0;\n let stopped = false;\n let next: Cancel | null = null;\n const pings = new Set<Waiting>();\n\n const count = (answered: boolean): void => {\n if (stopped) return;\n if (answered) {\n misses = 0;\n return;\n }\n if (options.live !== undefined && !options.live()) return;\n misses += 1;\n options.onMiss?.(misses);\n if (misses >= limit) {\n misses = 0;\n options.onDead();\n }\n };\n\n const send = (): void => {\n const controller = new AbortController();\n const entry: Waiting = {\n controller,\n timer: null,\n settle: (answered) => {\n if (!pings.delete(entry)) return;\n entry.timer?.();\n const done = (): void => count(answered);\n if (options.turn === undefined) done();\n else void options.turn().then(done, done);\n },\n };\n pings.add(entry);\n if (Number.isFinite(timeout))\n entry.timer = clock.after(timeout, () => {\n entry.settle(false);\n controller.abort();\n });\n let result: Promise<boolean> | void;\n try {\n result = options.ping(controller.signal);\n } catch {\n entry.settle(false);\n return;\n }\n if (result !== undefined)\n result.then(\n (answered) => entry.settle(answered === true),\n () => entry.settle(false),\n );\n };\n\n const tick = (): void => {\n next = clock.after(interval, tick);\n if (options.due !== undefined && !options.due()) return;\n if (stopped || (options.overlap !== true && pings.size > 0)) return;\n send();\n };\n if (Number.isFinite(interval)) next = clock.after(interval, tick);\n\n return {\n answer() {\n if (stopped) return;\n misses = 0;\n for (const entry of [...pings]) entry.settle(true);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n next?.();\n next = null;\n for (const entry of [...pings]) {\n pings.delete(entry);\n entry.timer?.();\n entry.controller.abort();\n }\n },\n get misses() {\n return misses;\n },\n get waiting() {\n return pings.size;\n },\n get stopped() {\n return stopped;\n },\n };\n};\n\n/**\n * This function gives the most time that a heartbeat takes to find a silent peer, in milliseconds.\n * The first ping without an answer starts one interval after the silence at the latest. The last\n * of `misses` pings then fails at its timeout: `misses` intervals plus a timeout. An interval that\n * is not finite gives infinity.\n *\n * The time holds when each tick sends a ping: with `overlap`, or with a timeout below the interval.\n */\nexport const detectionTime = (interval: number, timeout: number, misses: number): number =>\n Number.isFinite(interval) ? misses * interval + timeout : Number.POSITIVE_INFINITY;\n"],"mappings":";;;;;;;AAuEA,MAAa,aAAa,YAAyC;CACjE,MAAM,EAAE,UAAU,SAAS,QAAQ,O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Y,QAAQ,YAAY,QAAQ,MAAM,OAAO,GAAI;EAC7D,KAAK;CACP;CACA,IAAI,OAAO,SAAS,QAAQ,GAAG,OAAO,MAAM,MAAM,UAAU,IAAI;CAEhE,OAAO;EACL,SAAS;GACP,IAAI,SAAS;GACb,SAAS;GACT,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,GAAG,MAAM,OAAO,IAAI;EACnD;EACA,OAAO;GACL,IAAI,SAAS;GACb,UAAU;GACV,OAAO;GACP,OAAO;GACP,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,GAAG;IAC9B,MAAM,OAAO,KAAK;IAClB,MAAM,QAAQ;IACd,MAAM,WAAW,MAAM;GACzB;EACF;EACA,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,MAAM;EACf;EACA,IAAI,UAAU;GACZ,OAAO;EACT;CACF;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,UAAkB,SAAiB,WAC/D,OAAO,SAAS,QAAQ,IAAI,SAAS,WAAW,UAAU,OAAO"}
1
+ {"version":3,"file":"heartbeat.js","names":[],"sources":["../src/heartbeat.ts"],"sourcesContent":["// @mark1russell7/service/heartbeat: a heartbeat on a clock, with no other part of the package. A\n// ping starts each interval, each ping has a timeout, and a count of misses in sequence finds a\n// dead peer. The entry imports no `node:` module and no zod. Thus a client in a browser can use it.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a heartbeat. Each time is in milliseconds on the clock. */\nexport interface HeartbeatOptions {\n /**\n * This time is the interval of the ticks, from the start of one tick to the start of the next.\n * A time that is not finite starts no tick.\n */\n readonly interval: number;\n /** This time bounds each ping. A time that is not finite gives a ping without a timeout. */\n readonly timeout: number;\n /** This count is the number of misses in sequence that make the peer dead. It is a whole number above zero. */\n readonly misses: number;\n /**\n * This function sends one ping. The signal aborts at the timeout of the ping and at `stop()`.\n * - A promise gives the answer: true when the peer answered, and false when it did not.\n * - No value tells that the answer comes later through `answer()`, for example as a pong message.\n * - A throw or a rejection is a miss.\n */\n readonly ping: (signal: AbortSignal) => Promise<boolean> | void;\n /** This function receives the death of the peer: the last of `misses` misses in sequence. The count of misses is then zero again. */\n readonly onDead: () => void;\n /** This function receives each miss, with the count of misses in sequence. */\n readonly onMiss?: ((misses: number) => void) | undefined;\n /**\n * This function operates at each tick, before the ping. The tick sends a ping only when it gives\n * true. A client can also act at the tick, for example to connect again. Without it, each tick sends a ping.\n */\n readonly due?: (() => boolean) | undefined;\n /** This function tells if a miss counts. A miss does not count while it gives false. Without it, each miss counts. */\n readonly live?: (() => boolean) | undefined;\n /** True lets a tick send a ping while an earlier ping waits for its answer. The default is false: one ping at a time. */\n readonly overlap?: boolean | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts an\n * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n /**\n * This clock gives the ticks and the timeouts. The default is `realClock`, and its timers keep a\n * Node process alive until `stop()`. A heartbeat only watches a connection, and the connection\n * decides if the process stays alive. Thus the owner of a connection gives `unrefClock(clock)`.\n */\n readonly clock?: Clock | undefined;\n}\n\n/** A heartbeat is a loop of pings that runs until `stop()`. */\nexport interface Heartbeat {\n /** This method tells the heartbeat that the peer answered. Each ping that waits gets its answer, and the count of misses is zero. */\n answer(): void;\n /** This method stops the ticks and the timeouts, and it aborts each ping that waits. A second use does nothing. */\n stop(): void;\n /** This count is the number of misses in the current sequence. */\n readonly misses: number;\n /** This count is the number of pings that wait for their answer. */\n readonly waiting: number;\n readonly stopped: boolean;\n}\n\ninterface Waiting {\n readonly settle: (answered: boolean) => void;\n readonly controller: AbortController;\n timer: Cancel | null;\n}\n\n/**\n * This function starts a heartbeat. The first tick comes one interval after the start. Each tick\n * starts the next one first, thus the ticks keep their interval while a ping waits. A ping that has\n * no answer at its timeout is a miss. The last miss of `misses` in sequence starts `onDead`.\n */\nexport const heartbeat = (options: HeartbeatOptions): Heartbeat => {\n const { interval, timeout, misses: limit, clock = realClock } = options;\n if (!Number.isInteger(limit) || limit < 1)\n throw new RangeError(`a heartbeat needs a count of misses that is a whole number above zero, not ${limit}`);\n let misses = 0;\n let stopped = false;\n let next: Cancel | null = null;\n const pings = new Set<Waiting>();\n\n const count = (answered: boolean): void => {\n if (stopped) return;\n if (answered) {\n misses = 0;\n return;\n }\n if (options.live !== undefined && !options.live()) return;\n misses += 1;\n options.onMiss?.(misses);\n if (misses >= limit) {\n misses = 0;\n options.onDead();\n }\n };\n\n const send = (): void => {\n const controller = new AbortController();\n const entry: Waiting = {\n controller,\n timer: null,\n settle: (answered) => {\n if (!pings.delete(entry)) return;\n entry.timer?.();\n const done = (): void => count(answered);\n if (options.turn === undefined) done();\n else void options.turn().then(done, done);\n },\n };\n pings.add(entry);\n if (Number.isFinite(timeout))\n entry.timer = clock.after(timeout, () => {\n entry.settle(false);\n controller.abort();\n });\n let result: Promise<boolean> | void;\n try {\n result = options.ping(controller.signal);\n } catch {\n entry.settle(false);\n return;\n }\n if (result !== undefined)\n result.then(\n (answered) => entry.settle(answered === true),\n () => entry.settle(false),\n );\n };\n\n const tick = (): void => {\n next = clock.after(interval, tick);\n if (options.due !== undefined && !options.due()) return;\n if (stopped || (options.overlap !== true && pings.size > 0)) return;\n send();\n };\n if (Number.isFinite(interval)) next = clock.after(interval, tick);\n\n return {\n answer() {\n if (stopped) return;\n misses = 0;\n for (const entry of [...pings]) entry.settle(true);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n next?.();\n next = null;\n for (const entry of [...pings]) {\n pings.delete(entry);\n entry.timer?.();\n entry.controller.abort();\n }\n },\n get misses() {\n return misses;\n },\n get waiting() {\n return pings.size;\n },\n get stopped() {\n return stopped;\n },\n };\n};\n\n/**\n * This function gives the most time that a heartbeat takes to find a silent peer, in milliseconds.\n * The first ping without an answer starts one interval after the silence at the latest. The last\n * of `misses` pings then fails at its timeout: `misses` intervals plus a timeout. An interval that\n * is not finite gives infinity.\n *\n * The time holds when each tick sends a ping: with `overlap`, or with a timeout below the interval.\n */\nexport const detectionTime = (interval: number, timeout: number, misses: number): number =>\n Number.isFinite(interval) ? misses * interval + timeout : Number.POSITIVE_INFINITY;\n"],"mappings":";;;;;;;AA2EA,MAAa,aAAa,YAAyC;CACjE,MAAM,EAAE,UAAU,SAAS,QAAQ,OAAO,QAAQ,cAAc;CAChE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,8EAA8E,OAAO;CAC5G,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,OAAsB;CAC1B,MAAM,wBAAQ,IAAI,IAAa;CAE/B,MAAM,SAAS,aAA4B;EACzC,IAAI,SAAS;EACb,IAAI,UAAU;GACZ,SAAS;GACT;EACF;EACA,IAAI,QAAQ,SAAS,KAAA,KAAa,CAAC,QAAQ,KAAK,GAAG;EACnD,UAAU;EACV,QAAQ,SAAS,MAAM;EACvB,IAAI,UAAU,OAAO;GACnB,SAAS;GACT,QAAQ,OAAO;EACjB;CACF;CAEA,MAAM,aAAmB;EACvB,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,QAAiB;GACrB;GACA,OAAO;GACP,SAAS,aAAa;IACpB,IAAI,CAAC,MAAM,OAAO,KAAK,GAAG;IAC1B,MAAM,QAAQ;IACd,MAAM,aAAmB,MAAM,QAAQ;IACvC,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK;SAChC,QAAa,KAAK,CAAC,CAAC,KAAK,MAAM,IAAI;GAC1C;EACF;EACA,MAAM,IAAI,KAAK;EACf,IAAI,OAAO,SAAS,OAAO,GACzB,MAAM,QAAQ,MAAM,MAAM,eAAe;GACvC,MAAM,OAAO,KAAK;GAClB,WAAW,MAAM;EACnB,CAAC;EACH,IAAI;EACJ,IAAI;GACF,SAAS,QAAQ,KAAK,WAAW,MAAM;EACzC,QAAQ;GACN,MAAM,OAAO,KAAK;GAClB;EACF;EACA,IAAI,WAAW,KAAA,GACb,OAAO,MACJ,aAAa,MAAM,OAAO,aAAa,IAAI,SACtC,MAAM,OAAO,KAAK,CAC1B;CACJ;CAEA,MAAM,aAAmB;EACvB,OAAO,MAAM,MAAM,UAAU,IAAI;EACjC,IAAI,QAAQ,QAAQ,KAAA,KAAa,CAAC,QAAQ,IAAI,GAAG;EACjD,IAAI,WAAY,QAAQ,YAAY,QAAQ,MAAM,OAAO,GAAI;EAC7D,KAAK;CACP;CACA,IAAI,OAAO,SAAS,QAAQ,GAAG,OAAO,MAAM,MAAM,UAAU,IAAI;CAEhE,OAAO;EACL,SAAS;GACP,IAAI,SAAS;GACb,SAAS;GACT,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,GAAG,MAAM,OAAO,IAAI;EACnD;EACA,OAAO;GACL,IAAI,SAAS;GACb,UAAU;GACV,OAAO;GACP,OAAO;GACP,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,GAAG;IAC9B,MAAM,OAAO,KAAK;IAClB,MAAM,QAAQ;IACd,MAAM,WAAW,MAAM;GACzB;EACF;EACA,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,MAAM;EACf;EACA,IAAI,UAAU;GACZ,OAAO;EACT;CACF;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,UAAkB,SAAiB,WAC/D,OAAO,SAAS,QAAQ,IAAI,SAAS,WAAW,UAAU,OAAO"}
@@ -240,9 +240,13 @@ const superviseGroup = (spec, ports, options = {}) => {
240
240
  pid: child.pid
241
241
  });
242
242
  const restart = unit.spec.restart === void 0 ? DEFAULT_RESTART : unit.spec.restart;
243
- if (unit.retry !== null && restart !== null) unit.timers.push(ports.clock.after(ms(restart.resetAfter), () => {
244
- if (unit.child === child && unit.phase === "ready") unit.retry?.reset();
245
- }));
243
+ if (unit.retry !== null && restart !== null) {
244
+ const reset = ports.clock.after(ms(restart.resetAfter), () => {
245
+ if (unit.child === child && unit.phase === "ready") unit.retry?.reset();
246
+ });
247
+ reset.unref?.();
248
+ unit.timers.push(reset);
249
+ }
246
250
  if (unit.spec.alive !== void 0) watch(unit, child, unit.spec.alive);
247
251
  considerAll();
248
252
  };
@@ -255,6 +259,7 @@ const superviseGroup = (spec, ports, options = {}) => {
255
259
  unit.watch = null;
256
260
  check();
257
261
  });
262
+ unit.watch.unref?.();
258
263
  };
259
264
  const check = async () => {
260
265
  if (!current()) return;
@@ -315,7 +320,9 @@ const superviseGroup = (spec, ports, options = {}) => {
315
320
  stagedStop(unit, child);
316
321
  return;
317
322
  }
318
- unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));
323
+ const again = ports.clock.after(ms(ready.interval), () => void attempt());
324
+ again.unref?.();
325
+ unit.timers.push(again);
319
326
  };
320
327
  attempt();
321
328
  };
@@ -1 +1 @@
1
- {"version":3,"file":"group.js","names":[],"sources":["../../src/host/group.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { backoffProblems } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport type { LogFields, LogLevel } from \"../logger.ts\";\nimport type { MessageShape } from \"../process.ts\";\nimport { isMessageShape } from \"../process.ts\";\nimport type { Retrier } from \"../retrier.ts\";\nimport { retrier } from \"../retrier.ts\";\nimport { removeDiscovery, writeDiscovery } from \"./discovery.ts\";\nimport { parseEnvFile } from \"./env.ts\";\nimport type { InstanceLock } from \"./lock.ts\";\nimport { acquireInstanceLock } from \"./lock.ts\";\nimport type { LogSpec, RotatingLog } from \"./logs.ts\";\nimport { rotatingLog } from \"./logs.ts\";\nimport type { ChildHandle, HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport type { ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/** A ready spec tells how the supervisor finds that a program is ready. */\nexport interface ReadySpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This time is the most that the program can take to be ready. After it, the supervisor stops the program and starts it again. */\n readonly within: Quantity;\n}\n\n/**\n * An alive spec tells how the supervisor finds that a ready program still works. A program can hang and not exit:\n * its process stays, and only a probe finds it. After `failures` failures in sequence, the supervisor stops the\n * program in stages and starts it again after its backoff.\n */\nexport interface AliveSpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. The first use is one interval after the program is ready. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This count of failures in sequence stops the program: a whole number of 1 or more. A pass sets the count to 0. */\n readonly failures: number;\n}\n\n/** A program restart tells how the supervisor starts a program again after it stops. */\nexport interface ProgramRestart {\n /** This backoff gives the wait before each start again, in milliseconds, as `retrier` uses it. */\n readonly backoff: Backoff;\n /** This time is how long a program is ready before its count of tries goes back to 0. */\n readonly resetAfter: Quantity;\n}\n\n/** A stop spec tells how the supervisor stops a program. */\nexport interface StopSpec {\n /** This time is the wait for the staged stop, before the supervisor stops the process tree. */\n readonly grace: Quantity;\n /** This message goes on the IPC channel of a child that has one. The default is `\"shutdown\"`, which `run()` can match. */\n readonly message?: MessageShape | undefined;\n /** This signal goes to a child without an IPC channel on Linux. The default is `SIGTERM`. */\n readonly signal?: \"SIGINT\" | \"SIGTERM\" | undefined;\n}\n\n/** A program spec tells one program of a group, and what it needs before it starts. */\nexport interface ProgramSpec {\n /** This name is the name of the program in the group: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly program: string;\n readonly args?: readonly string[] | undefined;\n readonly cwd?: string | undefined;\n /** These variables go to the program. They replace the variables of the env file and of the host. */\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** This file gives variables to the program at each start (`parseEnvFile`). They replace the variables of the host. */\n readonly envFile?: string | undefined;\n /** These are the programs that must be ready before this program starts. */\n readonly after?: readonly string[] | undefined;\n /** This spec tells when the program is ready. Without it, the program is ready when it starts. */\n readonly ready?: ReadySpec | undefined;\n /** This spec tells how the supervisor finds that the ready program still works. Without it, only an exit starts the program again. */\n readonly alive?: AliveSpec | undefined;\n /** This policy starts the program again after it stops. The default is `DEFAULT_RESTART`. Null does not start it again. */\n readonly restart?: ProgramRestart | null | undefined;\n /** This spec tells the log file. The default is `<stateDir>/logs/<name>.log`, 10 MB, with 3 old files. Null keeps no log. */\n readonly log?: LogSpec | null | undefined;\n /** True gives the child an IPC channel, for the staged stop of a Node program. The default is false. */\n readonly ipc?: boolean | undefined;\n /** This spec tells the stop. The default is a grace of 10 s. */\n readonly stop?: StopSpec | undefined;\n /** These fields go in the discovery file of the program, `<stateDir>/<name>.json`. */\n readonly listen?: { readonly port?: number | null | undefined; readonly url?: string | null | undefined } | undefined;\n}\n\n/** A group spec tells a group of programs that one supervisor starts in sequence and keeps alive. */\nexport interface GroupSpec {\n readonly name: string;\n /** This folder keeps the lock, the discovery file and the log of each program. */\n readonly stateDir: string;\n readonly programs: readonly ProgramSpec[];\n}\n\n/** These options go with a supervisor. */\nexport interface GroupOptions {\n /** This function gives a number in [0, 1) for the jitter of the backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * A program phase tells where a program of a group is.\n * - `waiting`: a program that it needs is not ready.\n * - `starting`: it runs, and its probe did not pass.\n * - `ready`: it runs, and its probe passed.\n * - `backoff`: it stopped, and it starts again after its backoff.\n * - `held`: another instance holds its lock. The supervisor tries again after the backoff.\n * - `exited`: it stopped, and it has no restart.\n * - `stopping`, `stopped`: the stop of the group.\n */\nexport type ProgramPhase = \"waiting\" | \"starting\" | \"ready\" | \"backoff\" | \"held\" | \"exited\" | \"stopping\" | \"stopped\";\n\n/** A program state is the state of one program of a group, for a status. */\nexport interface ProgramState {\n readonly name: string;\n readonly phase: ProgramPhase;\n /** This number is the process ID of the child, or null. */\n readonly pid: number | null;\n /** This count is the number of starts again since the start of the group. */\n readonly restarts: number;\n /** This text tells the last problem, for example why the probe failed, or it is null. */\n readonly detail: string | null;\n}\n\n/** A group supervisor starts the programs of a group in sequence, starts each again after it stops, and stops them in stages. */\nexport interface GroupSupervisor {\n /** This method starts each program whose programs are ready. A second use does nothing. */\n start(): void;\n /** This method stops each program in the reverse sequence of the start. A second use gives the same promise. */\n stop(): Promise<void>;\n /** This method gives the state of each program, in the sequence of the spec. */\n states(): readonly ProgramState[];\n}\n\n/**\n * This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.\n * The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.\n */\nexport const DEFAULT_RESTART: ProgramRestart = {\n backoff: { base: 1000, factor: 2, cap: 60_000, jitter: { kind: \"subtract\", fraction: 0.5 } },\n resetAfter: { value: 60, unit: \"s\" },\n};\n\nconst DEFAULT_GRACE: Quantity = { value: 10, unit: \"s\" };\nconst DEFAULT_LOG_SIZE: Quantity = { value: 10, unit: \"MB\" };\nconst DEFAULT_LOG_KEEP = 3;\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nconst ms = (time: Quantity): number => valueIn(time, \"ms\");\n\n/**\n * This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the\n * layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.\n */\nexport const startOrder = (spec: GroupSpec): string[][] => {\n const names = new Set(spec.programs.map((program) => program.name));\n const placed = new Set<string>();\n const layers: string[][] = [];\n for (;;) {\n const layer = spec.programs\n .filter((program) => !placed.has(program.name))\n .filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name)))\n .map((program) => program.name);\n if (layer.length === 0) return layers;\n for (const name of layer) placed.add(name);\n layers.push([...new Set(layer)]);\n }\n};\n\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean =>\n isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\n\n/** This function gives the problems of a group spec: each value that the supervisor cannot use. */\nexport const groupProblems = (spec: GroupSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (spec.programs.length === 0) problems.push(\"the group has no programs\");\n const seen = new Set<string>();\n const names = new Set(spec.programs.map((program) => program.name));\n for (const program of spec.programs) {\n const name = program.name;\n const of = `the program ${JSON.stringify(name)}`;\n if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, \".\", \"_\" and \"-\"`);\n if (seen.has(name)) problems.push(`${of} comes two times`);\n seen.add(name);\n if (program.program === \"\") problems.push(`${of}: the program is empty`);\n for (const need of program.after ?? []) {\n if (need === name) problems.push(`${of} is after itself`);\n else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);\n }\n if (program.ready !== undefined) {\n problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));\n for (const field of [\"interval\", \"timeout\", \"within\"] as const)\n if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);\n }\n if (program.alive !== undefined) {\n problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));\n for (const field of [\"interval\", \"timeout\"] as const)\n if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);\n if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1))\n problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);\n }\n if (program.restart !== undefined && program.restart !== null) {\n problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);\n }\n if (program.log !== undefined && program.log !== null) {\n const size = program.log.maxSize;\n if (!(isQuantity(size) && convertible(size.unit, \"B\") && valueIn(size, \"B\") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);\n if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);\n if (program.log.path === \"\") problems.push(`${of}: the path of the log is empty`);\n }\n if (program.stop !== undefined) {\n if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);\n if (program.stop.message !== undefined && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);\n const signal = program.stop.signal;\n if (signal !== undefined && signal !== \"SIGINT\" && signal !== \"SIGTERM\") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);\n }\n const port = program.listen?.port;\n if (port !== undefined && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65_535))\n problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);\n }\n const placed = new Set(startOrder(spec).flat());\n const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));\n if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(\", \")} are in a cycle of \"after\", or after a program in one`);\n return problems;\n};\n\n/** The supervisor keeps one unit for each program: its spec, its files and its state. */\ninterface Unit {\n readonly spec: ProgramSpec;\n readonly lockPath: string;\n readonly discoveryPath: string;\n readonly log: RotatingLog | null;\n readonly retry: Retrier | null;\n phase: ProgramPhase;\n child: ChildHandle | null;\n lock: InstanceLock | null;\n timers: Cancel[];\n /** This cancel stops the next use of the liveness probe. It is one timer, thus a long life adds no timers. */\n watch: Cancel | null;\n restarts: number;\n detail: string | null;\n /** This text tells why the supervisor stopped the child, or it is null. */\n reason: string | null;\n waiters: Array<() => void>;\n}\n\n/**\n * This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes\n * through the ports, thus a test gives `fakeHost()` and starts no process.\n * - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.\n * - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.\n * - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.\n * - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.\n * - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.\n */\nexport const superviseGroup = (spec: GroupSpec, ports: HostPorts, options: GroupOptions = {}): GroupSupervisor => {\n const problems = groupProblems(spec);\n if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join(\"; \")}`);\n const abort = new AbortController();\n const layers = startOrder(spec);\n let started = false;\n let stopping = false;\n let stopped: Promise<void> | null = null;\n\n const say = (level: LogLevel, message: string, fields: LogFields): void => {\n try {\n ports.logger?.log(level, message, { group: spec.name, ...fields });\n } catch {\n // the supervisor does not depend on its logger\n }\n };\n\n const units = new Map<string, Unit>();\n for (const program of spec.programs) {\n const restart = program.restart === undefined ? DEFAULT_RESTART : program.restart;\n const logSpec =\n program.log === undefined\n ? { path: joinPath(ports.platform, spec.stateDir, \"logs\", `${program.name}.log`), maxSize: DEFAULT_LOG_SIZE, keep: DEFAULT_LOG_KEEP }\n : program.log;\n units.set(program.name, {\n spec: program,\n lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),\n discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),\n log: logSpec === null ? null : rotatingLog(logSpec, ports.files),\n retry:\n restart === null\n ? null\n : retrier({ ...restart.backoff, clock: ports.clock, signal: abort.signal, ...(options.random === undefined ? {} : { random: options.random }) }),\n phase: \"waiting\",\n child: null,\n lock: null,\n timers: [],\n watch: null,\n restarts: 0,\n detail: null,\n reason: null,\n waiters: [],\n });\n }\n const unitOf = (name: string): Unit => units.get(name)!;\n\n const clearTimers = (unit: Unit): void => {\n for (const cancel of unit.timers.splice(0)) cancel();\n unit.watch?.();\n unit.watch = null;\n };\n\n const environment = async (unit: Unit): Promise<Record<string, string>> => {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(ports.env)) if (value !== undefined) env[key] = value;\n const file = unit.spec.envFile;\n if (file !== undefined) {\n try {\n const text = await ports.files.read(file);\n if (text === null) say(\"warn\", `the env file ${file} of ${unit.spec.name} does not exist`, { program: unit.spec.name, file });\n else {\n const parsed = parseEnvFile(text);\n Object.assign(env, parsed.env);\n for (const problem of parsed.problems) say(\"warn\", `the env file ${file} of ${unit.spec.name}: ${problem}`, { program: unit.spec.name, file });\n }\n } catch (error) {\n say(\"warn\", `the read of the env file ${file} of ${unit.spec.name} failed`, { program: unit.spec.name, file, error });\n }\n }\n return Object.assign(env, unit.spec.env ?? {});\n };\n\n const consider = (unit: Unit): void => {\n if (!started || stopping || unit.phase !== \"waiting\") return;\n if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === \"ready\")) return;\n void launch(unit);\n };\n const considerAll = (): void => {\n for (const layer of layers) for (const name of layer) consider(unitOf(name));\n };\n\n /** This function starts the program again after the backoff, or ends it when it has no restart. */\n const later = (unit: Unit, phase: \"backoff\" | \"held\"): void => {\n const delay = unit.retry?.schedule(() => {\n if (stopping) return;\n unit.phase = \"waiting\";\n unit.restarts += 1;\n consider(unit);\n });\n if (delay === undefined || delay === null) {\n unit.phase = phase === \"held\" ? \"held\" : \"exited\";\n void unit.lock?.release();\n unit.lock = null;\n return;\n }\n unit.phase = phase;\n say(\"info\", `${unit.spec.name} starts again in ${delay} ms`, { program: unit.spec.name, delay: { value: delay, unit: \"ms\" }, attempt: unit.retry?.attempts });\n };\n\n const markReady = (unit: Unit, child: ChildHandle): void => {\n if (unit.child !== child || stopping) return;\n unit.phase = \"ready\";\n unit.detail = null;\n say(\"info\", `${unit.spec.name} is ready`, { program: unit.spec.name, pid: child.pid });\n const restart = unit.spec.restart === undefined ? DEFAULT_RESTART : unit.spec.restart;\n if (unit.retry !== null && restart !== null)\n unit.timers.push(\n ports.clock.after(ms(restart.resetAfter), () => {\n if (unit.child === child && unit.phase === \"ready\") unit.retry?.reset();\n }),\n );\n if (unit.spec.alive !== undefined) watch(unit, child, unit.spec.alive);\n considerAll();\n };\n\n /** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */\n const watch = (unit: Unit, child: ChildHandle, alive: AliveSpec): void => {\n let failures = 0;\n const current = (): boolean => unit.child === child && unit.phase === \"ready\" && !stopping;\n const next = (): void => {\n unit.watch = ports.clock.after(ms(alive.interval), () => {\n unit.watch = null;\n void check();\n });\n };\n const check = async (): Promise<void> => {\n if (!current()) return;\n const result = await probeOnce(alive.probe, ms(alive.timeout), ports);\n if (!current()) return;\n if (result.ok) {\n if (failures > 0) say(\"info\", `${unit.spec.name} is alive again`, { program: unit.spec.name, pid: child.pid, failures });\n failures = 0;\n unit.detail = null;\n next();\n return;\n }\n failures += 1;\n unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;\n if (failures < alive.failures) {\n say(\"warn\", `${unit.spec.name}: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, why: result.why });\n next();\n return;\n }\n unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not alive, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n };\n next();\n };\n\n const probe = (unit: Unit, child: ChildHandle, ready: ReadySpec): void => {\n const deadline = ports.clock.now() + ms(ready.within);\n const attempt = async (): Promise<void> => {\n if (unit.child !== child || stopping) return;\n const result = await probeOnce(ready.probe, ms(ready.timeout), ports);\n if (unit.child !== child || stopping) return;\n if (result.ok) {\n markReady(unit, child);\n return;\n }\n unit.detail = result.why;\n if (ports.clock.now() >= deadline) {\n unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not ready in its time, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n return;\n }\n unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));\n };\n void attempt();\n };\n\n const exited = (unit: Unit, child: ChildHandle, code: number | null, signal: string | null): void => {\n if (unit.child !== child) return;\n clearTimers(unit);\n unit.child = null;\n for (const waiter of unit.waiters.splice(0)) waiter();\n if (child.pid !== null) void removeDiscovery(unit.discoveryPath, ports, child.pid);\n void unit.lock?.update(null).catch(() => {});\n if (stopping || unit.phase === \"stopping\") {\n unit.phase = \"stopped\";\n return;\n }\n const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? \"unknown\"}` : `the code ${code}`}`;\n unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;\n unit.reason = null;\n say(\"warn\", `${unit.spec.name} stopped: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, code, signal });\n later(unit, \"backoff\");\n };\n\n const launch = async (unit: Unit): Promise<void> => {\n unit.phase = \"starting\";\n unit.detail = null;\n const name = unit.spec.name;\n if (unit.lock === null) {\n const taken = await acquireInstanceLock(unit.lockPath, ports);\n if (stopping) {\n if (taken.kind === \"acquired\") await taken.lock.release();\n return;\n }\n if (taken.kind !== \"acquired\") {\n unit.detail = taken.kind === \"held\" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;\n say(\"warn\", `${name} does not start: ${unit.detail}`, { program: name, lock: unit.lockPath });\n later(unit, \"held\");\n return;\n }\n unit.lock = taken.lock;\n }\n const lock = unit.lock;\n const env = await environment(unit);\n if (stopping) {\n await lock.release();\n unit.lock = null;\n return;\n }\n const child = ports.processes.spawn({ program: unit.spec.program, args: unit.spec.args ?? [], cwd: unit.spec.cwd, env, ipc: unit.spec.ipc ?? false });\n const startedAt = ports.wall();\n unit.child = child;\n child.onOutput((_stream, chunk) => unit.log?.write(chunk));\n child.onExit((code, signal) => exited(unit, child, code, signal));\n const pid = child.pid;\n if (pid === null) return;\n say(\"info\", `${name} started`, { program: name, pid });\n const mark = { pid, startedAt };\n try {\n await lock.update(mark);\n await writeDiscovery(\n unit.discoveryPath,\n { pid, startedAt: new Date(startedAt).toISOString(), port: unit.spec.listen?.port ?? null, url: unit.spec.listen?.url ?? null, extra: { group: spec.name, program: name } },\n ports,\n );\n } catch (error) {\n say(\"warn\", `the files of ${name} were not written`, { program: name, error });\n }\n // a child that ended during the writes leaves no discovery file\n if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);\n if (unit.child !== child || stopping) return;\n if (unit.spec.ready === undefined) markReady(unit, child);\n else probe(unit, child, unit.spec.ready);\n };\n\n /** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */\n const ended = (unit: Unit, child: ChildHandle, wait: number): Promise<boolean> =>\n new Promise((resolve) => {\n if (unit.child !== child) {\n resolve(true);\n return;\n }\n const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));\n unit.waiters.push(() => {\n cancel();\n resolve(true);\n });\n });\n\n /**\n * This function stops a child in stages. The message goes on its IPC channel when it has one. Else\n * Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.\n */\n const stagedStop = async (unit: Unit, child: ChildHandle): Promise<void> => {\n const pid = child.pid;\n if (pid === null || unit.child !== child) return;\n const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);\n const gone = ended(unit, child, grace);\n let asked: string | null = null;\n if (child.ipc && child.send(unit.spec.stop?.message ?? \"shutdown\")) asked = \"the IPC message\";\n else if (ports.platform === \"win32\") {\n const result = await ports.commands.run(\"taskkill\", [\"/T\", \"/PID\", String(pid)]).catch(() => null);\n if (result?.code === 0) asked = \"taskkill\";\n } else {\n const signal = unit.spec.stop?.signal ?? \"SIGTERM\";\n if (ports.processes.signal(pid, signal)) asked = signal;\n }\n say(\"info\", `${unit.spec.name} stops${asked === null ? \"\" : ` through ${asked}`}`, { program: unit.spec.name, pid, grace: { value: grace, unit: \"ms\" } });\n if (asked !== null && (await gone)) return;\n const tree = await stopTree(pid, ports);\n const why = asked === null ? \"the staged stop did not go\" : \"it did not stop in its grace\";\n say(tree.kind === \"failed\" ? \"error\" : \"warn\", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {\n program: unit.spec.name,\n pid,\n outcome: tree.kind,\n });\n if (!(await ended(unit, child, grace))) say(\"error\", `${unit.spec.name} did not end after the stop of its process tree`, { program: unit.spec.name, pid });\n };\n\n const stopUnit = async (unit: Unit): Promise<void> => {\n clearTimers(unit);\n const child = unit.child;\n const pid = child?.pid ?? null;\n if (child !== null && pid !== null) {\n unit.phase = \"stopping\";\n await stagedStop(unit, child);\n await removeDiscovery(unit.discoveryPath, ports, pid);\n }\n unit.phase = \"stopped\";\n await unit.lock?.release();\n unit.lock = null;\n };\n\n return {\n start() {\n if (started || stopping) return;\n started = true;\n say(\"info\", `the group ${spec.name} starts`, { layers });\n considerAll();\n },\n stop() {\n if (stopped !== null) return stopped;\n stopping = true;\n abort.abort();\n stopped = (async () => {\n for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));\n await Promise.all([...units.values()].map((unit) => unit.log?.flush()));\n say(\"info\", `the group ${spec.name} stopped`, {});\n })();\n return stopped;\n },\n states() {\n return spec.programs.map((program) => {\n const unit = unitOf(program.name);\n return { name: program.name, phase: unit.phase, pid: unit.child?.pid ?? null, restarts: unit.restarts, detail: unit.detail };\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAoJA,MAAa,kBAAkC;CAC7C,SAAS;EAAE,MAAM;EAAM,QAAQ;EAAG,KAAK;EAAQ,QAAQ;GAAE,MAAM;GAAY,UAAU;EAAI;CAAE;CAC3F,YAAY;EAAE,OAAO;EAAI,MAAM;CAAI;AACrC;AAEA,MAAM,gBAA0B;CAAE,OAAO;CAAI,MAAM;AAAI;AACvD,MAAM,mBAA6B;CAAE,OAAO;CAAI,MAAM;AAAK;AAC3D,MAAM,mBAAmB;AACzB,MAAM,OAAO;AAEb,MAAM,MAAM,SAA2B,QAAQ,MAAM,IAAI;;;;;AAMzD,MAAa,cAAc,SAAgC;CACzD,MAAM,QA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QAAQ,QAAQ,MAAM;GAClC,KAAK,QAAQ;GACb,MAAM,WAAW,MAAM,KAAK;GAC5B,MAAM,gBAAgB,KAAK,eAAe,OAAO,GAAG;EACtD;EACA,KAAK,QAAQ;EACb,MAAM,KAAK,MAAM,QAAQ;EACzB,KAAK,OAAO;CACd;CAEA,OAAO;EACL,QAAQ;GACN,IAAI,WAAW,UAAU;GACzB,UAAU;GACV,IAAI,QAAQ,aAAa,KAAK,KAAK,UAAU,EAAE,OAAO,CAAC;GACvD,YAAY;EACd;EACA,OAAO;GACL,IAAI,YAAY,MAAM,OAAO;GAC7B,WAAW;GACX,MAAM,MAAM;GACZ,WAAW,YAAY;IACrB,KAAK,MAAM,SAAS,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,GAAG,MAAM,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,OAAO,IAAI,CAAC,CAAC,CAAC;IACxG,MAAM,QAAQ,IAAI,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,MAAM,CAAC,CAAC;IACtE,IAAI,QAAQ,aAAa,KAAK,KAAK,WAAW,CAAC,CAAC;GAClD,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,KAAK,SAAS,KAAK,YAAY;IACpC,MAAM,OAAO,OAAO,QAAQ,IAAI;IAChC,OAAO;KAAE,MAAM,QAAQ;KAAM,OAAO,KAAK;KAAO,KAAK,KAAK,OAAO,OAAO;KAAM,UAAU,KAAK;KAAU,QAAQ,KAAK;IAAO;GAC7H,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"group.js","names":[],"sources":["../../src/host/group.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { backoffProblems } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport type { LogFields, LogLevel } from \"../logger.ts\";\nimport type { MessageShape } from \"../process.ts\";\nimport { isMessageShape } from \"../process.ts\";\nimport type { Retrier } from \"../retrier.ts\";\nimport { retrier } from \"../retrier.ts\";\nimport { removeDiscovery, writeDiscovery } from \"./discovery.ts\";\nimport { parseEnvFile } from \"./env.ts\";\nimport type { InstanceLock } from \"./lock.ts\";\nimport { acquireInstanceLock } from \"./lock.ts\";\nimport type { LogSpec, RotatingLog } from \"./logs.ts\";\nimport { rotatingLog } from \"./logs.ts\";\nimport type { ChildHandle, HostPorts } from \"./ports.ts\";\nimport { joinPath } from \"./ports.ts\";\nimport type { ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { stopTree } from \"./processes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/** A ready spec tells how the supervisor finds that a program is ready. */\nexport interface ReadySpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This time is the most that the program can take to be ready. After it, the supervisor stops the program and starts it again. */\n readonly within: Quantity;\n}\n\n/**\n * An alive spec tells how the supervisor finds that a ready program still works. A program can hang and not exit:\n * its process stays, and only a probe finds it. After `failures` failures in sequence, the supervisor stops the\n * program in stages and starts it again after its backoff.\n */\nexport interface AliveSpec {\n readonly probe: ReadyProbe;\n /** This time is the pause between two uses of the probe. The first use is one interval after the program is ready. */\n readonly interval: Quantity;\n /** This time is the most that one use of the probe can take. */\n readonly timeout: Quantity;\n /** This count of failures in sequence stops the program: a whole number of 1 or more. A pass sets the count to 0. */\n readonly failures: number;\n}\n\n/** A program restart tells how the supervisor starts a program again after it stops. */\nexport interface ProgramRestart {\n /** This backoff gives the wait before each start again, in milliseconds, as `retrier` uses it. */\n readonly backoff: Backoff;\n /** This time is how long a program is ready before its count of tries goes back to 0. */\n readonly resetAfter: Quantity;\n}\n\n/** A stop spec tells how the supervisor stops a program. */\nexport interface StopSpec {\n /** This time is the wait for the staged stop, before the supervisor stops the process tree. */\n readonly grace: Quantity;\n /** This message goes on the IPC channel of a child that has one. The default is `\"shutdown\"`, which `run()` can match. */\n readonly message?: MessageShape | undefined;\n /** This signal goes to a child without an IPC channel on Linux. The default is `SIGTERM`. */\n readonly signal?: \"SIGINT\" | \"SIGTERM\" | undefined;\n}\n\n/** A program spec tells one program of a group, and what it needs before it starts. */\nexport interface ProgramSpec {\n /** This name is the name of the program in the group: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly program: string;\n readonly args?: readonly string[] | undefined;\n readonly cwd?: string | undefined;\n /** These variables go to the program. They replace the variables of the env file and of the host. */\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** This file gives variables to the program at each start (`parseEnvFile`). They replace the variables of the host. */\n readonly envFile?: string | undefined;\n /** These are the programs that must be ready before this program starts. */\n readonly after?: readonly string[] | undefined;\n /** This spec tells when the program is ready. Without it, the program is ready when it starts. */\n readonly ready?: ReadySpec | undefined;\n /** This spec tells how the supervisor finds that the ready program still works. Without it, only an exit starts the program again. */\n readonly alive?: AliveSpec | undefined;\n /** This policy starts the program again after it stops. The default is `DEFAULT_RESTART`. Null does not start it again. */\n readonly restart?: ProgramRestart | null | undefined;\n /** This spec tells the log file. The default is `<stateDir>/logs/<name>.log`, 10 MB, with 3 old files. Null keeps no log. */\n readonly log?: LogSpec | null | undefined;\n /** True gives the child an IPC channel, for the staged stop of a Node program. The default is false. */\n readonly ipc?: boolean | undefined;\n /** This spec tells the stop. The default is a grace of 10 s. */\n readonly stop?: StopSpec | undefined;\n /** These fields go in the discovery file of the program, `<stateDir>/<name>.json`. */\n readonly listen?: { readonly port?: number | null | undefined; readonly url?: string | null | undefined } | undefined;\n}\n\n/** A group spec tells a group of programs that one supervisor starts in sequence and keeps alive. */\nexport interface GroupSpec {\n readonly name: string;\n /** This folder keeps the lock, the discovery file and the log of each program. */\n readonly stateDir: string;\n readonly programs: readonly ProgramSpec[];\n}\n\n/** These options go with a supervisor. */\nexport interface GroupOptions {\n /** This function gives a number in [0, 1) for the jitter of the backoff. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * A program phase tells where a program of a group is.\n * - `waiting`: a program that it needs is not ready.\n * - `starting`: it runs, and its probe did not pass.\n * - `ready`: it runs, and its probe passed.\n * - `backoff`: it stopped, and it starts again after its backoff.\n * - `held`: another instance holds its lock. The supervisor tries again after the backoff.\n * - `exited`: it stopped, and it has no restart.\n * - `stopping`, `stopped`: the stop of the group.\n */\nexport type ProgramPhase = \"waiting\" | \"starting\" | \"ready\" | \"backoff\" | \"held\" | \"exited\" | \"stopping\" | \"stopped\";\n\n/** A program state is the state of one program of a group, for a status. */\nexport interface ProgramState {\n readonly name: string;\n readonly phase: ProgramPhase;\n /** This number is the process ID of the child, or null. */\n readonly pid: number | null;\n /** This count is the number of starts again since the start of the group. */\n readonly restarts: number;\n /** This text tells the last problem, for example why the probe failed, or it is null. */\n readonly detail: string | null;\n}\n\n/** A group supervisor starts the programs of a group in sequence, starts each again after it stops, and stops them in stages. */\nexport interface GroupSupervisor {\n /** This method starts each program whose programs are ready. A second use does nothing. */\n start(): void;\n /** This method stops each program in the reverse sequence of the start. A second use gives the same promise. */\n stop(): Promise<void>;\n /** This method gives the state of each program, in the sequence of the spec. */\n states(): readonly ProgramState[];\n}\n\n/**\n * This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.\n * The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.\n */\nexport const DEFAULT_RESTART: ProgramRestart = {\n backoff: { base: 1000, factor: 2, cap: 60_000, jitter: { kind: \"subtract\", fraction: 0.5 } },\n resetAfter: { value: 60, unit: \"s\" },\n};\n\nconst DEFAULT_GRACE: Quantity = { value: 10, unit: \"s\" };\nconst DEFAULT_LOG_SIZE: Quantity = { value: 10, unit: \"MB\" };\nconst DEFAULT_LOG_KEEP = 3;\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nconst ms = (time: Quantity): number => valueIn(time, \"ms\");\n\n/**\n * This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the\n * layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.\n */\nexport const startOrder = (spec: GroupSpec): string[][] => {\n const names = new Set(spec.programs.map((program) => program.name));\n const placed = new Set<string>();\n const layers: string[][] = [];\n for (;;) {\n const layer = spec.programs\n .filter((program) => !placed.has(program.name))\n .filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name)))\n .map((program) => program.name);\n if (layer.length === 0) return layers;\n for (const name of layer) placed.add(name);\n layers.push([...new Set(layer)]);\n }\n};\n\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean =>\n isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\n\n/** This function gives the problems of a group spec: each value that the supervisor cannot use. */\nexport const groupProblems = (spec: GroupSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (spec.programs.length === 0) problems.push(\"the group has no programs\");\n const seen = new Set<string>();\n const names = new Set(spec.programs.map((program) => program.name));\n for (const program of spec.programs) {\n const name = program.name;\n const of = `the program ${JSON.stringify(name)}`;\n if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, \".\", \"_\" and \"-\"`);\n if (seen.has(name)) problems.push(`${of} comes two times`);\n seen.add(name);\n if (program.program === \"\") problems.push(`${of}: the program is empty`);\n for (const need of program.after ?? []) {\n if (need === name) problems.push(`${of} is after itself`);\n else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);\n }\n if (program.ready !== undefined) {\n problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));\n for (const field of [\"interval\", \"timeout\", \"within\"] as const)\n if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);\n }\n if (program.alive !== undefined) {\n problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));\n for (const field of [\"interval\", \"timeout\"] as const)\n if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);\n if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1))\n problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);\n }\n if (program.restart !== undefined && program.restart !== null) {\n problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);\n }\n if (program.log !== undefined && program.log !== null) {\n const size = program.log.maxSize;\n if (!(isQuantity(size) && convertible(size.unit, \"B\") && valueIn(size, \"B\") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);\n if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);\n if (program.log.path === \"\") problems.push(`${of}: the path of the log is empty`);\n }\n if (program.stop !== undefined) {\n if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);\n if (program.stop.message !== undefined && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);\n const signal = program.stop.signal;\n if (signal !== undefined && signal !== \"SIGINT\" && signal !== \"SIGTERM\") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);\n }\n const port = program.listen?.port;\n if (port !== undefined && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65_535))\n problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);\n }\n const placed = new Set(startOrder(spec).flat());\n const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));\n if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(\", \")} are in a cycle of \"after\", or after a program in one`);\n return problems;\n};\n\n/** The supervisor keeps one unit for each program: its spec, its files and its state. */\ninterface Unit {\n readonly spec: ProgramSpec;\n readonly lockPath: string;\n readonly discoveryPath: string;\n readonly log: RotatingLog | null;\n readonly retry: Retrier | null;\n phase: ProgramPhase;\n child: ChildHandle | null;\n lock: InstanceLock | null;\n timers: Cancel[];\n /** This cancel stops the next use of the liveness probe. It is one timer, thus a long life adds no timers. */\n watch: Cancel | null;\n restarts: number;\n detail: string | null;\n /** This text tells why the supervisor stopped the child, or it is null. */\n reason: string | null;\n waiters: Array<() => void>;\n}\n\n/**\n * This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes\n * through the ports, thus a test gives `fakeHost()` and starts no process.\n * - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.\n * - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.\n * - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.\n * - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.\n * - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.\n */\nexport const superviseGroup = (spec: GroupSpec, ports: HostPorts, options: GroupOptions = {}): GroupSupervisor => {\n const problems = groupProblems(spec);\n if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join(\"; \")}`);\n const abort = new AbortController();\n const layers = startOrder(spec);\n let started = false;\n let stopping = false;\n let stopped: Promise<void> | null = null;\n\n const say = (level: LogLevel, message: string, fields: LogFields): void => {\n try {\n ports.logger?.log(level, message, { group: spec.name, ...fields });\n } catch {\n // the supervisor does not depend on its logger\n }\n };\n\n const units = new Map<string, Unit>();\n for (const program of spec.programs) {\n const restart = program.restart === undefined ? DEFAULT_RESTART : program.restart;\n const logSpec =\n program.log === undefined\n ? { path: joinPath(ports.platform, spec.stateDir, \"logs\", `${program.name}.log`), maxSize: DEFAULT_LOG_SIZE, keep: DEFAULT_LOG_KEEP }\n : program.log;\n units.set(program.name, {\n spec: program,\n lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),\n discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),\n log: logSpec === null ? null : rotatingLog(logSpec, ports.files),\n retry:\n restart === null\n ? null\n : retrier({ ...restart.backoff, clock: ports.clock, signal: abort.signal, ...(options.random === undefined ? {} : { random: options.random }) }),\n phase: \"waiting\",\n child: null,\n lock: null,\n timers: [],\n watch: null,\n restarts: 0,\n detail: null,\n reason: null,\n waiters: [],\n });\n }\n const unitOf = (name: string): Unit => units.get(name)!;\n\n const clearTimers = (unit: Unit): void => {\n for (const cancel of unit.timers.splice(0)) cancel();\n unit.watch?.();\n unit.watch = null;\n };\n\n const environment = async (unit: Unit): Promise<Record<string, string>> => {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(ports.env)) if (value !== undefined) env[key] = value;\n const file = unit.spec.envFile;\n if (file !== undefined) {\n try {\n const text = await ports.files.read(file);\n if (text === null) say(\"warn\", `the env file ${file} of ${unit.spec.name} does not exist`, { program: unit.spec.name, file });\n else {\n const parsed = parseEnvFile(text);\n Object.assign(env, parsed.env);\n for (const problem of parsed.problems) say(\"warn\", `the env file ${file} of ${unit.spec.name}: ${problem}`, { program: unit.spec.name, file });\n }\n } catch (error) {\n say(\"warn\", `the read of the env file ${file} of ${unit.spec.name} failed`, { program: unit.spec.name, file, error });\n }\n }\n return Object.assign(env, unit.spec.env ?? {});\n };\n\n const consider = (unit: Unit): void => {\n if (!started || stopping || unit.phase !== \"waiting\") return;\n if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === \"ready\")) return;\n void launch(unit);\n };\n const considerAll = (): void => {\n for (const layer of layers) for (const name of layer) consider(unitOf(name));\n };\n\n /** This function starts the program again after the backoff, or ends it when it has no restart. */\n const later = (unit: Unit, phase: \"backoff\" | \"held\"): void => {\n const delay = unit.retry?.schedule(() => {\n if (stopping) return;\n unit.phase = \"waiting\";\n unit.restarts += 1;\n consider(unit);\n });\n if (delay === undefined || delay === null) {\n unit.phase = phase === \"held\" ? \"held\" : \"exited\";\n void unit.lock?.release();\n unit.lock = null;\n return;\n }\n unit.phase = phase;\n say(\"info\", `${unit.spec.name} starts again in ${delay} ms`, { program: unit.spec.name, delay: { value: delay, unit: \"ms\" }, attempt: unit.retry?.attempts });\n };\n\n const markReady = (unit: Unit, child: ChildHandle): void => {\n if (unit.child !== child || stopping) return;\n unit.phase = \"ready\";\n unit.detail = null;\n say(\"info\", `${unit.spec.name} is ready`, { program: unit.spec.name, pid: child.pid });\n const restart = unit.spec.restart === undefined ? DEFAULT_RESTART : unit.spec.restart;\n if (unit.retry !== null && restart !== null) {\n const reset = ports.clock.after(ms(restart.resetAfter), () => {\n if (unit.child === child && unit.phase === \"ready\") unit.retry?.reset();\n });\n // the child keeps the supervisor alive, thus this timer does not (SYS-126)\n reset.unref?.();\n unit.timers.push(reset);\n }\n if (unit.spec.alive !== undefined) watch(unit, child, unit.spec.alive);\n considerAll();\n };\n\n /** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */\n const watch = (unit: Unit, child: ChildHandle, alive: AliveSpec): void => {\n let failures = 0;\n const current = (): boolean => unit.child === child && unit.phase === \"ready\" && !stopping;\n const next = (): void => {\n unit.watch = ports.clock.after(ms(alive.interval), () => {\n unit.watch = null;\n void check();\n });\n // the child keeps the supervisor alive, thus the watch does not (SYS-126)\n unit.watch.unref?.();\n };\n const check = async (): Promise<void> => {\n if (!current()) return;\n const result = await probeOnce(alive.probe, ms(alive.timeout), ports);\n if (!current()) return;\n if (result.ok) {\n if (failures > 0) say(\"info\", `${unit.spec.name} is alive again`, { program: unit.spec.name, pid: child.pid, failures });\n failures = 0;\n unit.detail = null;\n next();\n return;\n }\n failures += 1;\n unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;\n if (failures < alive.failures) {\n say(\"warn\", `${unit.spec.name}: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, why: result.why });\n next();\n return;\n }\n unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not alive, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n };\n next();\n };\n\n const probe = (unit: Unit, child: ChildHandle, ready: ReadySpec): void => {\n const deadline = ports.clock.now() + ms(ready.within);\n const attempt = async (): Promise<void> => {\n if (unit.child !== child || stopping) return;\n const result = await probeOnce(ready.probe, ms(ready.timeout), ports);\n if (unit.child !== child || stopping) return;\n if (result.ok) {\n markReady(unit, child);\n return;\n }\n unit.detail = result.why;\n if (ports.clock.now() >= deadline) {\n unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;\n unit.detail = unit.reason;\n say(\"warn\", `${unit.spec.name} is not ready in its time, thus it stops`, { program: unit.spec.name, pid: child.pid, why: result.why });\n void stagedStop(unit, child);\n return;\n }\n const again = ports.clock.after(ms(ready.interval), () => void attempt());\n // the child keeps the supervisor alive, thus the poll of its readiness does not (SYS-126)\n again.unref?.();\n unit.timers.push(again);\n };\n void attempt();\n };\n\n const exited = (unit: Unit, child: ChildHandle, code: number | null, signal: string | null): void => {\n if (unit.child !== child) return;\n clearTimers(unit);\n unit.child = null;\n for (const waiter of unit.waiters.splice(0)) waiter();\n if (child.pid !== null) void removeDiscovery(unit.discoveryPath, ports, child.pid);\n void unit.lock?.update(null).catch(() => {});\n if (stopping || unit.phase === \"stopping\") {\n unit.phase = \"stopped\";\n return;\n }\n const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? \"unknown\"}` : `the code ${code}`}`;\n unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;\n unit.reason = null;\n say(\"warn\", `${unit.spec.name} stopped: ${unit.detail}`, { program: unit.spec.name, pid: child.pid, code, signal });\n later(unit, \"backoff\");\n };\n\n const launch = async (unit: Unit): Promise<void> => {\n unit.phase = \"starting\";\n unit.detail = null;\n const name = unit.spec.name;\n if (unit.lock === null) {\n const taken = await acquireInstanceLock(unit.lockPath, ports);\n if (stopping) {\n if (taken.kind === \"acquired\") await taken.lock.release();\n return;\n }\n if (taken.kind !== \"acquired\") {\n unit.detail = taken.kind === \"held\" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;\n say(\"warn\", `${name} does not start: ${unit.detail}`, { program: name, lock: unit.lockPath });\n later(unit, \"held\");\n return;\n }\n unit.lock = taken.lock;\n }\n const lock = unit.lock;\n const env = await environment(unit);\n if (stopping) {\n await lock.release();\n unit.lock = null;\n return;\n }\n const child = ports.processes.spawn({ program: unit.spec.program, args: unit.spec.args ?? [], cwd: unit.spec.cwd, env, ipc: unit.spec.ipc ?? false });\n const startedAt = ports.wall();\n unit.child = child;\n child.onOutput((_stream, chunk) => unit.log?.write(chunk));\n child.onExit((code, signal) => exited(unit, child, code, signal));\n const pid = child.pid;\n if (pid === null) return;\n say(\"info\", `${name} started`, { program: name, pid });\n const mark = { pid, startedAt };\n try {\n await lock.update(mark);\n await writeDiscovery(\n unit.discoveryPath,\n { pid, startedAt: new Date(startedAt).toISOString(), port: unit.spec.listen?.port ?? null, url: unit.spec.listen?.url ?? null, extra: { group: spec.name, program: name } },\n ports,\n );\n } catch (error) {\n say(\"warn\", `the files of ${name} were not written`, { program: name, error });\n }\n // a child that ended during the writes leaves no discovery file\n if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);\n if (unit.child !== child || stopping) return;\n if (unit.spec.ready === undefined) markReady(unit, child);\n else probe(unit, child, unit.spec.ready);\n };\n\n /** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */\n const ended = (unit: Unit, child: ChildHandle, wait: number): Promise<boolean> =>\n new Promise((resolve) => {\n if (unit.child !== child) {\n resolve(true);\n return;\n }\n // the stop awaits this wait, thus it keeps the process alive (SYS-126)\n const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));\n unit.waiters.push(() => {\n cancel();\n resolve(true);\n });\n });\n\n /**\n * This function stops a child in stages. The message goes on its IPC channel when it has one. Else\n * Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.\n */\n const stagedStop = async (unit: Unit, child: ChildHandle): Promise<void> => {\n const pid = child.pid;\n if (pid === null || unit.child !== child) return;\n const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);\n const gone = ended(unit, child, grace);\n let asked: string | null = null;\n if (child.ipc && child.send(unit.spec.stop?.message ?? \"shutdown\")) asked = \"the IPC message\";\n else if (ports.platform === \"win32\") {\n const result = await ports.commands.run(\"taskkill\", [\"/T\", \"/PID\", String(pid)]).catch(() => null);\n if (result?.code === 0) asked = \"taskkill\";\n } else {\n const signal = unit.spec.stop?.signal ?? \"SIGTERM\";\n if (ports.processes.signal(pid, signal)) asked = signal;\n }\n say(\"info\", `${unit.spec.name} stops${asked === null ? \"\" : ` through ${asked}`}`, { program: unit.spec.name, pid, grace: { value: grace, unit: \"ms\" } });\n if (asked !== null && (await gone)) return;\n const tree = await stopTree(pid, ports);\n const why = asked === null ? \"the staged stop did not go\" : \"it did not stop in its grace\";\n say(tree.kind === \"failed\" ? \"error\" : \"warn\", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {\n program: unit.spec.name,\n pid,\n outcome: tree.kind,\n });\n if (!(await ended(unit, child, grace))) say(\"error\", `${unit.spec.name} did not end after the stop of its process tree`, { program: unit.spec.name, pid });\n };\n\n const stopUnit = async (unit: Unit): Promise<void> => {\n clearTimers(unit);\n const child = unit.child;\n const pid = child?.pid ?? null;\n if (child !== null && pid !== null) {\n unit.phase = \"stopping\";\n await stagedStop(unit, child);\n await removeDiscovery(unit.discoveryPath, ports, pid);\n }\n unit.phase = \"stopped\";\n await unit.lock?.release();\n unit.lock = null;\n };\n\n return {\n start() {\n if (started || stopping) return;\n started = true;\n say(\"info\", `the group ${spec.name} starts`, { layers });\n considerAll();\n },\n stop() {\n if (stopped !== null) return stopped;\n stopping = true;\n abort.abort();\n stopped = (async () => {\n for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));\n await Promise.all([...units.values()].map((unit) => unit.log?.flush()));\n say(\"info\", `the group ${spec.name} stopped`, {});\n })();\n return stopped;\n },\n states() {\n return spec.programs.map((program) => {\n const unit = unitOf(program.name);\n return { name: program.name, phase: unit.phase, pid: unit.child?.pid ?? null, restarts: unit.restarts, detail: unit.detail };\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAoJA,MAAa,kBAAkC;CAC7C,SAAS;EAAE,MAAM;EAAM,QAAQ;EAAG,KAAK;EAAQ,QAAQ;GAAE,MAAM;GAAY,UAAU;EAAI;CAAE;CAC3F,YAAY;EAAE,OAAO;EAAI,MAAM;CAAI;AACrC;AAEA,MAAM,gBAA0B;CAAE,OAAO;CAAI,MAAM;AAAI;AACvD,MAAM,mBAA6B;CAAE,OAAO;CAAI,MAAM;AAAK;AAC3D,MAAM,mBAAmB;AACzB,MAAM,OAAO;AAEb,MAAM,MAAM,SAA2B,QAAQ,MAAM,IAAI;;;;;AAMzD,MAAa,cAAc,SAAgC;CACzD,MAAM,QAAQ,IAAI,IAAI,KAAK,SAAS,KAAK,YAAY,QAAQ,IAAI,CAAC;CAClE,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,SAAqB,CAAC;CAC5B,SAAS;EACP,MAAM,QAAQ,KAAK,SAChB,QAAQ,YAAY,CAAC,OAAO,IAAI,QAAQ,IAAI,CAAC,CAAC,CAC9C,QAAQ,aAAa,QAAQ,SAAS,CAAC,EAAA,CAAG,OAAO,SAAS,MAAM,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,CAC/F,KAAK,YAAY,QAAQ,IAAI;EAChC,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,KAAK,MAAM,QAAQ,OAAO,OAAO,IAAI,IAAI;EACzC,OAAO,KAAK,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC;CACjC;AACF;A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B,KAAK,MAAM,SAAS,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,GAAG,MAAM,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,OAAO,IAAI,CAAC,CAAC,CAAC;IACxG,MAAM,QAAQ,IAAI,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,MAAM,CAAC,CAAC;IACtE,IAAI,QAAQ,aAAa,KAAK,KAAK,WAAW,CAAC,CAAC;GAClD,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,KAAK,SAAS,KAAK,YAAY;IACpC,MAAM,OAAO,OAAO,QAAQ,IAAI;IAChC,OAAO;KAAE,MAAM,QAAQ;KAAM,OAAO,KAAK;KAAO,KAAK,KAAK,OAAO,OAAO;KAAM,UAAU,KAAK;KAAU,QAAQ,KAAK;IAAO;GAC7H,CAAC;EACH;CACF;AACF"}
@@ -238,6 +238,7 @@ const httpTransport = (edge, knobs, options = {}) => {
238
238
  closeIdleConnections();
239
239
  startSweep();
240
240
  });
241
+ sweep.unref?.();
241
242
  };
242
243
  /**
243
244
  * This function watches the headers of each response when they go, whatever wrote them. Each 503
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","names":["knobMilliseconds"],"sources":["../../src/http/transport.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, valueIn } from \"@mark1russell7/quantity\";\nimport type { CallContext } from \"../call-context.ts\";\nimport type { IncomingMessage, Server, ServerEventMap, ServerResponse } from \"node:http\";\nimport type { Http2Server, Http2ServerResponse, Http2Session } from \"node:http2\";\nimport type { ListenOptions, Socket } from \"node:net\";\nimport type { Cancel, Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { LateHold } from \"../drains.ts\";\nimport { holdLate, noteOutside } from \"../drains.ts\";\nimport { millisecondsOf as knobMilliseconds } from \"../knobs.ts\";\nimport type { Lifecycle, TransportImpl } from \"../lifecycle.ts\";\nimport { answerOwner, watchAnswers } from \"./answers.ts\";\n\n/**\n * These are the knobs of an HTTP transport, by the names of the ordering law. The transport has no\n * defaults, thus each knob is necessary. The declaration of the server gets the same record.\n */\nexport interface HttpKnobs {\n /**\n * This time is the real idle close of the server, which O01 compares with the idle time of a\n * client. Node closes an idle connection at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`.\n * Thus the transport sets `keepAliveTimeout` to this time less the buffer of the server.\n * A time without a bound stops the timer. On HTTP/2, the time is the timeout of a session with no\n * frame (`server.setTimeout`). Node then sends GOAWAY and closes the session.\n */\n readonly server_idle_close: Extent;\n /**\n * This time is the interval of the sweep of idle connections, from the stop of the intake until the\n * close. A time without a bound gives one sweep, at the stop of the intake.\n */\n readonly server_idle_sweep_interval: Extent;\n /** This time goes in the `Retry-After` of each 503 that the transport gives after its intake stops. */\n readonly server_retry_after: Quantity;\n /**\n * This count is the backlog of listen(2), the limit of the accept queue that the server asks for (SYS-103). The\n * kernel clamps it to `net.core.somaxconn`, and a full queue holds the limit plus one (SYS-63). Without this\n * knob, the transport gives no backlog, and Node asks for 511. The knob needs the listen options of the transport.\n * The knob is 1 or more: Node gives listen(2) 511 for a backlog of 0 (`lib/net.js` of Node 24.21.0, line 2325).\n */\n readonly server_listen_backlog?: Quantity;\n /** The other knobs of the server go to the declaration. The transport does not read them. */\n readonly [knob: string]: Extent;\n}\n\n/**\n * These are the knobs that the transport gives the declaration: the knobs of the caller, and the two\n * times that the transport found. Thus the declaration shows the three times of the idle close.\n */\nexport interface HttpTransportKnobs extends HttpKnobs {\n /** This time is the hint that each response sends (`Keep-Alive: timeout=…`), in whole seconds. A time without a bound tells that no hint goes, as on HTTP/2. */\n readonly server_idle_close_hint: Extent;\n /** This time is the `keepAliveTimeoutBuffer` of the server, which Node adds to the timer and not to the hint. A server of HTTP/2 has none: 0 ms. */\n readonly server_idle_close_buffer: Quantity;\n}\n\n/** A mount stage is the stage of the shutdown at which a mount stops: the stop of the intake, or the close. */\nexport type MountStage = \"stop intake\" | \"close transports\";\n\n/** A mount context gives each handler the signals of the shutdown, the lifecycle and the time of a retry. */\nexport interface MountContext {\n /** This signal aborts when the intake stops. A long stream ends in its own protocol at it. */\n readonly intake: AbortSignal;\n /** This signal aborts at the cooperative abort of the drain, or at the close. The work in flight stops at it. */\n readonly signal: AbortSignal;\n /** This lifecycle is the lifecycle that the transport got at its start, or null before the start. */\n readonly life: Lifecycle | null;\n /** This time is the knob `server_retry_after`: the `Retry-After` of each 503 of the handlers. */\n readonly retryAfter: Quantity;\n /**\n * This function tells if a response of a handler can keep its connection open, as the transport\n * decides it. The decision is the option `keepAlive` or `life.keepAlive()`, while the intake is\n * open. Without this function, a handler reads `life.keepAlive()`.\n */\n readonly keepAlive?: (() => boolean) | undefined;\n}\n\n/**\n * A request handler answers a request and gives true, or it gives false and does not touch the\n * response. Then the next handler gets the request. `until` tells when the handler stops.\n */\nexport interface RequestHandler {\n (req: IncomingMessage, res: ServerResponse, context: MountContext): boolean | Promise<boolean>;\n readonly until?: MountStage | undefined;\n}\n\ntype UpgradeArgs = ServerEventMap[\"upgrade\"];\n\n/** An upgrade socket is the stream of an upgraded connection, as the `upgrade` event of Node gives it. */\nexport type UpgradeSocket = UpgradeArgs[1];\n\n/** An upgrade handler takes an upgraded connection, for example a WebSocket server in its `noServer` mode. */\nexport interface UpgradeHandler {\n (req: IncomingMessage, socket: UpgradeSocket, head: UpgradeArgs[2], context: MountContext): void;\n readonly until?: MountStage | undefined;\n}\n\n/** An upgrade match is a path, without its query, or a function that tells if a handler takes a request. */\nexport type UpgradeMatch = string | ((req: IncomingMessage) => boolean);\n\n/** These options change one mount. */\nexport interface MountOptions {\n /**\n * This stage is when the mount stops. Without it, the stage of the handler applies, and then\n * `stop intake`. A mount until `close transports` keeps the listener open through the drain.\n */\n readonly until?: MountStage | undefined;\n}\n\n/**\n * An edge server is the server of a transport: a server of `node:http`, or a server of `node:http2`\n * without TLS (h2c, from `http2.createServer()`).\n */\nexport type EdgeServer = Server | Http2Server;\n\n/** These options make an HTTP transport. */\nexport interface HttpTransportOptions<S extends EdgeServer = Server> {\n /**\n * These are the listen options of `start()`, or a function that makes the server listen. Without\n * them, `start()` takes a server that listens already.\n */\n readonly listen?: ListenOptions | ((server: S) => Promise<void> | void) | undefined;\n /** This clock is the clock of the lifecycle. The deadline of the drain and the sweep use it. */\n readonly clock?: Clock | undefined;\n /**\n * This function tells if a response can keep its connection open. Without it, the transport reads\n * `life.keepAlive()` of the lifecycle of its start. The transport reads it when the headers of\n * each response go. On HTTP/1.1, false gives `Connection: close`. On HTTP/2, false gives a GOAWAY\n * on the session of the response.\n */\n readonly keepAlive?: (() => boolean) | undefined;\n /** This function receives each error of a handler. The transport then answers 500, or it destroys the response. */\n readonly onError?: ((error: unknown, req: IncomingMessage) => void) | undefined;\n /**\n * With this call context, each handler runs in the context of the headers of its request. The context\n * has the trace of `traceparent`, and the baggage of a trusted request. `callContext` of the entry `/otel` gives one.\n */\n readonly callContext?: CallContext | undefined;\n /**\n * This function tells if the baggage of a request is trusted, for example after a token check. The\n * default trusts no request: each request joins the trace of its caller, and its baggage is dropped.\n */\n readonly trustBaggage?: ((req: IncomingMessage) => boolean) | undefined;\n}\n\n/** An HTTP transport is a server of `node:http` or `node:http2` as a transport of the lifecycle, with a list of mounts on its listener. */\nexport interface HttpTransport<S extends EdgeServer = Server> extends TransportImpl {\n readonly server: S;\n /** These knobs go to the declaration of the server: the knobs of the caller, the hint and the buffer. */\n readonly knobs: HttpTransportKnobs;\n /** This method adds a request handler at the end of the list, and gives the function that removes it. */\n mount(handler: RequestHandler, options?: MountOptions): () => void;\n /** This method adds an upgrade handler for a path, and gives the function that removes it. A server of HTTP/2 has no upgrade, thus it refuses the handler. */\n upgrade(match: UpgradeMatch, handler: UpgradeHandler, options?: MountOptions): () => void;\n /** This count is the number of open connections, idle connections and upgraded connections too. On HTTP/2, a connection is the socket of a session. */\n readonly connections: number;\n /** This flag tells if the transport stopped its intake. */\n readonly intakeStopped: boolean;\n}\n\ninterface RequestMount {\n readonly handler: RequestHandler;\n readonly until: MountStage;\n}\n\ninterface UpgradeMount {\n readonly matches: (req: IncomingMessage) => boolean;\n readonly handler: UpgradeHandler;\n readonly until: MountStage;\n}\n\n/** This function gives the path of a request target, without its query and fragment. */\nexport const pathOf = (url: string | undefined): string => {\n const raw = url ?? \"/\";\n const end = raw.search(/[?#]/);\n const path = end === -1 ? raw : raw.slice(0, end);\n if (path.startsWith(\"/\")) return path;\n // an absolute target, as a proxy sends it\n try {\n return new URL(raw).pathname;\n } catch {\n return path;\n }\n};\n\n/** This function gives a knob in milliseconds, or infinity for a time without a bound. */\nconst millisecondsOf = (knobs: Readonly<Record<string, Extent | undefined>>, name: string, owner = \"httpTransport\"): number =>\n knobMilliseconds(knobs, name, owner);\n\n/**\n * This function gives the `Retry-After` of the knob `server_retry_after`, in whole seconds, rounded\n * up. The knob is necessary, and it has a bound.\n */\nexport const retryAfterOf = (knobs: Readonly<Record<string, Extent | undefined>>, owner: string): string => {\n const retryAfter = millisecondsOf(knobs, \"server_retry_after\", owner);\n if (!Number.isFinite(retryAfter)) throw new Error(\"the knob server_retry_after has no bound: a Retry-After needs a time\");\n return String(Math.ceil(retryAfter / 1000));\n};\n\n/**\n * This function gives the backlog of listen(2) from the knob `server_listen_backlog`, or undefined without the\n * knob. The backlog is a whole count of 0 or more. A backlog of 0 is valid: the queue then holds one connection.\n */\nexport const backlogOf = (knobs: Readonly<Record<string, Extent | undefined>>, owner: string): number | undefined => {\n const amount = knobs[\"server_listen_backlog\"];\n if (amount === undefined) return undefined;\n if (!convertible(amount.unit, \"count\")) throw new Error(\"the knob server_listen_backlog is not a count\");\n if (amount.value === \"infinite\") throw new Error(`the knob server_listen_backlog of ${owner} has no bound: listen(2) takes a whole count`);\n const value = valueIn(amount, \"count\");\n if (!(Number.isInteger(value) && value >= 0)) throw new Error(`the knob server_listen_backlog is ${value}, not a whole count of 0 or more`);\n // Node calls listen(2) with `backlog || 511` (lib/net.js of Node 24.21.0, line 2325), thus a backlog of 0 is 511\n if (value === 0)\n throw new Error(`the knob server_listen_backlog of ${owner} is 0, and Node gives listen(2) 511 for 0: the transport cannot ask for 0`);\n return value;\n};\n\n/** This function tells if the headers of a call of `writeHead` name a header, an object or a flat list of names and values. */\nconst names = (headers: unknown, name: string): boolean => {\n if (Array.isArray(headers)) return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === name);\n return typeof headers === \"object\" && headers !== null && Object.keys(headers).some((key) => key.toLowerCase() === name);\n};\n\n/** This function gives the headers of a call of `writeHead` without one header. */\nconst without = (headers: unknown, name: string): unknown => {\n if (Array.isArray(headers)) {\n const kept: unknown[] = [];\n for (let at = 0; at + 1 < headers.length; at += 2)\n if (String(headers[at]).toLowerCase() !== name) kept.push(headers[at], headers[at + 1]);\n return kept;\n }\n if (typeof headers !== \"object\" || headers === null) return headers;\n return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== name));\n};\n\n/**\n * This function applies the rule of `Retry-After` to a call of `writeHead`, and gives its arguments.\n * A 503 without `Retry-After` gets the time of `server_retry_after` (RFC 9110). A 500 loses each\n * `Retry-After`, from the call and from the response.\n */\nconst retryRule = (res: ServerResponse, args: unknown[], retryAfter: string): unknown[] => {\n const status = typeof args[0] === \"number\" ? args[0] : res.statusCode;\n const at = typeof args[1] === \"string\" ? 2 : 1;\n if (status === 503 && !res.hasHeader(\"retry-after\") && !names(args[at], \"retry-after\")) res.setHeader(\"retry-after\", retryAfter);\n if (status !== 500) return args;\n res.removeHeader(\"retry-after\");\n if (!names(args[at], \"retry-after\")) return args;\n const given = [...args];\n given[at] = without(args[at], \"retry-after\");\n return given;\n};\n\nconst STATUS_TEXT: Readonly<Record<number, string>> = { 404: \"Not Found\", 500: \"Internal Server Error\", 503: \"Service Unavailable\" };\n\n/** This function tells if an edge server is a server of `node:http2`. A server of `node:http` has `closeIdleConnections`, and one of HTTP/2 has none. */\nconst isHttp2 = (server: EdgeServer): server is Http2Server => typeof (server as Partial<Server>).closeIdleConnections !== \"function\";\n\n/** This function gives the session of HTTP/2 of a response, or undefined for a response of HTTP/1.1. */\nconst sessionOf = (res: ServerResponse): Http2Session | undefined => (res as unknown as Partial<Http2ServerResponse>).stream?.session;\n\n/** This function tells if a response is destroyed. A response of HTTP/2 tells it through its stream. */\nconst destroyed = (res: ServerResponse): boolean =>\n res.destroyed === true || (res as unknown as Partial<Http2ServerResponse>).stream?.destroyed === true;\n\n/** This function tells if the headers of a call of `writeHead` give `Connection: close`. */\nconst closes = (headers: unknown): boolean => {\n if (Array.isArray(headers))\n return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === \"connection\" && String(headers[at + 1]).toLowerCase() === \"close\");\n if (typeof headers !== \"object\" || headers === null) return false;\n return Object.entries(headers).some(([key, value]) => key.toLowerCase() === \"connection\" && String(value).toLowerCase() === \"close\");\n};\n\n/**\n * This function sends GOAWAY on a session of HTTP/2, once. `close()` of Node sends it with the last\n * stream that the server took. Each stream up to that one ends as usual. Then the session closes.\n * The client sends each later stream again on a new connection, because the server did not take it.\n */\nconst goaway = (session: Http2Session): void => {\n if (!session.closed && !session.destroyed) session.close();\n};\n\n/**\n * This function makes a server of `node:http` or `node:http2` a transport of the lifecycle (S6 A8 and\n * A13). It is not a framework: it has no routes, no body parser and no middleware.\n * - The count of work in flight comes from events: each response until its `close`, and each upgraded\n * connection until its `close`.\n * - `stopIntake` closes the listener, and new connections get a refusal. It closes the idle connections\n * at once and at each `server_idle_sweep_interval`. Each later response gets `Connection: close`.\n * A connection is not idle while the bytes of its answer go (SYS-33).\n * - `drain` waits until no work is in flight, or until the deadline. It gives the cooperative abort to\n * the handlers through their context. At the deadline, it also waits for each answer that is to come\n * or to go out (SYS-29). The cap of the phase bounds that wait. Answers that did not go out by the\n * cap are not a failure of the phase. A stream outside the lifecycle of the transport does not hold it.\n * - `close` destroys each connection. A second close gives the same promise.\n * - The mounts share one port. The first request handler that gives true answers. After the stop of\n * the intake, only the mounts until `close transports` answer, and each other request gets a 503.\n * - HTTP/2 has no `Connection` header (RFC 9113, section 8.2.2). Thus a close of a connection is a\n * GOAWAY on its session. Each handler gets the request and the response of the compatibility API of\n * `node:http2`. They have the parts of the API that the handlers of this entry use. A handler that\n * gives `Connection: close` gets a GOAWAY. The stop of the intake sends GOAWAY on each session, and\n * the close destroys each session.\n */\nexport const httpTransport = <S extends EdgeServer = Server>(edge: S, knobs: HttpKnobs, options: HttpTransportOptions<S> = {}): HttpTransport<S> => {\n // the events and the listener are those of net.Server on each kind of server\n const server = edge as unknown as Server;\n const h2 = isHttp2(edge) ? edge : null;\n const clock = options.clock ?? realClock;\n const idleClose = millisecondsOf(knobs, \"server_idle_close\");\n const sweepEvery = millisecondsOf(knobs, \"server_idle_sweep_interval\");\n if (sweepEvery === 0)\n throw new Error(\"the knob server_idle_sweep_interval is zero: a sweep needs an interval above zero\");\n const retryAfterHeader = retryAfterOf(knobs, \"httpTransport\");\n const backlog = backlogOf(knobs, \"httpTransport\");\n if (backlog !== undefined && (options.listen === undefined || typeof options.listen === \"function\"))\n throw new Error(\"the knob server_listen_backlog needs the listen options of the transport: the transport does not make this server listen\");\n if (backlog !== undefined && typeof options.listen === \"object\" && options.listen.backlog !== undefined)\n throw new Error(\"the backlog is in the knob server_listen_backlog and in the listen options: give it once, as the knob\");\n for (const derived of [\"server_idle_close_hint\", \"server_idle_close_buffer\"])\n if ((knobs as Readonly<Record<string, Extent | undefined>>)[derived] !== undefined)\n throw new Error(`the knob ${derived} comes from the transport: give only server_idle_close`);\n if (server.listenerCount(\"request\") > 0 || server.listenerCount(\"upgrade\") > 0)\n throw new Error(\"the server has a request or upgrade listener of its own: mount it as a handler\");\n // Node closes an idle connection at keepAliveTimeout + keepAliveTimeoutBuffer, and its hint is\n // keepAliveTimeout. The buffer stays, thus the hint is less than the real close. An older Node has no\n // buffer. A session of HTTP/2 closes at the timeout of the server, with no buffer and no hint\n const buffer = h2 === null ? ((server as { keepAliveTimeoutBuffer?: number }).keepAliveTimeoutBuffer ?? 0) : 0;\n if (h2 !== null && idleClose === 0)\n throw new Error(\"the knob server_idle_close is 0 ms: the timeout of a session of HTTP/2 needs a time above zero\");\n if (h2 === null && Number.isFinite(idleClose) && idleClose <= buffer)\n throw new Error(\n `the knob server_idle_close is ${idleClose} ms, at or below the keepAliveTimeoutBuffer of the server, ${buffer} ms: ` +\n \"the server closes an idle connection at keepAliveTimeout + keepAliveTimeoutBuffer\",\n );\n // 0 stops the keep-alive timer and the hint in Node, and the timeout of each session of HTTP/2\n if (h2 === null) server.keepAliveTimeout = Number.isFinite(idleClose) ? idleClose - buffer : 0;\n else h2.setTimeout(Number.isFinite(idleClose) ? idleClose : 0);\n const declared: HttpTransportKnobs = {\n ...knobs,\n server_idle_close_hint:\n h2 === null && Number.isFinite(idleClose)\n ? { value: Math.floor(server.keepAliveTimeout / 1000), unit: \"s\" }\n : { value: \"infinite\", unit: \"s\" },\n server_idle_close_buffer: { value: buffer, unit: \"ms\" },\n };\n\n const requestMounts: RequestMount[] = [];\n const upgradeMounts: UpgradeMount[] = [];\n const responses = new Set<ServerResponse>();\n const upgraded = new Set<UpgradeSocket>();\n const sockets = new Set<Socket>();\n // the sessions of HTTP/2: the stop of the intake sends GOAWAY on each one, and the close destroys each one\n const sessions = new Set<Http2Session>();\n // the check of each drain: it ends its drain when nothing holds it\n const drainers = new Set<() => void>();\n const closedWaiters = new Set<() => void>();\n const intake = new AbortController();\n const cooperative = new AbortController();\n // the lifecycle comes at the start, thus the context reads it at each request\n let life: Lifecycle | null = null;\n const context: MountContext = {\n intake: intake.signal,\n signal: cooperative.signal,\n get life() {\n return life;\n },\n retryAfter: knobs.server_retry_after,\n // the option keepAlive decides for each handler too, thus a handled route does not close by itself\n keepAlive: () => keepsAlive(),\n };\n let intakeOpen = true;\n let listenerOpen = server.listening;\n let serverClosed = !server.listening;\n let sweep: Cancel | null = null;\n let closing: Promise<void> | null = null;\n\n const inFlight = (): number => responses.size + upgraded.size;\n /**\n * This function gives what holds a drain after its deadline. An answer is unflushed when its handler\n * ended it and its bytes did not all go. It is unflushed too while `writeOutcome` waits for a client\n * that does not read. A call runs while `writeOutcome` waits for the end of its request, which the\n * cut of the drain gives. Only a stream of the lifecycle of the transport counts, because only its\n * cut ends the stream. A response that is open for another reason does not hold the drain.\n */\n const lateHold = (): LateHold & { readonly outside: number } => {\n let running = 0;\n let unflushed = 0;\n let outside = 0;\n for (const res of responses) {\n if (destroyed(res)) continue;\n if (res.writableEnded) {\n if (!res.writableFinished) unflushed += 1;\n continue;\n }\n const owner = answerOwner(res);\n if (owner === undefined) continue;\n if (life === null || owner !== life) outside += 1;\n else if (res.writableNeedDrain) unflushed += 1;\n else running += 1;\n }\n return { running, unflushed, outside };\n };\n const answering = (): boolean => {\n const hold = lateHold();\n return hold.running + hold.unflushed > 0;\n };\n const report = (error: unknown, req: IncomingMessage): void => {\n try {\n options.onError?.(error, req);\n } catch {\n // an error of the error hook does not stop the transport\n }\n };\n const settled = (): void => {\n for (const check of [...drainers]) check();\n if (closing !== null && inFlight() === 0 && sockets.size === 0 && serverClosed)\n for (const done of [...closedWaiters]) done();\n };\n // before its start, a transport has no lifecycle: a server that listens already keeps its connections\n const keepsAlive = (): boolean => intakeOpen && (options.keepAlive?.() ?? life?.keepAlive() ?? true);\n const live = <T extends { readonly until: MountStage }>(mounts: readonly T[]): T[] =>\n intakeOpen ? [...mounts] : mounts.filter((mount) => mount.until === \"close transports\");\n const throughDrain = (): boolean =>\n requestMounts.some((mount) => mount.until === \"close transports\") ||\n upgradeMounts.some((mount) => mount.until === \"close transports\");\n const closeListener = (): void => {\n if (!listenerOpen) return;\n listenerOpen = false;\n server.close();\n };\n // a session of HTTP/2 ends its streams after a GOAWAY, thus each session gets it, an idle one or not\n const closeIdleConnections = (): void => {\n if (h2 === null) server.closeIdleConnections();\n else for (const session of sessions) goaway(session);\n };\n const startSweep = (): void => {\n if (!Number.isFinite(sweepEvery) || closing !== null) return;\n sweep = clock.after(sweepEvery, () => {\n sweep = null;\n if (closing !== null) return;\n closeIdleConnections();\n startSweep();\n });\n };\n\n /**\n * This function watches the headers of each response when they go, whatever wrote them. Each 503\n * gets `Retry-After`, and a 500 gets none. The response closes its connection while the transport\n * cannot keep it. On HTTP/2, the `Connection` header goes away, and a close is a GOAWAY on the session.\n */\n const watchHeaders = (res: ServerResponse): void => {\n const writeHead = res.writeHead as (...args: unknown[]) => ServerResponse;\n res.writeHead = ((...args: unknown[]): ServerResponse => {\n if (res.headersSent) return writeHead.apply(res, args);\n const session = sessionOf(res);\n if (session !== undefined) {\n const at = typeof args[1] === \"string\" ? 2 : 1;\n const asked = String(res.getHeader(\"connection\") ?? \"\").toLowerCase() === \"close\" || closes(args[at]);\n res.removeHeader(\"connection\");\n const given = [...args];\n if (names(args[at], \"connection\")) given[at] = without(args[at], \"connection\");\n if (asked || !keepsAlive()) goaway(session);\n return writeHead.apply(res, retryRule(res, given, retryAfterHeader));\n }\n if (!keepsAlive()) {\n res.shouldKeepAlive = false;\n res.setHeader(\"connection\", \"close\");\n }\n return writeHead.apply(res, retryRule(res, args, retryAfterHeader));\n }) as ServerResponse[\"writeHead\"];\n };\n const answer = (res: ServerResponse, status: number, headers: Readonly<Record<string, string>> = {}): void => {\n if (res.headersSent) {\n res.destroy();\n return;\n }\n const body = STATUS_TEXT[status] ?? \"\";\n res.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\", \"content-length\": String(Buffer.byteLength(body)), ...headers });\n res.end(body);\n };\n const refuse = (res: ServerResponse): void => answer(res, 503, { \"retry-after\": retryAfterHeader, connection: \"close\" });\n\n const route = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const mounts = live(requestMounts);\n try {\n for (const mount of mounts) {\n const given = mount.handler(req, res, context);\n const taken = typeof given === \"boolean\" ? given : await given;\n // a handler that wrote its response took the request, whatever it gave\n if (taken || res.headersSent || res.writableEnded) return;\n }\n } catch (error) {\n report(error, req);\n if (!res.writableEnded) answer(res, 500);\n return;\n }\n if (intakeOpen) answer(res, 404);\n else refuse(res);\n };\n\n // each handler runs in the context of the headers of its request, when the options give a call context\n const callContext = options.callContext;\n const trustBaggage = options.trustBaggage ?? (() => false);\n const inCall = <T>(req: IncomingMessage, fn: () => T): T => (callContext === undefined ? fn() : callContext.run(req.headers, trustBaggage(req), fn));\n\n const onRequest = (req: IncomingMessage, res: ServerResponse): void => {\n responses.add(res);\n // the bytes of an answer went: a drain after its deadline can end\n res.once(\"finish\", settled);\n res.once(\"close\", () => {\n responses.delete(res);\n settled();\n });\n watchHeaders(res);\n void inCall(req, () => route(req, res));\n };\n\n const onUpgrade = (req: IncomingMessage, socket: UpgradeSocket, head: UpgradeArgs[2]): void => {\n socket.on(\"error\", () => {});\n const mount = live(upgradeMounts).find((each) => each.matches(req));\n if (mount === undefined) {\n const status = intakeOpen ? 404 : 503;\n const extra = intakeOpen ? \"\" : `Retry-After: ${retryAfterHeader}\\r\\n`;\n socket.end(`HTTP/1.1 ${status} ${STATUS_TEXT[status]!}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n${extra}\\r\\n`);\n return;\n }\n if (socket.destroyed) return;\n upgraded.add(socket);\n socket.once(\"close\", () => {\n upgraded.delete(socket);\n settled();\n });\n try {\n inCall(req, () => mount.handler(req, socket, head, context));\n } catch (error) {\n report(error, req);\n socket.destroy();\n }\n };\n\n const onConnection = (socket: Socket): void => {\n sockets.add(socket);\n socket.once(\"close\", () => {\n sockets.delete(socket);\n settled();\n });\n };\n\n /**\n * Node counts a connection idle at the `end()` of its response, also while the bytes of the body\n * still go. Then `closeIdleConnections` destroys the socket and cuts the answer (SYS-33). This\n * method replaces it on the server, thus `server.close()` uses it too. Node keeps the socket of\n * a response that did not end. Thus the method shows each answer whose bytes did not go as not\n * ended, for the time of the call.\n */\n if (h2 === null) {\n const closeIdle = server.closeIdleConnections;\n server.closeIdleConnections = function closeIdleConnections(this: Server): void {\n const going = [...responses].filter((res) => res.writableEnded && !res.writableFinished && !res.destroyed);\n for (const res of going) res.finished = false;\n try {\n closeIdle.call(this);\n } finally {\n for (const res of going) res.finished = true;\n }\n };\n }\n\n server.on(\"request\", onRequest);\n if (h2 === null) server.on(\"upgrade\", onUpgrade);\n else\n h2.on(\"session\", (session) => {\n sessions.add(session);\n session.once(\"close\", () => {\n sessions.delete(session);\n settled();\n });\n });\n server.on(\"connection\", onConnection);\n server.on(\"listening\", () => {\n listenerOpen = true;\n serverClosed = false;\n });\n server.on(\"close\", () => {\n listenerOpen = false;\n serverClosed = true;\n settled();\n });\n\n const remover = <T>(list: T[], entry: T) => (): void => {\n const at = list.indexOf(entry);\n if (at >= 0) list.splice(at, 1);\n // the last mount through the drain went: the listener closes as the stop of the intake asks\n if (!intakeOpen && closing === null && !throughDrain()) closeListener();\n };\n\n return {\n server: edge,\n knobs: declared,\n get connections() {\n return sockets.size;\n },\n get intakeStopped() {\n return !intakeOpen;\n },\n mount(handler, mountOptions = {}) {\n const entry: RequestMount = { handler, until: mountOptions.until ?? handler.until ?? \"stop intake\" };\n requestMounts.push(entry);\n return remover(requestMounts, entry);\n },\n upgrade(match, handler, mountOptions = {}) {\n if (h2 !== null) throw new Error(\"a server of HTTP/2 has no upgrade: mount a request handler\");\n const matches = typeof match === \"string\" ? (req: IncomingMessage) => pathOf(req.url) === match : match;\n const entry: UpgradeMount = { matches, handler, until: mountOptions.until ?? handler.until ?? \"stop intake\" };\n upgradeMounts.push(entry);\n return remover(upgradeMounts, entry);\n },\n async start(_signal, given) {\n life = given;\n if (closing !== null) throw new Error(\"the transport closed: a closed transport does not start again\");\n // a listener that another owner adds after the transport answers too, thus the start refuses it\n if (server.listenerCount(\"request\") > 1 || server.listenerCount(\"upgrade\") > 1)\n throw new Error(\"the server has a request or upgrade listener of its own: mount it as a handler\");\n if (server.listening) return;\n const listen = options.listen;\n if (listen === undefined) throw new Error(\"the server does not listen, and the transport has no listen options\");\n if (typeof listen === \"function\") {\n await listen(edge);\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const failed = (error: Error): void => {\n server.off(\"listening\", listened);\n reject(error);\n };\n const listened = (): void => {\n server.off(\"error\", failed);\n resolve();\n };\n server.once(\"error\", failed);\n server.once(\"listening\", listened);\n server.listen(backlog === undefined ? listen : { ...listen, backlog });\n });\n },\n stopIntake() {\n if (!intakeOpen) return;\n intakeOpen = false;\n intake.abort(new Error(\"the transport stopped its intake\"));\n if (!throughDrain()) closeListener();\n closeIdleConnections();\n startSweep();\n },\n drain(deadline, signal) {\n const abort = (): void => {\n if (!cooperative.signal.aborted) cooperative.abort(signal.reason);\n };\n if (signal.aborted) abort();\n else signal.addEventListener(\"abort\", abort, { once: true });\n // nothing in flight: the drain ends at once, with no timer\n if (inFlight() === 0) {\n signal.removeEventListener(\"abort\", abort);\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n let unwatch: () => void = () => {};\n let unhold: () => void = () => {};\n let late = false;\n let ended = false;\n // before the deadline, the work in flight holds the drain. After it, only an answer to come or to go out holds it\n const check = (): void => {\n if (ended || (inFlight() > 0 && (!late || answering()))) return;\n ended = true;\n drainers.delete(check);\n cancel();\n unwatch();\n unhold();\n signal.removeEventListener(\"abort\", abort);\n resolve();\n };\n // the cut of the requests comes at the same time, before or after this timer: the drain waits for its answers in each case\n const reached = (): void => {\n late = true;\n unwatch = watchAnswers(check);\n // the lifecycle reads the hold at the cap: answers that do not go out are not a failure of the phase\n if (life !== null) {\n unhold = holdLate(life, () => {\n const { running, unflushed } = lateHold();\n return { running, unflushed };\n });\n // a stream outside the lifecycle does not hold the drain: the record of the phase gives the count\n noteOutside(life, lateHold().outside);\n }\n check();\n };\n drainers.add(check);\n if (deadline <= clock.now()) reached();\n else cancel = clock.after(deadline - clock.now(), reached);\n });\n },\n inFlight,\n close() {\n if (closing !== null) return closing;\n intakeOpen = false;\n if (!intake.signal.aborted) intake.abort(new Error(\"the transport closed\"));\n if (!cooperative.signal.aborted) cooperative.abort(new Error(\"the transport closed\"));\n sweep?.();\n sweep = null;\n closing = new Promise<void>((resolve) => {\n closedWaiters.add(resolve);\n });\n closeListener();\n if (h2 === null) server.closeAllConnections();\n else for (const session of [...sessions]) session.destroy();\n for (const socket of [...upgraded]) socket.destroy();\n for (const socket of [...sockets]) socket.destroy();\n settled();\n return closing;\n },\n };\n};\n"],"mappings":";;;;;;;AA4KA,MAAa,UAAU,QAAoC;CACzD,MAAM,MAAM,OAAO;CACnB,MAAM,MAAM,IAAI,OAAO,MAAM;CAC7B,MAAM,OAAO,QAAQ,KAAK,MAAM,IAAI,MAAM,GAAG,GAAG;CAChD,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CAEjC,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAM,kBAAkB,OAAqD,MAAc,QAAQ,oBACjGA,iBAAiB,OAAO,MAAM,KAAK;;;;;AAMrC,MAAa,gBAAgB,OAAqD,UAA0B;CAC1G,MAAM,aAAa,eAAe,OAAO,sBAAsB,KAAK;CACpE,IAAI,CAAC,OAAO,SAAS,UAAU,GAAG,MAAM,IAAI,MAAM,sEAAsE;CACxH,OAAO,OAAO,KAAK,KAAK,aAAa,GAAI,CAAC;AAC5C;;;;;AAMA,MAAa,aAAa,OAAqD,UAAsC;CACnH,MAAM,SAAS,MAAM;CACrB,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,IAAI,CAAC,YAAY,OAAO,MAAM,OAAO,GAAG,MAAM,IAAI,MAAM,+CAA+C;CACvG,IAAI,OAAO,UAAU,YAAY,MAAM,IAAI,MAAM,qCAAqC,MAAM,6CAA6C;CACzI,MAAM,QAAQ,QAAQ,QAAQ,OAAO;CACrC,IAAI,EAAE,OAAO,UAAU,KAAK,KAAK,SAAS,IAAI,MAAM,IAAI,MAAM,qCAAqC,MAAM,iCAAiC;CAE1I,IAAI,UAAU,GACZ,MAAM,IAAI,MAAM,qCAAqC,MAAM,0EAA0E;CACvI,OAAO;AACT;;AAGA,MAAM,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AEA,MAAM,gBAAsB;KAC1B,OAAO;KACP,UAAU,aAAa,KAAK;KAE5B,IAAI,SAAS,MAAM;MACjB,SAAS,SAAS,YAAY;OAC5B,MAAM,EAAE,SAAS,cAAc,SAAS;OACxC,OAAO;QAAE;QAAS;OAAU;MAC9B,CAAC;MAED,YAAY,MAAM,SAAS,CAAC,CAAC,OAAO;KACtC;KACA,MAAM;IACR;IACA,SAAS,IAAI,KAAK;IAClB,IAAI,YAAY,MAAM,IAAI,GAAG,QAAQ;SAChC,SAAS,MAAM,MAAM,WAAW,MAAM,IAAI,GAAG,OAAO;GAC3D,CAAC;EACH;EACA;EACA,QAAQ;GACN,IAAI,YAAY,MAAM,OAAO;GAC7B,aAAa;GACb,IAAI,CAAC,OAAO,OAAO,SAAS,OAAO,sBAAM,IAAI,MAAM,sBAAsB,CAAC;GAC1E,IAAI,CAAC,YAAY,OAAO,SAAS,YAAY,sBAAM,IAAI,MAAM,sBAAsB,CAAC;GACpF,QAAQ;GACR,QAAQ;GACR,UAAU,IAAI,SAAe,YAAY;IACvC,cAAc,IAAI,OAAO;GAC3B,CAAC;GACD,cAAc;GACd,IAAI,OAAO,MAAM,OAAO,oBAAoB;QACvC,KAAK,MAAM,WAAW,CAAC,GAAG,QAAQ,GAAG,QAAQ,QAAQ;GAC1D,KAAK,MAAM,UAAU,CAAC,GAAG,QAAQ,GAAG,OAAO,QAAQ;GACnD,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,QAAQ;GAClD,QAAQ;GACR,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"transport.js","names":["knobMilliseconds"],"sources":["../../src/http/transport.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, valueIn } from \"@mark1russell7/quantity\";\nimport type { CallContext } from \"../call-context.ts\";\nimport type { IncomingMessage, Server, ServerEventMap, ServerResponse } from \"node:http\";\nimport type { Http2Server, Http2ServerResponse, Http2Session } from \"node:http2\";\nimport type { ListenOptions, Socket } from \"node:net\";\nimport type { Cancel, Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { LateHold } from \"../drains.ts\";\nimport { holdLate, noteOutside } from \"../drains.ts\";\nimport { millisecondsOf as knobMilliseconds } from \"../knobs.ts\";\nimport type { Lifecycle, TransportImpl } from \"../lifecycle.ts\";\nimport { answerOwner, watchAnswers } from \"./answers.ts\";\n\n/**\n * These are the knobs of an HTTP transport, by the names of the ordering law. The transport has no\n * defaults, thus each knob is necessary. The declaration of the server gets the same record.\n */\nexport interface HttpKnobs {\n /**\n * This time is the real idle close of the server, which O01 compares with the idle time of a\n * client. Node closes an idle connection at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`.\n * Thus the transport sets `keepAliveTimeout` to this time less the buffer of the server.\n * A time without a bound stops the timer. On HTTP/2, the time is the timeout of a session with no\n * frame (`server.setTimeout`). Node then sends GOAWAY and closes the session.\n */\n readonly server_idle_close: Extent;\n /**\n * This time is the interval of the sweep of idle connections, from the stop of the intake until the\n * close. A time without a bound gives one sweep, at the stop of the intake.\n */\n readonly server_idle_sweep_interval: Extent;\n /** This time goes in the `Retry-After` of each 503 that the transport gives after its intake stops. */\n readonly server_retry_after: Quantity;\n /**\n * This count is the backlog of listen(2), the limit of the accept queue that the server asks for (SYS-103). The\n * kernel clamps it to `net.core.somaxconn`, and a full queue holds the limit plus one (SYS-63). Without this\n * knob, the transport gives no backlog, and Node asks for 511. The knob needs the listen options of the transport.\n * The knob is 1 or more: Node gives listen(2) 511 for a backlog of 0 (`lib/net.js` of Node 24.21.0, line 2325).\n */\n readonly server_listen_backlog?: Quantity;\n /** The other knobs of the server go to the declaration. The transport does not read them. */\n readonly [knob: string]: Extent;\n}\n\n/**\n * These are the knobs that the transport gives the declaration: the knobs of the caller, and the two\n * times that the transport found. Thus the declaration shows the three times of the idle close.\n */\nexport interface HttpTransportKnobs extends HttpKnobs {\n /** This time is the hint that each response sends (`Keep-Alive: timeout=…`), in whole seconds. A time without a bound tells that no hint goes, as on HTTP/2. */\n readonly server_idle_close_hint: Extent;\n /** This time is the `keepAliveTimeoutBuffer` of the server, which Node adds to the timer and not to the hint. A server of HTTP/2 has none: 0 ms. */\n readonly server_idle_close_buffer: Quantity;\n}\n\n/** A mount stage is the stage of the shutdown at which a mount stops: the stop of the intake, or the close. */\nexport type MountStage = \"stop intake\" | \"close transports\";\n\n/** A mount context gives each handler the signals of the shutdown, the lifecycle and the time of a retry. */\nexport interface MountContext {\n /** This signal aborts when the intake stops. A long stream ends in its own protocol at it. */\n readonly intake: AbortSignal;\n /** This signal aborts at the cooperative abort of the drain, or at the close. The work in flight stops at it. */\n readonly signal: AbortSignal;\n /** This lifecycle is the lifecycle that the transport got at its start, or null before the start. */\n readonly life: Lifecycle | null;\n /** This time is the knob `server_retry_after`: the `Retry-After` of each 503 of the handlers. */\n readonly retryAfter: Quantity;\n /**\n * This function tells if a response of a handler can keep its connection open, as the transport\n * decides it. The decision is the option `keepAlive` or `life.keepAlive()`, while the intake is\n * open. Without this function, a handler reads `life.keepAlive()`.\n */\n readonly keepAlive?: (() => boolean) | undefined;\n}\n\n/**\n * A request handler answers a request and gives true, or it gives false and does not touch the\n * response. Then the next handler gets the request. `until` tells when the handler stops.\n */\nexport interface RequestHandler {\n (req: IncomingMessage, res: ServerResponse, context: MountContext): boolean | Promise<boolean>;\n readonly until?: MountStage | undefined;\n}\n\ntype UpgradeArgs = ServerEventMap[\"upgrade\"];\n\n/** An upgrade socket is the stream of an upgraded connection, as the `upgrade` event of Node gives it. */\nexport type UpgradeSocket = UpgradeArgs[1];\n\n/** An upgrade handler takes an upgraded connection, for example a WebSocket server in its `noServer` mode. */\nexport interface UpgradeHandler {\n (req: IncomingMessage, socket: UpgradeSocket, head: UpgradeArgs[2], context: MountContext): void;\n readonly until?: MountStage | undefined;\n}\n\n/** An upgrade match is a path, without its query, or a function that tells if a handler takes a request. */\nexport type UpgradeMatch = string | ((req: IncomingMessage) => boolean);\n\n/** These options change one mount. */\nexport interface MountOptions {\n /**\n * This stage is when the mount stops. Without it, the stage of the handler applies, and then\n * `stop intake`. A mount until `close transports` keeps the listener open through the drain.\n */\n readonly until?: MountStage | undefined;\n}\n\n/**\n * An edge server is the server of a transport: a server of `node:http`, or a server of `node:http2`\n * without TLS (h2c, from `http2.createServer()`).\n */\nexport type EdgeServer = Server | Http2Server;\n\n/** These options make an HTTP transport. */\nexport interface HttpTransportOptions<S extends EdgeServer = Server> {\n /**\n * These are the listen options of `start()`, or a function that makes the server listen. Without\n * them, `start()` takes a server that listens already.\n */\n readonly listen?: ListenOptions | ((server: S) => Promise<void> | void) | undefined;\n /** This clock is the clock of the lifecycle. The deadline of the drain and the sweep use it. */\n readonly clock?: Clock | undefined;\n /**\n * This function tells if a response can keep its connection open. Without it, the transport reads\n * `life.keepAlive()` of the lifecycle of its start. The transport reads it when the headers of\n * each response go. On HTTP/1.1, false gives `Connection: close`. On HTTP/2, false gives a GOAWAY\n * on the session of the response.\n */\n readonly keepAlive?: (() => boolean) | undefined;\n /** This function receives each error of a handler. The transport then answers 500, or it destroys the response. */\n readonly onError?: ((error: unknown, req: IncomingMessage) => void) | undefined;\n /**\n * With this call context, each handler runs in the context of the headers of its request. The context\n * has the trace of `traceparent`, and the baggage of a trusted request. `callContext` of the entry `/otel` gives one.\n */\n readonly callContext?: CallContext | undefined;\n /**\n * This function tells if the baggage of a request is trusted, for example after a token check. The\n * default trusts no request: each request joins the trace of its caller, and its baggage is dropped.\n */\n readonly trustBaggage?: ((req: IncomingMessage) => boolean) | undefined;\n}\n\n/** An HTTP transport is a server of `node:http` or `node:http2` as a transport of the lifecycle, with a list of mounts on its listener. */\nexport interface HttpTransport<S extends EdgeServer = Server> extends TransportImpl {\n readonly server: S;\n /** These knobs go to the declaration of the server: the knobs of the caller, the hint and the buffer. */\n readonly knobs: HttpTransportKnobs;\n /** This method adds a request handler at the end of the list, and gives the function that removes it. */\n mount(handler: RequestHandler, options?: MountOptions): () => void;\n /** This method adds an upgrade handler for a path, and gives the function that removes it. A server of HTTP/2 has no upgrade, thus it refuses the handler. */\n upgrade(match: UpgradeMatch, handler: UpgradeHandler, options?: MountOptions): () => void;\n /** This count is the number of open connections, idle connections and upgraded connections too. On HTTP/2, a connection is the socket of a session. */\n readonly connections: number;\n /** This flag tells if the transport stopped its intake. */\n readonly intakeStopped: boolean;\n}\n\ninterface RequestMount {\n readonly handler: RequestHandler;\n readonly until: MountStage;\n}\n\ninterface UpgradeMount {\n readonly matches: (req: IncomingMessage) => boolean;\n readonly handler: UpgradeHandler;\n readonly until: MountStage;\n}\n\n/** This function gives the path of a request target, without its query and fragment. */\nexport const pathOf = (url: string | undefined): string => {\n const raw = url ?? \"/\";\n const end = raw.search(/[?#]/);\n const path = end === -1 ? raw : raw.slice(0, end);\n if (path.startsWith(\"/\")) return path;\n // an absolute target, as a proxy sends it\n try {\n return new URL(raw).pathname;\n } catch {\n return path;\n }\n};\n\n/** This function gives a knob in milliseconds, or infinity for a time without a bound. */\nconst millisecondsOf = (knobs: Readonly<Record<string, Extent | undefined>>, name: string, owner = \"httpTransport\"): number =>\n knobMilliseconds(knobs, name, owner);\n\n/**\n * This function gives the `Retry-After` of the knob `server_retry_after`, in whole seconds, rounded\n * up. The knob is necessary, and it has a bound.\n */\nexport const retryAfterOf = (knobs: Readonly<Record<string, Extent | undefined>>, owner: string): string => {\n const retryAfter = millisecondsOf(knobs, \"server_retry_after\", owner);\n if (!Number.isFinite(retryAfter)) throw new Error(\"the knob server_retry_after has no bound: a Retry-After needs a time\");\n return String(Math.ceil(retryAfter / 1000));\n};\n\n/**\n * This function gives the backlog of listen(2) from the knob `server_listen_backlog`, or undefined without the\n * knob. The backlog is a whole count of 0 or more. A backlog of 0 is valid: the queue then holds one connection.\n */\nexport const backlogOf = (knobs: Readonly<Record<string, Extent | undefined>>, owner: string): number | undefined => {\n const amount = knobs[\"server_listen_backlog\"];\n if (amount === undefined) return undefined;\n if (!convertible(amount.unit, \"count\")) throw new Error(\"the knob server_listen_backlog is not a count\");\n if (amount.value === \"infinite\") throw new Error(`the knob server_listen_backlog of ${owner} has no bound: listen(2) takes a whole count`);\n const value = valueIn(amount, \"count\");\n if (!(Number.isInteger(value) && value >= 0)) throw new Error(`the knob server_listen_backlog is ${value}, not a whole count of 0 or more`);\n // Node calls listen(2) with `backlog || 511` (lib/net.js of Node 24.21.0, line 2325), thus a backlog of 0 is 511\n if (value === 0)\n throw new Error(`the knob server_listen_backlog of ${owner} is 0, and Node gives listen(2) 511 for 0: the transport cannot ask for 0`);\n return value;\n};\n\n/** This function tells if the headers of a call of `writeHead` name a header, an object or a flat list of names and values. */\nconst names = (headers: unknown, name: string): boolean => {\n if (Array.isArray(headers)) return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === name);\n return typeof headers === \"object\" && headers !== null && Object.keys(headers).some((key) => key.toLowerCase() === name);\n};\n\n/** This function gives the headers of a call of `writeHead` without one header. */\nconst without = (headers: unknown, name: string): unknown => {\n if (Array.isArray(headers)) {\n const kept: unknown[] = [];\n for (let at = 0; at + 1 < headers.length; at += 2)\n if (String(headers[at]).toLowerCase() !== name) kept.push(headers[at], headers[at + 1]);\n return kept;\n }\n if (typeof headers !== \"object\" || headers === null) return headers;\n return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== name));\n};\n\n/**\n * This function applies the rule of `Retry-After` to a call of `writeHead`, and gives its arguments.\n * A 503 without `Retry-After` gets the time of `server_retry_after` (RFC 9110). A 500 loses each\n * `Retry-After`, from the call and from the response.\n */\nconst retryRule = (res: ServerResponse, args: unknown[], retryAfter: string): unknown[] => {\n const status = typeof args[0] === \"number\" ? args[0] : res.statusCode;\n const at = typeof args[1] === \"string\" ? 2 : 1;\n if (status === 503 && !res.hasHeader(\"retry-after\") && !names(args[at], \"retry-after\")) res.setHeader(\"retry-after\", retryAfter);\n if (status !== 500) return args;\n res.removeHeader(\"retry-after\");\n if (!names(args[at], \"retry-after\")) return args;\n const given = [...args];\n given[at] = without(args[at], \"retry-after\");\n return given;\n};\n\nconst STATUS_TEXT: Readonly<Record<number, string>> = { 404: \"Not Found\", 500: \"Internal Server Error\", 503: \"Service Unavailable\" };\n\n/** This function tells if an edge server is a server of `node:http2`. A server of `node:http` has `closeIdleConnections`, and one of HTTP/2 has none. */\nconst isHttp2 = (server: EdgeServer): server is Http2Server => typeof (server as Partial<Server>).closeIdleConnections !== \"function\";\n\n/** This function gives the session of HTTP/2 of a response, or undefined for a response of HTTP/1.1. */\nconst sessionOf = (res: ServerResponse): Http2Session | undefined => (res as unknown as Partial<Http2ServerResponse>).stream?.session;\n\n/** This function tells if a response is destroyed. A response of HTTP/2 tells it through its stream. */\nconst destroyed = (res: ServerResponse): boolean =>\n res.destroyed === true || (res as unknown as Partial<Http2ServerResponse>).stream?.destroyed === true;\n\n/** This function tells if the headers of a call of `writeHead` give `Connection: close`. */\nconst closes = (headers: unknown): boolean => {\n if (Array.isArray(headers))\n return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === \"connection\" && String(headers[at + 1]).toLowerCase() === \"close\");\n if (typeof headers !== \"object\" || headers === null) return false;\n return Object.entries(headers).some(([key, value]) => key.toLowerCase() === \"connection\" && String(value).toLowerCase() === \"close\");\n};\n\n/**\n * This function sends GOAWAY on a session of HTTP/2, once. `close()` of Node sends it with the last\n * stream that the server took. Each stream up to that one ends as usual. Then the session closes.\n * The client sends each later stream again on a new connection, because the server did not take it.\n */\nconst goaway = (session: Http2Session): void => {\n if (!session.closed && !session.destroyed) session.close();\n};\n\n/**\n * This function makes a server of `node:http` or `node:http2` a transport of the lifecycle (S6 A8 and\n * A13). It is not a framework: it has no routes, no body parser and no middleware.\n * - The count of work in flight comes from events: each response until its `close`, and each upgraded\n * connection until its `close`.\n * - `stopIntake` closes the listener, and new connections get a refusal. It closes the idle connections\n * at once and at each `server_idle_sweep_interval`. Each later response gets `Connection: close`.\n * A connection is not idle while the bytes of its answer go (SYS-33).\n * - `drain` waits until no work is in flight, or until the deadline. It gives the cooperative abort to\n * the handlers through their context. At the deadline, it also waits for each answer that is to come\n * or to go out (SYS-29). The cap of the phase bounds that wait. Answers that did not go out by the\n * cap are not a failure of the phase. A stream outside the lifecycle of the transport does not hold it.\n * - `close` destroys each connection. A second close gives the same promise.\n * - The mounts share one port. The first request handler that gives true answers. After the stop of\n * the intake, only the mounts until `close transports` answer, and each other request gets a 503.\n * - HTTP/2 has no `Connection` header (RFC 9113, section 8.2.2). Thus a close of a connection is a\n * GOAWAY on its session. Each handler gets the request and the response of the compatibility API of\n * `node:http2`. They have the parts of the API that the handlers of this entry use. A handler that\n * gives `Connection: close` gets a GOAWAY. The stop of the intake sends GOAWAY on each session, and\n * the close destroys each session.\n */\nexport const httpTransport = <S extends EdgeServer = Server>(edge: S, knobs: HttpKnobs, options: HttpTransportOptions<S> = {}): HttpTransport<S> => {\n // the events and the listener are those of net.Server on each kind of server\n const server = edge as unknown as Server;\n const h2 = isHttp2(edge) ? edge : null;\n const clock = options.clock ?? realClock;\n const idleClose = millisecondsOf(knobs, \"server_idle_close\");\n const sweepEvery = millisecondsOf(knobs, \"server_idle_sweep_interval\");\n if (sweepEvery === 0)\n throw new Error(\"the knob server_idle_sweep_interval is zero: a sweep needs an interval above zero\");\n const retryAfterHeader = retryAfterOf(knobs, \"httpTransport\");\n const backlog = backlogOf(knobs, \"httpTransport\");\n if (backlog !== undefined && (options.listen === undefined || typeof options.listen === \"function\"))\n throw new Error(\"the knob server_listen_backlog needs the listen options of the transport: the transport does not make this server listen\");\n if (backlog !== undefined && typeof options.listen === \"object\" && options.listen.backlog !== undefined)\n throw new Error(\"the backlog is in the knob server_listen_backlog and in the listen options: give it once, as the knob\");\n for (const derived of [\"server_idle_close_hint\", \"server_idle_close_buffer\"])\n if ((knobs as Readonly<Record<string, Extent | undefined>>)[derived] !== undefined)\n throw new Error(`the knob ${derived} comes from the transport: give only server_idle_close`);\n if (server.listenerCount(\"request\") > 0 || server.listenerCount(\"upgrade\") > 0)\n throw new Error(\"the server has a request or upgrade listener of its own: mount it as a handler\");\n // Node closes an idle connection at keepAliveTimeout + keepAliveTimeoutBuffer, and its hint is\n // keepAliveTimeout. The buffer stays, thus the hint is less than the real close. An older Node has no\n // buffer. A session of HTTP/2 closes at the timeout of the server, with no buffer and no hint\n const buffer = h2 === null ? ((server as { keepAliveTimeoutBuffer?: number }).keepAliveTimeoutBuffer ?? 0) : 0;\n if (h2 !== null && idleClose === 0)\n throw new Error(\"the knob server_idle_close is 0 ms: the timeout of a session of HTTP/2 needs a time above zero\");\n if (h2 === null && Number.isFinite(idleClose) && idleClose <= buffer)\n throw new Error(\n `the knob server_idle_close is ${idleClose} ms, at or below the keepAliveTimeoutBuffer of the server, ${buffer} ms: ` +\n \"the server closes an idle connection at keepAliveTimeout + keepAliveTimeoutBuffer\",\n );\n // 0 stops the keep-alive timer and the hint in Node, and the timeout of each session of HTTP/2\n if (h2 === null) server.keepAliveTimeout = Number.isFinite(idleClose) ? idleClose - buffer : 0;\n else h2.setTimeout(Number.isFinite(idleClose) ? idleClose : 0);\n const declared: HttpTransportKnobs = {\n ...knobs,\n server_idle_close_hint:\n h2 === null && Number.isFinite(idleClose)\n ? { value: Math.floor(server.keepAliveTimeout / 1000), unit: \"s\" }\n : { value: \"infinite\", unit: \"s\" },\n server_idle_close_buffer: { value: buffer, unit: \"ms\" },\n };\n\n const requestMounts: RequestMount[] = [];\n const upgradeMounts: UpgradeMount[] = [];\n const responses = new Set<ServerResponse>();\n const upgraded = new Set<UpgradeSocket>();\n const sockets = new Set<Socket>();\n // the sessions of HTTP/2: the stop of the intake sends GOAWAY on each one, and the close destroys each one\n const sessions = new Set<Http2Session>();\n // the check of each drain: it ends its drain when nothing holds it\n const drainers = new Set<() => void>();\n const closedWaiters = new Set<() => void>();\n const intake = new AbortController();\n const cooperative = new AbortController();\n // the lifecycle comes at the start, thus the context reads it at each request\n let life: Lifecycle | null = null;\n const context: MountContext = {\n intake: intake.signal,\n signal: cooperative.signal,\n get life() {\n return life;\n },\n retryAfter: knobs.server_retry_after,\n // the option keepAlive decides for each handler too, thus a handled route does not close by itself\n keepAlive: () => keepsAlive(),\n };\n let intakeOpen = true;\n let listenerOpen = server.listening;\n let serverClosed = !server.listening;\n let sweep: Cancel | null = null;\n let closing: Promise<void> | null = null;\n\n const inFlight = (): number => responses.size + upgraded.size;\n /**\n * This function gives what holds a drain after its deadline. An answer is unflushed when its handler\n * ended it and its bytes did not all go. It is unflushed too while `writeOutcome` waits for a client\n * that does not read. A call runs while `writeOutcome` waits for the end of its request, which the\n * cut of the drain gives. Only a stream of the lifecycle of the transport counts, because only its\n * cut ends the stream. A response that is open for another reason does not hold the drain.\n */\n const lateHold = (): LateHold & { readonly outside: number } => {\n let running = 0;\n let unflushed = 0;\n let outside = 0;\n for (const res of responses) {\n if (destroyed(res)) continue;\n if (res.writableEnded) {\n if (!res.writableFinished) unflushed += 1;\n continue;\n }\n const owner = answerOwner(res);\n if (owner === undefined) continue;\n if (life === null || owner !== life) outside += 1;\n else if (res.writableNeedDrain) unflushed += 1;\n else running += 1;\n }\n return { running, unflushed, outside };\n };\n const answering = (): boolean => {\n const hold = lateHold();\n return hold.running + hold.unflushed > 0;\n };\n const report = (error: unknown, req: IncomingMessage): void => {\n try {\n options.onError?.(error, req);\n } catch {\n // an error of the error hook does not stop the transport\n }\n };\n const settled = (): void => {\n for (const check of [...drainers]) check();\n if (closing !== null && inFlight() === 0 && sockets.size === 0 && serverClosed)\n for (const done of [...closedWaiters]) done();\n };\n // before its start, a transport has no lifecycle: a server that listens already keeps its connections\n const keepsAlive = (): boolean => intakeOpen && (options.keepAlive?.() ?? life?.keepAlive() ?? true);\n const live = <T extends { readonly until: MountStage }>(mounts: readonly T[]): T[] =>\n intakeOpen ? [...mounts] : mounts.filter((mount) => mount.until === \"close transports\");\n const throughDrain = (): boolean =>\n requestMounts.some((mount) => mount.until === \"close transports\") ||\n upgradeMounts.some((mount) => mount.until === \"close transports\");\n const closeListener = (): void => {\n if (!listenerOpen) return;\n listenerOpen = false;\n server.close();\n };\n // a session of HTTP/2 ends its streams after a GOAWAY, thus each session gets it, an idle one or not\n const closeIdleConnections = (): void => {\n if (h2 === null) server.closeIdleConnections();\n else for (const session of sessions) goaway(session);\n };\n const startSweep = (): void => {\n if (!Number.isFinite(sweepEvery) || closing !== null) return;\n sweep = clock.after(sweepEvery, () => {\n sweep = null;\n if (closing !== null) return;\n closeIdleConnections();\n startSweep();\n });\n // the listener keeps the process alive, thus the sweep does not (SYS-126)\n sweep.unref?.();\n };\n\n /**\n * This function watches the headers of each response when they go, whatever wrote them. Each 503\n * gets `Retry-After`, and a 500 gets none. The response closes its connection while the transport\n * cannot keep it. On HTTP/2, the `Connection` header goes away, and a close is a GOAWAY on the session.\n */\n const watchHeaders = (res: ServerResponse): void => {\n const writeHead = res.writeHead as (...args: unknown[]) => ServerResponse;\n res.writeHead = ((...args: unknown[]): ServerResponse => {\n if (res.headersSent) return writeHead.apply(res, args);\n const session = sessionOf(res);\n if (session !== undefined) {\n const at = typeof args[1] === \"string\" ? 2 : 1;\n const asked = String(res.getHeader(\"connection\") ?? \"\").toLowerCase() === \"close\" || closes(args[at]);\n res.removeHeader(\"connection\");\n const given = [...args];\n if (names(args[at], \"connection\")) given[at] = without(args[at], \"connection\");\n if (asked || !keepsAlive()) goaway(session);\n return writeHead.apply(res, retryRule(res, given, retryAfterHeader));\n }\n if (!keepsAlive()) {\n res.shouldKeepAlive = false;\n res.setHeader(\"connection\", \"close\");\n }\n return writeHead.apply(res, retryRule(res, args, retryAfterHeader));\n }) as ServerResponse[\"writeHead\"];\n };\n const answer = (res: ServerResponse, status: number, headers: Readonly<Record<string, string>> = {}): void => {\n if (res.headersSent) {\n res.destroy();\n return;\n }\n const body = STATUS_TEXT[status] ?? \"\";\n res.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\", \"content-length\": String(Buffer.byteLength(body)), ...headers });\n res.end(body);\n };\n const refuse = (res: ServerResponse): void => answer(res, 503, { \"retry-after\": retryAfterHeader, connection: \"close\" });\n\n const route = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const mounts = live(requestMounts);\n try {\n for (const mount of mounts) {\n const given = mount.handler(req, res, context);\n const taken = typeof given === \"boolean\" ? given : await given;\n // a handler that wrote its response took the request, whatever it gave\n if (taken || res.headersSent || res.writableEnded) return;\n }\n } catch (error) {\n report(error, req);\n if (!res.writableEnded) answer(res, 500);\n return;\n }\n if (intakeOpen) answer(res, 404);\n else refuse(res);\n };\n\n // each handler runs in the context of the headers of its request, when the options give a call context\n const callContext = options.callContext;\n const trustBaggage = options.trustBaggage ?? (() => false);\n const inCall = <T>(req: IncomingMessage, fn: () => T): T => (callContext === undefined ? fn() : callContext.run(req.headers, trustBaggage(req), fn));\n\n const onRequest = (req: IncomingMessage, res: ServerResponse): void => {\n responses.add(res);\n // the bytes of an answer went: a drain after its deadline can end\n res.once(\"finish\", settled);\n res.once(\"close\", () => {\n responses.delete(res);\n settled();\n });\n watchHeaders(res);\n void inCall(req, () => route(req, res));\n };\n\n const onUpgrade = (req: IncomingMessage, socket: UpgradeSocket, head: UpgradeArgs[2]): void => {\n socket.on(\"error\", () => {});\n const mount = live(upgradeMounts).find((each) => each.matches(req));\n if (mount === undefined) {\n const status = intakeOpen ? 404 : 503;\n const extra = intakeOpen ? \"\" : `Retry-After: ${retryAfterHeader}\\r\\n`;\n socket.end(`HTTP/1.1 ${status} ${STATUS_TEXT[status]!}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n${extra}\\r\\n`);\n return;\n }\n if (socket.destroyed) return;\n upgraded.add(socket);\n socket.once(\"close\", () => {\n upgraded.delete(socket);\n settled();\n });\n try {\n inCall(req, () => mount.handler(req, socket, head, context));\n } catch (error) {\n report(error, req);\n socket.destroy();\n }\n };\n\n const onConnection = (socket: Socket): void => {\n sockets.add(socket);\n socket.once(\"close\", () => {\n sockets.delete(socket);\n settled();\n });\n };\n\n /**\n * Node counts a connection idle at the `end()` of its response, also while the bytes of the body\n * still go. Then `closeIdleConnections` destroys the socket and cuts the answer (SYS-33). This\n * method replaces it on the server, thus `server.close()` uses it too. Node keeps the socket of\n * a response that did not end. Thus the method shows each answer whose bytes did not go as not\n * ended, for the time of the call.\n */\n if (h2 === null) {\n const closeIdle = server.closeIdleConnections;\n server.closeIdleConnections = function closeIdleConnections(this: Server): void {\n const going = [...responses].filter((res) => res.writableEnded && !res.writableFinished && !res.destroyed);\n for (const res of going) res.finished = false;\n try {\n closeIdle.call(this);\n } finally {\n for (const res of going) res.finished = true;\n }\n };\n }\n\n server.on(\"request\", onRequest);\n if (h2 === null) server.on(\"upgrade\", onUpgrade);\n else\n h2.on(\"session\", (session) => {\n sessions.add(session);\n session.once(\"close\", () => {\n sessions.delete(session);\n settled();\n });\n });\n server.on(\"connection\", onConnection);\n server.on(\"listening\", () => {\n listenerOpen = true;\n serverClosed = false;\n });\n server.on(\"close\", () => {\n listenerOpen = false;\n serverClosed = true;\n settled();\n });\n\n const remover = <T>(list: T[], entry: T) => (): void => {\n const at = list.indexOf(entry);\n if (at >= 0) list.splice(at, 1);\n // the last mount through the drain went: the listener closes as the stop of the intake asks\n if (!intakeOpen && closing === null && !throughDrain()) closeListener();\n };\n\n return {\n server: edge,\n knobs: declared,\n get connections() {\n return sockets.size;\n },\n get intakeStopped() {\n return !intakeOpen;\n },\n mount(handler, mountOptions = {}) {\n const entry: RequestMount = { handler, until: mountOptions.until ?? handler.until ?? \"stop intake\" };\n requestMounts.push(entry);\n return remover(requestMounts, entry);\n },\n upgrade(match, handler, mountOptions = {}) {\n if (h2 !== null) throw new Error(\"a server of HTTP/2 has no upgrade: mount a request handler\");\n const matches = typeof match === \"string\" ? (req: IncomingMessage) => pathOf(req.url) === match : match;\n const entry: UpgradeMount = { matches, handler, until: mountOptions.until ?? handler.until ?? \"stop intake\" };\n upgradeMounts.push(entry);\n return remover(upgradeMounts, entry);\n },\n async start(_signal, given) {\n life = given;\n if (closing !== null) throw new Error(\"the transport closed: a closed transport does not start again\");\n // a listener that another owner adds after the transport answers too, thus the start refuses it\n if (server.listenerCount(\"request\") > 1 || server.listenerCount(\"upgrade\") > 1)\n throw new Error(\"the server has a request or upgrade listener of its own: mount it as a handler\");\n if (server.listening) return;\n const listen = options.listen;\n if (listen === undefined) throw new Error(\"the server does not listen, and the transport has no listen options\");\n if (typeof listen === \"function\") {\n await listen(edge);\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const failed = (error: Error): void => {\n server.off(\"listening\", listened);\n reject(error);\n };\n const listened = (): void => {\n server.off(\"error\", failed);\n resolve();\n };\n server.once(\"error\", failed);\n server.once(\"listening\", listened);\n server.listen(backlog === undefined ? listen : { ...listen, backlog });\n });\n },\n stopIntake() {\n if (!intakeOpen) return;\n intakeOpen = false;\n intake.abort(new Error(\"the transport stopped its intake\"));\n if (!throughDrain()) closeListener();\n closeIdleConnections();\n startSweep();\n },\n drain(deadline, signal) {\n const abort = (): void => {\n if (!cooperative.signal.aborted) cooperative.abort(signal.reason);\n };\n if (signal.aborted) abort();\n else signal.addEventListener(\"abort\", abort, { once: true });\n // nothing in flight: the drain ends at once, with no timer\n if (inFlight() === 0) {\n signal.removeEventListener(\"abort\", abort);\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n let unwatch: () => void = () => {};\n let unhold: () => void = () => {};\n let late = false;\n let ended = false;\n // before the deadline, the work in flight holds the drain. After it, only an answer to come or to go out holds it\n const check = (): void => {\n if (ended || (inFlight() > 0 && (!late || answering()))) return;\n ended = true;\n drainers.delete(check);\n cancel();\n unwatch();\n unhold();\n signal.removeEventListener(\"abort\", abort);\n resolve();\n };\n // the cut of the requests comes at the same time, before or after this timer: the drain waits for its answers in each case\n const reached = (): void => {\n late = true;\n unwatch = watchAnswers(check);\n // the lifecycle reads the hold at the cap: answers that do not go out are not a failure of the phase\n if (life !== null) {\n unhold = holdLate(life, () => {\n const { running, unflushed } = lateHold();\n return { running, unflushed };\n });\n // a stream outside the lifecycle does not hold the drain: the record of the phase gives the count\n noteOutside(life, lateHold().outside);\n }\n check();\n };\n drainers.add(check);\n if (deadline <= clock.now()) reached();\n // the drain awaits its deadline, thus this timer keeps the process alive (SYS-126)\n else cancel = clock.after(deadline - clock.now(), reached);\n });\n },\n inFlight,\n close() {\n if (closing !== null) return closing;\n intakeOpen = false;\n if (!intake.signal.aborted) intake.abort(new Error(\"the transport closed\"));\n if (!cooperative.signal.aborted) cooperative.abort(new Error(\"the transport closed\"));\n sweep?.();\n sweep = null;\n closing = new Promise<void>((resolve) => {\n closedWaiters.add(resolve);\n });\n closeListener();\n if (h2 === null) server.closeAllConnections();\n else for (const session of [...sessions]) session.destroy();\n for (const socket of [...upgraded]) socket.destroy();\n for (const socket of [...sockets]) socket.destroy();\n settled();\n return closing;\n },\n };\n};\n"],"mappings":";;;;;;;AA4KA,MAAa,UAAU,QAAoC;CACzD,MAAM,MAAM,OAAO;CACnB,MAAM,MAAM,IAAI,OAAO,MAAM;CAC7B,MAAM,OAAO,QAAQ,KAAK,MAAM,IAAI,MAAM,GAAG,GAAG;CAChD,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CAEjC,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAM,kBAAkB,OAAqD,MAAc,QAAQ,oBACjGA,iBAAiB,OAAO,MAAM,KAAK;;;;;AAMrC,MAAa,gBAAgB,OAAqD,UAA0B;CAC1G,MAAM,aAAa,eAAe,OAAO,sBAAsB,KAAK;CACpE,IAAI,CAAC,OAAO,SAAS,UAAU,GAAG,MAAM,IAAI,MAAM,sEAAsE;CACxH,OAAO,OAAO,KAAK,KAAK,aAAa,GAAI,CAAC;AAC5C;;;;;AAMA,MAAa,aAAa,OAAqD,UAAsC;CACnH,MAAM,SAAS,MAAM;CACrB,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,IAAI,CAAC,YAAY,OAAO,MAAM,OAAO,GAAG,MAAM,IAAI,MAAM,+C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