@operad-io/engine 0.0.0-stage → 0.0.1

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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,668 @@
1
+ /**
2
+ * What a step leaves behind. Every process a step starts carries an
3
+ * environment marker naming the run and the step; children inherit it whatever
4
+ * process group or session they move to. When the step ends, the sweep here
5
+ * finds the live processes of the same user that still carry the marker and
6
+ * stops them the way a group stop does: TERM, a bounded wait, KILL. The same
7
+ * sweep runs at serve start for markers of runs that are no longer active.
8
+ *
9
+ * A process that removes the variable from its own environment is not found.
10
+ * Nothing here runs in the kernel's own process.
11
+ */
12
+
13
+ import { execFile } from "node:child_process";
14
+ import { createHash } from "node:crypto";
15
+ import { existsSync } from "node:fs";
16
+ import { readFile, readdir } from "node:fs/promises";
17
+ import { AsyncLocalStorage } from "node:async_hooks";
18
+ import type { PluginLogger } from "../plugin/types.ts";
19
+ import { createProcessWatch, type ProcessWatch } from "./process-watch.ts";
20
+ import { KILL_GRACE_MS, systemClock, type Clock } from "./process-group.ts";
21
+
22
+ /** The variable that names the run and the step: `<run id>:<step>`. */
23
+ export const MARKER_ENV = "OPERAD_RUN";
24
+
25
+ /** The variable that names the operad home, so two homes never meet. */
26
+ export const MARKER_HOME_ENV = "OPERAD_RUN_HOME";
27
+
28
+ /** The longest a command is shown in a log line. */
29
+ export const COMMAND_WIDTH = 120;
30
+
31
+ /** Who a step is: the run it belongs to, its name, and the home it runs in. */
32
+ export interface StepMarker {
33
+ readonly runId: string;
34
+ readonly step: string;
35
+ readonly home: string;
36
+ }
37
+
38
+ const current = new AsyncLocalStorage<StepMarker>();
39
+
40
+ /** Runs `body` so every process it starts through the platform is marked. */
41
+ export function withStepMarker<T>(marker: StepMarker, body: () => T): T {
42
+ return current.run(marker, body);
43
+ }
44
+
45
+ /** The marker of the step that is running now, if any. */
46
+ export function currentStepMarker(): StepMarker | undefined {
47
+ return current.getStore();
48
+ }
49
+
50
+ function token(text: string): string {
51
+ return text.replace(/\s+/g, "_");
52
+ }
53
+
54
+ /** A short stable name for a home path; it never contains a space. */
55
+ export function homeToken(home: string): string {
56
+ return createHash("sha256").update(home).digest("hex").slice(0, 16);
57
+ }
58
+
59
+ /** The value of `OPERAD_RUN` for a step. */
60
+ export function markerValue(marker: StepMarker): string {
61
+ return `${token(marker.runId)}:${token(marker.step)}`;
62
+ }
63
+
64
+ /** The environment a process of this step gets; empty outside a step. */
65
+ export function markerEnv(
66
+ marker: StepMarker | undefined = currentStepMarker(),
67
+ ): Record<string, string> {
68
+ if (marker === undefined) return {};
69
+ return {
70
+ [MARKER_ENV]: markerValue(marker),
71
+ [MARKER_HOME_ENV]: homeToken(marker.home),
72
+ };
73
+ }
74
+
75
+ /** A live process that carries a marker. */
76
+ export interface MarkedProcess {
77
+ readonly pid: number;
78
+ /** The `OPERAD_RUN` value. */
79
+ readonly marker: string;
80
+ /** The `OPERAD_RUN_HOME` value. */
81
+ readonly home: string;
82
+ readonly command: string;
83
+ }
84
+
85
+ /** Lists the user's live processes that carry a marker. */
86
+ export type ProcessLister = () => Promise<readonly MarkedProcess[]>;
87
+
88
+ const MARKER_PATTERN = new RegExp(`(?:^|\\s)${MARKER_ENV}=(\\S+)`, "g");
89
+ const HOME_PATTERN = new RegExp(`(?:^|\\s)${MARKER_HOME_ENV}=(\\S+)`, "g");
90
+
91
+ /**
92
+ * The last value of a variable in a `ps -E` command column. The environment
93
+ * follows the arguments, so the last match is the real one: an argument that
94
+ * spells `OPERAD_RUN=` cannot override it.
95
+ */
96
+ function lastValue(pattern: RegExp, text: string): string | undefined {
97
+ let value: string | undefined;
98
+ for (const match of text.matchAll(pattern)) value = match[1];
99
+ return value;
100
+ }
101
+
102
+ /** The marker and home a `ps -E` command column carries, or undefined without a marker. */
103
+ export function parseEnvColumn(
104
+ text: string,
105
+ ): { readonly marker: string; readonly home: string } | undefined {
106
+ const marker = lastValue(MARKER_PATTERN, text);
107
+ if (marker === undefined) return undefined;
108
+ return { marker, home: lastValue(HOME_PATTERN, text) ?? "" };
109
+ }
110
+
111
+ function run(command: string, args: readonly string[]): Promise<{ pid: number | undefined; out: string }> {
112
+ return new Promise((resolve) => {
113
+ const child = execFile(
114
+ command,
115
+ [...args],
116
+ {
117
+ maxBuffer: 512 * 1024 * 1024,
118
+ encoding: "utf8",
119
+ env: { ...process.env, TZ: "UTC", LC_ALL: "C" },
120
+ },
121
+ (error, stdout) => resolve({ pid: child.pid, out: error === null ? stdout : "" }),
122
+ );
123
+ });
124
+ }
125
+
126
+ /** macOS and the BSDs: `ps -E` shows the environment of the user's own processes. */
127
+ async function listWithPs(): Promise<readonly MarkedProcess[]> {
128
+ const uid = String(process.getuid?.() ?? "");
129
+ const who = uid === "" ? ["-x"] : ["-U", uid];
130
+ const withEnv = await run("ps", [...who, "-ww", "-E", "-o", "pid=,command="]);
131
+ const found = new Map<number, { marker: string; home: string }>();
132
+ for (const line of withEnv.out.split("\n")) {
133
+ const match = /^\s*(\d+)\s(.*)$/.exec(line);
134
+ if (match === null) continue;
135
+ const carried = parseEnvColumn(match[2] ?? "");
136
+ if (carried === undefined) continue;
137
+ found.set(Number(match[1]), carried);
138
+ }
139
+ if (found.size === 0) return [];
140
+ const plain = await run("ps", [...who, "-ww", "-o", "pid=,command="]);
141
+ const commands = new Map<number, string>();
142
+ for (const line of plain.out.split("\n")) {
143
+ const match = /^\s*(\d+)\s(.*)$/.exec(line);
144
+ if (match !== null) commands.set(Number(match[1]), match[2] ?? "");
145
+ }
146
+ const own = new Set([process.pid, withEnv.pid, plain.pid]);
147
+ const processes: MarkedProcess[] = [];
148
+ for (const [pid, value] of found) {
149
+ if (own.has(pid)) continue;
150
+ const command = commands.get(pid);
151
+ // Gone between the two listings, or the listing's own helper.
152
+ if (command === undefined) continue;
153
+ processes.push({ pid, ...value, command });
154
+ }
155
+ return processes;
156
+ }
157
+
158
+ /** Linux: `/proc/<pid>/environ` of the user's own processes. */
159
+ async function listWithProc(): Promise<readonly MarkedProcess[]> {
160
+ const processes: MarkedProcess[] = [];
161
+ let names: string[];
162
+ try {
163
+ names = await readdir("/proc");
164
+ } catch {
165
+ return [];
166
+ }
167
+ for (const name of names) {
168
+ if (!/^\d+$/.test(name)) continue;
169
+ const pid = Number(name);
170
+ if (pid === process.pid) continue;
171
+ let environ: string;
172
+ try {
173
+ environ = await readFile(`/proc/${name}/environ`, "utf8");
174
+ } catch {
175
+ continue; // another user's process, or one that just ended
176
+ }
177
+ let marker: string | undefined;
178
+ let home = "";
179
+ for (const entry of environ.split("\0")) {
180
+ if (entry.startsWith(`${MARKER_ENV}=`)) marker = entry.slice(MARKER_ENV.length + 1);
181
+ else if (entry.startsWith(`${MARKER_HOME_ENV}=`)) home = entry.slice(MARKER_HOME_ENV.length + 1);
182
+ }
183
+ if (marker === undefined) continue;
184
+ let command = "";
185
+ try {
186
+ command = (await readFile(`/proc/${name}/cmdline`, "utf8")).split("\0").join(" ").trim();
187
+ } catch {
188
+ continue;
189
+ }
190
+ processes.push({ pid, marker, home, command });
191
+ }
192
+ return processes;
193
+ }
194
+
195
+ /** The lister for this system. */
196
+ export const listMarkedProcesses: ProcessLister = () =>
197
+ existsSync("/proc/self/environ") ? listWithProc() : listWithPs();
198
+
199
+ /** Sends one signal to one process. False when it could not. */
200
+ function signalProcess(pid: number, signal: NodeJS.Signals): boolean {
201
+ try {
202
+ process.kill(pid, signal);
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+
209
+ /** One live process of the user, from the process table. */
210
+ export interface ProcessRow {
211
+ readonly pid: number;
212
+ readonly ppid: number;
213
+ readonly pgid: number;
214
+ /** When it started, in whole seconds; with the pid it names one process. */
215
+ readonly startSec: number;
216
+ readonly command: string;
217
+ }
218
+
219
+ /** Reads the user's process table. */
220
+ export type ProcessTable = () => Promise<readonly ProcessRow[]>;
221
+
222
+ const ROW_PATTERN =
223
+ /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3}\s+\S+\s+\S+\s+[\d:]+\s+\d{4})\s+(.*)$/;
224
+
225
+ /** Seconds since the epoch of a `ps` start time (`Mon 9 Nov 00:26:59 2026` or `Mon Nov 9 00:26:59 2026`). */
226
+ export function parseStart(text: string): number {
227
+ const [, first = "", second = "", time = "", year = ""] = text.trim().split(/\s+/);
228
+ const numeric = /^\d+$/.test(first);
229
+ const day = numeric ? first : second;
230
+ const month = numeric ? second : first;
231
+ const [hours = 0, minutes = 0, seconds = 0] = time.split(":").map(Number);
232
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
233
+ // `ps` is asked for UTC (see `run`), so the time is read as UTC, whatever zone this process has.
234
+ return Math.floor(Date.UTC(Number(year), months.indexOf(month), Number(day), hours, minutes, seconds) / 1000);
235
+ }
236
+
237
+ /** The table of this user's processes, by `ps`; it works the same on macOS and Linux. */
238
+ export const readProcessTable: ProcessTable = async () => {
239
+ const uid = String(process.getuid?.() ?? "");
240
+ const who = uid === "" ? ["-x"] : ["-U", uid];
241
+ const listing = await run("ps", [...who, "-ww", "-o", "pid=,ppid=,pgid=,lstart=,command="]);
242
+ const rows: ProcessRow[] = [];
243
+ for (const line of listing.out.split("\n")) {
244
+ const match = ROW_PATTERN.exec(line);
245
+ if (match === null) continue;
246
+ if (Number(match[1]) === listing.pid) continue;
247
+ rows.push({
248
+ pid: Number(match[1]),
249
+ ppid: Number(match[2]),
250
+ pgid: Number(match[3]),
251
+ startSec: parseStart(match[4] ?? ""),
252
+ command: match[5] ?? "",
253
+ });
254
+ }
255
+ return rows;
256
+ };
257
+
258
+ function identity(row: { readonly pid: number; readonly startSec: number }): string {
259
+ return `${row.pid}@${row.startSec}`;
260
+ }
261
+
262
+ /** The pids of this process and of everything above it: never swept. */
263
+ function protectedPids(rows: readonly ProcessRow[]): Set<number> {
264
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
265
+ const kept = new Set<number>([process.pid, process.ppid]);
266
+ let at = byPid.get(process.pid)?.ppid;
267
+ while (at !== undefined && at > 1 && !kept.has(at)) {
268
+ kept.add(at);
269
+ at = byPid.get(at)?.ppid;
270
+ }
271
+ return kept;
272
+ }
273
+
274
+ /** A process that leads its own process group, seen while it lived. */
275
+ interface Leader {
276
+ readonly startSec: number;
277
+ /** When it was seen to be gone, in seconds; undefined while it lives. */
278
+ goneSec: number | undefined;
279
+ }
280
+
281
+ /**
282
+ * Follows the processes a step started, by the process table instead of the
283
+ * environment. macOS withholds the environment of Apple's own binaries
284
+ * (`/bin/sh`, `/bin/bash`, `/bin/zsh`), so a shell loop a command left in the
285
+ * background carries the marker without showing it. It is seen while it has a
286
+ * parent: a process seen below the step stays on the list when its parent ends
287
+ * and it moves to init. A command's shell leads a process group of its own, and
288
+ * what it left behind keeps that group id, so a later member of the group is
289
+ * followed too, as long as it started while the leader lived: a process that
290
+ * got the leader's pid after the leader was gone started later and is not
291
+ * ours.
292
+ *
293
+ * On macOS a `ProcessWatch` feeds it within milliseconds of each fork, which
294
+ * is what catches a shell that ends right after it started its loops.
295
+ */
296
+ export class StepTracker {
297
+ private readonly roots = new Set<number>();
298
+ private readonly seen = new Map<string, ProcessRow>();
299
+ private readonly leaders = new Map<number, Leader>();
300
+ private timer: unknown;
301
+ private stopped = false;
302
+ private polling: Promise<void> = Promise.resolve();
303
+ private readonly watcher: ProcessWatch | undefined;
304
+ private readonly now: () => number;
305
+ private readonly uid: number | undefined;
306
+
307
+ constructor(options: { readonly watcher?: ProcessWatch | undefined; readonly now?: (() => number) | undefined } = {}) {
308
+ this.watcher = options.watcher;
309
+ this.now = options.now ?? (() => Math.floor(Date.now() / 1000));
310
+ this.uid = process.getuid?.();
311
+ }
312
+
313
+ /** A process the step started itself: the sentinel that leads its group. */
314
+ addRoot(pid: number): void {
315
+ this.roots.add(pid);
316
+ this.follow(pid);
317
+ }
318
+
319
+ /** Whether a live process is one the step started. */
320
+ has(row: ProcessRow): boolean {
321
+ if (this.seen.has(identity(row))) return true;
322
+ const leader = this.leaders.get(row.pgid);
323
+ if (leader === undefined || row.pgid <= 1) return false;
324
+ return (
325
+ row.startSec >= leader.startSec &&
326
+ (leader.goneSec === undefined || row.startSec <= leader.goneSec)
327
+ );
328
+ }
329
+
330
+ private remember(row: { readonly pid: number; readonly pgid: number; readonly startSec: number; readonly command?: string }): boolean {
331
+ const id = identity(row);
332
+ if (this.seen.has(id)) return false;
333
+ this.seen.set(id, { command: "", ppid: 0, ...row });
334
+ if (row.pid === row.pgid && !this.leaders.has(row.pgid)) {
335
+ this.leaders.set(row.pgid, { startSec: row.startSec, goneSec: undefined });
336
+ }
337
+ return true;
338
+ }
339
+
340
+ /** Looks at one process and below it, now, through the watch. */
341
+ private follow(pid: number): void {
342
+ const watcher = this.watcher;
343
+ if (watcher === undefined) return;
344
+ if (!watcher.watch(pid)) return;
345
+ const own = watcher.info(pid);
346
+ if (own !== undefined && own.uid === this.uid) this.remember(own);
347
+ // Watched first, listed after: a fork before the watch shows in the list,
348
+ // a fork after it shows as an event.
349
+ for (const kid of watcher.children(pid)) {
350
+ const info = watcher.info(kid);
351
+ if (info === undefined || info.uid !== this.uid) continue;
352
+ if (this.remember(info)) this.follow(kid);
353
+ }
354
+ }
355
+
356
+ /** Reads what the watch has kept: follows the children of what forked. */
357
+ tick(): void {
358
+ const watcher = this.watcher;
359
+ if (watcher === undefined) return;
360
+ const { forked, exited } = watcher.drain();
361
+ for (const pid of forked) this.follow(pid);
362
+ for (const pid of exited) {
363
+ const leader = this.leaders.get(pid);
364
+ if (leader !== undefined && leader.goneSec === undefined) leader.goneSec = this.now();
365
+ }
366
+ }
367
+
368
+ /** Adds what the table shows below the roots, and below what is already followed. */
369
+ observe(rows: readonly ProcessRow[]): void {
370
+ const present = new Set(rows.map(identity));
371
+ for (const [pgid, leader] of this.leaders) {
372
+ const alive = present.has(`${pgid}@${leader.startSec}`);
373
+ if (!alive && leader.goneSec === undefined) leader.goneSec = this.now();
374
+ }
375
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
376
+ let grew = true;
377
+ while (grew) {
378
+ grew = false;
379
+ for (const row of rows) {
380
+ if (this.seen.has(identity(row)) || row.pid === process.pid) continue;
381
+ const parent = byPid.get(row.ppid);
382
+ const below =
383
+ this.roots.has(row.pid) || (parent !== undefined && this.seen.has(identity(parent)));
384
+ if (below && this.remember(row)) grew = true;
385
+ }
386
+ }
387
+ }
388
+
389
+ /** Looks at the table once; calls queue, so two looks never overlap. */
390
+ poll(table: ProcessTable = readProcessTable): Promise<void> {
391
+ this.polling = this.polling.then(async () => {
392
+ this.observe(await table());
393
+ });
394
+ return this.polling;
395
+ }
396
+
397
+ start(clock: Clock = systemClock, table: ProcessTable = readProcessTable): void {
398
+ const again = (): void => {
399
+ if (this.stopped) return;
400
+ this.timer = clock.setTimeout(() => {
401
+ void this.poll(table).then(again, again);
402
+ }, TRACK_MS);
403
+ unref(this.timer);
404
+ };
405
+ if (this.watcher !== undefined) {
406
+ const quick = (): void => {
407
+ if (this.stopped) return;
408
+ this.tick();
409
+ this.quick = clock.setTimeout(quick, WATCH_MS);
410
+ unref(this.quick);
411
+ };
412
+ quick();
413
+ }
414
+ void this.poll(table);
415
+ again();
416
+ }
417
+
418
+ private quick: unknown;
419
+
420
+ stop(clock: Clock = systemClock): void {
421
+ this.stopped = true;
422
+ if (this.timer !== undefined) clock.clearTimeout(this.timer);
423
+ if (this.quick !== undefined) clock.clearTimeout(this.quick);
424
+ }
425
+
426
+ /** Reads the watch a last time and lets it go. */
427
+ finish(): void {
428
+ this.tick();
429
+ this.watcher?.close();
430
+ }
431
+ }
432
+
433
+ /** A step that never ends must not keep its process alive by being looked at. */
434
+ function unref(timer: unknown): void {
435
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
436
+ (timer as { unref(): void }).unref();
437
+ }
438
+ }
439
+
440
+ /** How often the watch is read: a few milliseconds, since reading it is cheap. */
441
+ export const WATCH_MS = 2;
442
+
443
+ /** How often a running step's processes are looked at. */
444
+ export const TRACK_MS = 200;
445
+
446
+ const trackers = new Map<string, StepTracker>();
447
+
448
+ function keyOf(marker: StepMarker): string {
449
+ return `${homeToken(marker.home)}/${markerValue(marker)}`;
450
+ }
451
+
452
+ /**
453
+ * Tells the platform that the running step started a process of its own (the
454
+ * sentinel of a command or of a harness), so its descendants are followed.
455
+ */
456
+ export function trackRoot(pid: number | undefined): void {
457
+ const marker = currentStepMarker();
458
+ if (marker === undefined || pid === undefined) return;
459
+ const tracker = trackers.get(keyOf(marker));
460
+ if (tracker === undefined) return;
461
+ tracker.addRoot(pid);
462
+ void tracker.poll();
463
+ }
464
+
465
+ /** Looks at the table now for every running step. For a test that must not wait for the timer. */
466
+ export async function pollTrackedSteps(table: ProcessTable = readProcessTable): Promise<void> {
467
+ await Promise.all([...trackers.values()].map((tracker) => tracker.poll(table)));
468
+ }
469
+
470
+ export interface ReapOptions {
471
+ /** Which marked processes to stop. */
472
+ readonly select: (found: MarkedProcess) => boolean;
473
+ /** Processes the step's own tracker followed. */
474
+ readonly tracker?: StepTracker | undefined;
475
+ /** Where the line about what was stopped goes. */
476
+ readonly write?: ((text: string) => Promise<unknown>) | undefined;
477
+ /** What the first line says the processes were left behind by. */
478
+ readonly what: string;
479
+ readonly clock?: Clock | undefined;
480
+ readonly list?: ProcessLister | undefined;
481
+ readonly table?: ProcessTable | undefined;
482
+ readonly graceMs?: number | undefined;
483
+ }
484
+
485
+ /** The part of a stopped process the logs show. */
486
+ export interface Reaped {
487
+ readonly pid: number;
488
+ readonly command: string;
489
+ }
490
+
491
+ /** `pid: command`, the command cut to `COMMAND_WIDTH` characters. */
492
+ export function describeProcess(found: Reaped): string {
493
+ const command = found.command.replace(/\s+/g, " ");
494
+ const cut =
495
+ command.length > COMMAND_WIDTH ? `${command.slice(0, COMMAND_WIDTH - 1)}…` : command;
496
+ return `${found.pid}: ${cut}`;
497
+ }
498
+
499
+ /** The most rounds of looking and stopping; a parent that starts more is stopped first. */
500
+ const ROUNDS = 3;
501
+
502
+ /**
503
+ * The longest a sweep may take is this many rounds, each of which lists the
504
+ * table (twice on macOS), signals TERM, polls for one grace and signals KILL.
505
+ */
506
+ export const REAP_ROUNDS = ROUNDS;
507
+
508
+ /**
509
+ * What to stop now: the marked processes `select` picks, the processes the
510
+ * tracker followed that still live, and the parents of the marked ones. A
511
+ * marked process that is a child of a shell whose own environment the system
512
+ * withholds is the shell's work: the shell goes first, or it starts the next
513
+ * one. This process and everything above it are never picked.
514
+ */
515
+ async function collect(options: ReapOptions): Promise<readonly ProcessRow[]> {
516
+ const rows = await (options.table ?? readProcessTable)();
517
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
518
+ const never = protectedPids(rows);
519
+ const picked = new Map<string, ProcessRow>();
520
+ const add = (row: ProcessRow | undefined): row is ProcessRow => {
521
+ if (row === undefined || never.has(row.pid) || row.pid <= 1) return false;
522
+ picked.set(identity(row), row);
523
+ return true;
524
+ };
525
+ for (const one of (await (options.list ?? listMarkedProcesses)()).filter(options.select)) {
526
+ let row = byPid.get(one.pid);
527
+ if (!add(row)) continue;
528
+ // Climb to the parents: the first one that is not ours to stop ends it.
529
+ while (row !== undefined && row.ppid > 1) {
530
+ row = byPid.get(row.ppid);
531
+ if (row === undefined || picked.has(identity(row)) || !add(row)) break;
532
+ }
533
+ }
534
+ if (options.tracker !== undefined) {
535
+ for (const row of rows) if (options.tracker.has(row)) add(row);
536
+ }
537
+ return [...picked.values()];
538
+ }
539
+
540
+ /**
541
+ * Stops what a step left running: TERM, a bounded wait, then KILL for what
542
+ * lives on, named by pid and start time so a pid that was reused meanwhile is
543
+ * not signaled. A shell loop can start something new, so it looks again up to
544
+ * `ROUNDS` times. Writes how many and which commands, one line each. Returns
545
+ * what it found.
546
+ */
547
+ export async function reapMarked(options: ReapOptions): Promise<readonly Reaped[]> {
548
+ const clock = options.clock ?? systemClock;
549
+ const grace = options.graceMs ?? KILL_GRACE_MS;
550
+ const all: ProcessRow[] = [];
551
+ for (let round = 0; round < ROUNDS; round += 1) {
552
+ const found = await collect(options);
553
+ if (found.length === 0) break;
554
+ all.push(...found);
555
+ for (const one of found) signalProcess(one.pid, "SIGTERM");
556
+ const names = new Set(found.map(identity));
557
+ let waited = 0;
558
+ let left = found;
559
+ while (waited < grace && left.length > 0) {
560
+ const step = Math.min(50, grace - waited);
561
+ await clock.sleep(step);
562
+ waited += step;
563
+ left = (await (options.table ?? readProcessTable)()).filter((row) => names.has(identity(row)));
564
+ }
565
+ for (const one of left) signalProcess(one.pid, "SIGKILL");
566
+ }
567
+ if (all.length > 0 && options.write !== undefined) {
568
+ const noun = all.length === 1 ? "process" : "processes";
569
+ const lines = [
570
+ `${options.what}: stopping ${all.length} ${noun} it left running`,
571
+ ...all.map((one) => ` ${describeProcess(one)}`),
572
+ ];
573
+ try {
574
+ await options.write(lines.join("\n"));
575
+ } catch {
576
+ // A log that cannot be written must not keep the processes alive.
577
+ }
578
+ }
579
+ return all;
580
+ }
581
+
582
+ /** The step markers that are running in this process, by marker value and home. */
583
+ const running = new Map<string, number>();
584
+
585
+ /**
586
+ * Notes that a step began; the returned function notes that it ended and says
587
+ * whether it was the last one with this marker. Two steps of one run and name
588
+ * at once share a marker, so only the last to end may sweep.
589
+ */
590
+ export function enterStep(marker: StepMarker): () => boolean {
591
+ const key = keyOf(marker);
592
+ running.set(key, (running.get(key) ?? 0) + 1);
593
+ if (!trackers.has(key)) {
594
+ const tracker = new StepTracker({ watcher: createProcessWatch() });
595
+ trackers.set(key, tracker);
596
+ tracker.start();
597
+ }
598
+ return () => {
599
+ const count = (running.get(key) ?? 1) - 1;
600
+ if (count <= 0) {
601
+ running.delete(key);
602
+ return true;
603
+ }
604
+ running.set(key, count);
605
+ return false;
606
+ };
607
+ }
608
+
609
+ /** Stops what a step left running, and says so in the step's log. */
610
+ export async function reapStep(
611
+ marker: StepMarker,
612
+ logger: PluginLogger | undefined,
613
+ options: {
614
+ readonly clock?: Clock | undefined;
615
+ readonly list?: ProcessLister | undefined;
616
+ readonly table?: ProcessTable | undefined;
617
+ } = {},
618
+ ): Promise<readonly Reaped[]> {
619
+ const value = markerValue(marker);
620
+ const home = homeToken(marker.home);
621
+ const key = keyOf(marker);
622
+ const tracker = trackers.get(key);
623
+ tracker?.stop(options.clock);
624
+ tracker?.finish();
625
+ trackers.delete(key);
626
+ if (tracker !== undefined) await tracker.poll(options.table);
627
+ return reapMarked({
628
+ select: (one) => one.marker === value && one.home === home,
629
+ tracker,
630
+ what: `step ${marker.step}`,
631
+ write: logger === undefined ? undefined : (text) => logger.write(text),
632
+ clock: options.clock,
633
+ list: options.list,
634
+ table: options.table,
635
+ });
636
+ }
637
+
638
+ /**
639
+ * At serve start: stops the processes of this home whose run is not active,
640
+ * which a serve that died left behind. Says so once, as one message.
641
+ */
642
+ export async function reapStale(options: {
643
+ readonly home: string;
644
+ readonly activeRunIds: readonly string[];
645
+ readonly log: (message: string) => void;
646
+ readonly clock?: Clock | undefined;
647
+ readonly list?: ProcessLister | undefined;
648
+ readonly table?: ProcessTable | undefined;
649
+ }): Promise<readonly Reaped[]> {
650
+ const home = homeToken(options.home);
651
+ const active = options.activeRunIds.map((id) => `${token(id)}:`);
652
+ const lines: string[] = [];
653
+ const found = await reapMarked({
654
+ select: (one) => one.home === home && !active.some((prefix) => one.marker.startsWith(prefix)),
655
+ what: "serve start",
656
+ write: (text) => {
657
+ lines.push(text);
658
+ return Promise.resolve();
659
+ },
660
+ clock: options.clock,
661
+ list: options.list,
662
+ table: options.table,
663
+ });
664
+ if (found.length > 0) {
665
+ options.log(`${lines.join("\n")} (runs that are no longer active)`);
666
+ }
667
+ return found;
668
+ }