@operad-io/engine 0.0.0-stage → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,675 @@
1
+ /**
2
+ * Process groups. A plugin that runs a command starts it in a process group of
3
+ * its own and stops only the group it started. This module holds the pieces
4
+ * that took several review rounds to get right: the sentinel that leads the
5
+ * group, the control pipe it reports on, and the stop that signals the group
6
+ * with TERM and then KILL. `runLine` is the whole thing for one shell line; the
7
+ * helpers it is built from are exported for a plugin that streams a command's
8
+ * output its own way. Nothing here runs in the kernel.
9
+ */
10
+
11
+ import { spawn, type ChildProcess } from "node:child_process";
12
+ import { constants as osConstants } from "node:os";
13
+ import { Readable } from "node:stream";
14
+ import { messageOf } from "../plugin/errors.ts";
15
+ import type { PluginLogger } from "../plugin/types.ts";
16
+ import { markerEnv, trackRoot } from "./step-reap.ts";
17
+
18
+ /** How long a group gets to end after SIGTERM before SIGKILL. */
19
+ export const KILL_GRACE_MS = 500;
20
+
21
+ /**
22
+ * The sentinel is the process-group leader of one line. Its first action
23
+ * ignores SIGTERM; only then does it announce `ready` on the control pipe and
24
+ * start the line, in the same group. A stop that arrives earlier waits for
25
+ * `ready` before it signals, so a signal never reaches the sentinel before its
26
+ * trap is in place. When the line exits the sentinel reports the status and
27
+ * stays alive, so the numeric group id cannot be reused until the stop's last
28
+ * SIGKILL ends the sentinel together with any child that ignored the TERM.
29
+ *
30
+ * The sentinel also watches the process that started it (`$2`), from a helper
31
+ * that runs beside the line: if the host is killed before it can stop the
32
+ * group, the helper kills the whole group, line included, instead of leaving
33
+ * both to run on for a host that is gone. The check must not wait for the line
34
+ * to end, because the line may be the thing that never does.
35
+ *
36
+ * The control pipe is the sentinel's stderr; the line gets stderr redirected to
37
+ * its stdout, so the two channels never mix. The line cannot write to the
38
+ * control channel, and a reader that does not know a line ignores it.
39
+ */
40
+ const SENTINEL = [
41
+ "trap ':' TERM",
42
+ // The helper's output goes nowhere, so it never holds the control pipe open.
43
+ // The numeric group form is POSIX; dash does not accept `--` before it.
44
+ '( while kill -0 "$2" 2>/dev/null; do sleep 1; done; kill -KILL -$$ ) >/dev/null 2>&1 &',
45
+ "printf 'ready\\n' >&2",
46
+ 'sh -c "$1" 2>&1',
47
+ "status=$?",
48
+ "printf 'end %s\\n' \"$status\" >&2",
49
+ 'while kill -0 "$2" 2>/dev/null; do sleep 1 2>/dev/null; done',
50
+ ].join("\n");
51
+
52
+ /** The signal names by number, for the status a shell reports for a signal. */
53
+ const SIGNALS_BY_NUMBER = new Map<number, string>(
54
+ Object.entries(osConstants.signals).map(([name, number]) => [number, name]),
55
+ );
56
+
57
+ /**
58
+ * How long the pipes get to close after the group was stopped. A process that
59
+ * left the group keeps its inherited descriptors open, and the command must
60
+ * not wait for it: reading stops after this.
61
+ */
62
+ export const DRAIN_GRACE_MS = 1000;
63
+
64
+ /** The timers a line run reads. A test injects its own to control timeouts. */
65
+ export interface Clock {
66
+ setTimeout(handler: () => void, ms: number): unknown;
67
+ clearTimeout(handle: unknown): void;
68
+ sleep(ms: number): Promise<void>;
69
+ }
70
+
71
+ /** The clock a real run uses. */
72
+ export const systemClock: Clock = {
73
+ setTimeout: (handler, ms) => globalThis.setTimeout(handler, ms),
74
+ clearTimeout: (handle) =>
75
+ globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
76
+ sleep: (ms) => new Promise((resolve) => globalThis.setTimeout(resolve, ms)),
77
+ };
78
+
79
+ /** How much output the tail keeps; enough for the last lines of a long run. */
80
+ const TAIL_LIMIT = 64 * 1024;
81
+
82
+ /** How much complete output is buffered before it is written to the log. */
83
+ const FLUSH_AT = 16 * 1024;
84
+
85
+ export interface LineRunOptions {
86
+ readonly line: string;
87
+ readonly cwd: string;
88
+ readonly env?: Readonly<Record<string, string>> | undefined;
89
+ readonly timeoutMs?: number | undefined;
90
+ /** How long the line may write no output before its group is stopped. */
91
+ readonly stallMs?: number | undefined;
92
+ readonly signal: AbortSignal;
93
+ readonly logger?: PluginLogger | undefined;
94
+ readonly clock?: Clock | undefined;
95
+ /**
96
+ * Test-only seam: replaces the sentinel script, so a test can delay the
97
+ * `ready` announcement and exercise a stop that arrives before it. A
98
+ * production run never sets it.
99
+ */
100
+ readonly sentinelScript?: string | undefined;
101
+ /** Sends a signal to one process group; a test replaces it to watch signals. */
102
+ readonly killGroup?:
103
+ | ((pgid: number, signal: NodeJS.Signals | 0) => boolean)
104
+ | undefined;
105
+ }
106
+
107
+ export interface LineOutcome {
108
+ readonly exitCode: number | null;
109
+ readonly signal: string | null;
110
+ readonly timedOut: boolean;
111
+ readonly stalled: boolean;
112
+ readonly cancelled: boolean;
113
+ readonly spawnError: string | undefined;
114
+ readonly log: string | undefined;
115
+ readonly tail: readonly string[];
116
+ /** More of the end of the output, for the reason a stall gives. */
117
+ readonly stallTail: readonly string[];
118
+ }
119
+
120
+ /** The last `count` lines of a chunk of output, with no trailing blank line. */
121
+ export function lastLines(text: string, count: number): readonly string[] {
122
+ const lines = text.split("\n");
123
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
124
+ return lines.slice(-count);
125
+ }
126
+
127
+ /**
128
+ * Writes output to the step's log as complete chunks, so a long command does
129
+ * not need its whole output in memory. Only a bounded tail is kept for the
130
+ * fact.
131
+ */
132
+ class Output {
133
+ private tail = "";
134
+ private buffer = "";
135
+ private wrote = false;
136
+ private chain: Promise<void> = Promise.resolve();
137
+ private readonly logger: PluginLogger | undefined;
138
+ private readonly onOutput: (() => void) | undefined;
139
+
140
+ constructor(logger: PluginLogger | undefined, onOutput?: () => void) {
141
+ this.logger = logger;
142
+ this.onOutput = onOutput;
143
+ }
144
+
145
+ push(text: string): void {
146
+ if (text.length === 0) return;
147
+ this.tail = (this.tail + text).slice(-TAIL_LIMIT);
148
+ this.onOutput?.();
149
+ if (this.logger === undefined) return;
150
+
151
+ this.buffer += text;
152
+ const newline = this.buffer.lastIndexOf("\n");
153
+ if (newline >= 0 && newline >= FLUSH_AT) {
154
+ const complete = this.buffer.slice(0, newline);
155
+ this.buffer = this.buffer.slice(newline + 1);
156
+ this.enqueue(complete);
157
+ } else if (this.buffer.length >= FLUSH_AT * 4) {
158
+ const complete = this.buffer;
159
+ this.buffer = "";
160
+ this.enqueue(complete);
161
+ }
162
+ }
163
+
164
+ async end(): Promise<void> {
165
+ if (this.logger !== undefined) {
166
+ if (this.buffer.length > 0) {
167
+ const complete = this.buffer;
168
+ this.buffer = "";
169
+ this.enqueue(complete);
170
+ } else if (!this.wrote) {
171
+ this.enqueue("");
172
+ }
173
+ }
174
+ await this.chain;
175
+ }
176
+
177
+ tailLines(count: number): readonly string[] {
178
+ return lastLines(this.tail, count);
179
+ }
180
+
181
+ private enqueue(text: string): void {
182
+ const logger = this.logger;
183
+ if (logger === undefined) return;
184
+ if (text.length === 0 && this.wrote) return;
185
+ this.wrote = true;
186
+ this.chain = this.chain
187
+ .then(() => logger.write(text))
188
+ .then(() => undefined);
189
+ }
190
+ }
191
+
192
+ function consume(stream: Readable, output: Output): Promise<void> {
193
+ return (async () => {
194
+ const decoder = new TextDecoder();
195
+ try {
196
+ for await (const chunk of stream) {
197
+ output.push(decoder.decode(chunk as Uint8Array, { stream: true }));
198
+ }
199
+ output.push(decoder.decode());
200
+ } catch {
201
+ // A process that failed to start has no output; its streams may error.
202
+ }
203
+ })();
204
+ }
205
+
206
+ export interface Exit {
207
+ readonly code: number | null;
208
+ readonly signal: string | null;
209
+ }
210
+
211
+ /** The first line the sentinel writes: it is ready, or the shell is gone. */
212
+ export type Startup =
213
+ | { readonly kind: "ready" }
214
+ | { readonly kind: "closed" }
215
+ | { readonly kind: "error"; readonly message: string }
216
+ | { readonly kind: "exit"; readonly exit: Exit };
217
+
218
+ /** How the line's own shell ended. */
219
+ export type Ended =
220
+ | { readonly kind: "end"; readonly exit: Exit }
221
+ | { readonly kind: "exit"; readonly exit: Exit }
222
+ | { readonly kind: "closed" };
223
+
224
+ /**
225
+ * The status a shell reports for a line that a signal ended: 128 plus the
226
+ * signal number. A line that exits with such a code on purpose reads the same.
227
+ */
228
+ export function exitFromStatus(status: number | null): Exit {
229
+ if (status === null) return { code: null, signal: null };
230
+ // The shell keeps only one number, so a line that exits 130 on purpose and
231
+ // one killed by SIGINT read the same. The exit code is the fact's own
232
+ // value; the signal is what that number would name, recorded beside it.
233
+ if (status > 128) {
234
+ const signal = SIGNALS_BY_NUMBER.get(status - 128);
235
+ return { code: status, signal: signal ?? null };
236
+ }
237
+ return { code: status, signal: null };
238
+ }
239
+
240
+ /** The exit status in a sentinel `end <status>` line, if that is what it is. */
241
+ export function endStatus(line: string | null): number | undefined {
242
+ if (line === null) return undefined;
243
+ const match = /^end (\d+)$/.exec(line);
244
+ if (match === null) return undefined;
245
+ return Number(match[1]);
246
+ }
247
+
248
+ /**
249
+ * Reads the sentinel's control lines in order. Lines that arrive before a
250
+ * reader asks are queued; a closed pipe answers `null` to every later read.
251
+ * Anything that is not a control line (a shell message from the sentinel) is
252
+ * ignored.
253
+ */
254
+ export class ControlReader {
255
+ private buffer = "";
256
+ private readonly lines: string[] = [];
257
+ private readonly waiters: Array<(line: string | null) => void> = [];
258
+ private closed = false;
259
+ private readonly stream: Readable;
260
+
261
+ constructor(stream: Readable) {
262
+ this.stream = stream;
263
+ stream.setEncoding("utf8");
264
+ stream.on("data", (chunk: string) => this.receive(chunk));
265
+ stream.on("end", () => this.finish());
266
+ stream.on("close", () => this.finish());
267
+ stream.on("error", () => this.finish());
268
+ }
269
+
270
+ next(): Promise<string | null> {
271
+ const line = this.lines.shift();
272
+ if (line !== undefined) return Promise.resolve(line);
273
+ if (this.closed) return Promise.resolve(null);
274
+ return new Promise((resolve) => {
275
+ this.waiters.push(resolve);
276
+ });
277
+ }
278
+
279
+ destroy(): void {
280
+ // Resolve a pending read: `stream.destroy()` may only emit `close` later,
281
+ // and a waiter left until then would never settle.
282
+ this.finish();
283
+ this.stream.destroy();
284
+ }
285
+
286
+ private receive(text: string): void {
287
+ if (this.closed) return;
288
+ this.buffer += text;
289
+ let index = this.buffer.indexOf("\n");
290
+ while (index >= 0) {
291
+ const line = this.buffer.slice(0, index);
292
+ this.buffer = this.buffer.slice(index + 1);
293
+ if (line === "ready" || endStatus(line) !== undefined) this.deliver(line);
294
+ index = this.buffer.indexOf("\n");
295
+ }
296
+ }
297
+
298
+ private deliver(line: string): void {
299
+ const waiter = this.waiters.shift();
300
+ if (waiter !== undefined) waiter(line);
301
+ else this.lines.push(line);
302
+ }
303
+
304
+ private finish(): void {
305
+ if (this.closed) return;
306
+ this.closed = true;
307
+ for (const waiter of this.waiters.splice(0)) waiter(null);
308
+ }
309
+ }
310
+
311
+ /** Sends a signal to a whole process group. False when it could not. */
312
+ export function killProcessGroup(
313
+ pgid: number,
314
+ signal: NodeJS.Signals | 0,
315
+ ): boolean {
316
+ try {
317
+ process.kill(-pgid, signal);
318
+ return true;
319
+ } catch {
320
+ return false;
321
+ }
322
+ }
323
+
324
+ /** What the stop of one sentinel-led group reads while it runs. */
325
+ export interface GroupStopOptions {
326
+ readonly clock: Clock;
327
+ /** Sends a signal to one process group; a test replaces it to watch signals. */
328
+ readonly killGroup: (pgid: number, signal: NodeJS.Signals | 0) => boolean;
329
+ /** The sentinel's pid, which is the group id. */
330
+ readonly pid: () => number | undefined;
331
+ readonly sentinelExited: () => boolean;
332
+ /** True once the sentinel announced that its TERM trap is installed. */
333
+ readonly readySeen: () => boolean;
334
+ /** Settles when the sentinel announces `ready`. */
335
+ readonly ready: Promise<void>;
336
+ /**
337
+ * True while any process is left in the group. The default asks the kernel
338
+ * with signal 0; a test replaces it. Not routed through `killGroup`, so a
339
+ * test that records signals sees only the TERM and KILL that were sent.
340
+ */
341
+ readonly groupExists?: ((pgid: number) => boolean) | undefined;
342
+ /** Waits a moment, in real time, between two sweeps of the group. Blocks. */
343
+ readonly pause?: (() => void) | undefined;
344
+ }
345
+
346
+ /** How often the last SIGKILL is repeated for a straggler, and the wait between. */
347
+ export const SWEEP_ATTEMPTS = 50;
348
+ export const SWEEP_PAUSE_MS = 1;
349
+
350
+ /**
351
+ * Repeats SIGKILL while the group still has a member. A signal to a group
352
+ * reaches the processes that exist when it is delivered: a shell that forks at
353
+ * that instant leaves a child the signal missed, which then holds the line's
354
+ * output open for as long as it runs (a `sleep 30` outlived a cancelled line
355
+ * and the run waited for it).
356
+ *
357
+ * The group id is safe to signal only while its leader still owns it. The
358
+ * killed leader stays a zombie until the event loop reaps it, so the whole
359
+ * sweep is one synchronous step, with no yield: no exit event is handled
360
+ * inside it, the id cannot have been freed and reused, and every signal goes
361
+ * to the line's own group. The check below covers a leader reaped earlier.
362
+ */
363
+ function sweep(pgid: number, options: GroupStopOptions): void {
364
+ const exists = options.groupExists ?? groupExists;
365
+ const pause = options.pause ?? sleepSync;
366
+ for (let attempt = 0; attempt < SWEEP_ATTEMPTS; attempt += 1) {
367
+ // A kill of the group can take a moment to show; look after a pause.
368
+ pause();
369
+ if (options.sentinelExited() || !exists(pgid)) return;
370
+ options.killGroup(pgid, "SIGKILL");
371
+ }
372
+ }
373
+
374
+ /** Blocks the thread for one sweep pause. */
375
+ function sleepSync(): void {
376
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, SWEEP_PAUSE_MS);
377
+ }
378
+
379
+ /** True while the kernel still has a process in the group. */
380
+ function groupExists(pgid: number): boolean {
381
+ return killProcessGroup(pgid, 0);
382
+ }
383
+
384
+ /**
385
+ * Returns the stop of a sentinel-led group: SIGTERM, then SIGKILL after the
386
+ * grace period. It runs once; every later call returns the same promise. A
387
+ * signal before `ready` could reach the sentinel before it ignores TERM, so the
388
+ * stop waits for the announcement, bounded by the same grace.
389
+ */
390
+ export function createGroupStop(options: GroupStopOptions): () => Promise<void> {
391
+ let stopping: Promise<void> | undefined;
392
+ return () => {
393
+ stopping ??= (async () => {
394
+ if (options.sentinelExited()) return;
395
+ const pid = options.pid();
396
+ // A spawn that never produced a process has no group to signal or wait
397
+ // for; returning here keeps a failed spawn from paying the grace.
398
+ if (pid === undefined) return;
399
+ let ready = true;
400
+ if (!options.readySeen()) {
401
+ const outcome = await Promise.race<"ready" | "grace">([
402
+ options.ready.then(() => "ready"),
403
+ options.clock.sleep(KILL_GRACE_MS).then(() => "grace"),
404
+ ]);
405
+ ready = outcome === "ready";
406
+ }
407
+ if (options.sentinelExited()) return;
408
+ if (!ready) {
409
+ // The sentinel never announced its trap. There is no safe delay: one
410
+ // immediate SIGKILL while our leader is still alive is the only signal.
411
+ if (options.killGroup(pid, "SIGKILL")) sweep(pid, options);
412
+ return;
413
+ }
414
+ if (!options.killGroup(pid, "SIGTERM")) return;
415
+ await options.clock.sleep(KILL_GRACE_MS);
416
+ // The sentinel ignores SIGTERM, so its group id is still this command's
417
+ // unless it exited, in which case nothing is signaled at all.
418
+ if (options.sentinelExited()) return;
419
+ // A SIGKILL that found no group means the leader is gone and the id may
420
+ // already be someone else's: sweeping then would signal a stranger.
421
+ if (options.killGroup(pid, "SIGKILL")) sweep(pid, options);
422
+ })();
423
+ return stopping;
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Runs one line in a process group of its own. Cancellation and the timeout
429
+ * signal the group with SIGTERM and, after the grace period, SIGKILL. The group
430
+ * is always stopped after the line exits too, so a child it forked cannot
431
+ * outlive it. The sentinel leads the group until that SIGKILL, so its numeric
432
+ * id can never be reused by an unrelated group in between: the plugin only ever
433
+ * signals processes it started. A process that leaves the group on purpose
434
+ * cannot be signaled without risking an unrelated process, so the line stops
435
+ * reading its output instead.
436
+ */
437
+ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
438
+ if (options.signal.aborted) {
439
+ return {
440
+ exitCode: null,
441
+ signal: null,
442
+ timedOut: false,
443
+ stalled: false,
444
+ cancelled: true,
445
+ spawnError: undefined,
446
+ log: options.logger?.path,
447
+ tail: [],
448
+ stallTail: [],
449
+ };
450
+ }
451
+
452
+ const clock = options.clock ?? systemClock;
453
+ let resetStallForOutput = (): void => {};
454
+ const output = new Output(options.logger, () => resetStallForOutput());
455
+ let child: ChildProcess;
456
+ try {
457
+ child = spawn(
458
+ "sh",
459
+ [
460
+ "-c",
461
+ options.sentinelScript ?? SENTINEL,
462
+ "operad-shell",
463
+ options.line,
464
+ String(process.pid),
465
+ ],
466
+ {
467
+ cwd: options.cwd,
468
+ env: { ...process.env, ...markerEnv(), ...options.env },
469
+ detached: true,
470
+ stdio: ["ignore", "pipe", "pipe"],
471
+ },
472
+ );
473
+ } catch (error) {
474
+ const spawnError = messageOf(error);
475
+ await output.end();
476
+ return {
477
+ exitCode: null,
478
+ signal: null,
479
+ timedOut: false,
480
+ stalled: false,
481
+ cancelled: false,
482
+ spawnError,
483
+ log: options.logger?.path,
484
+ tail: output.tailLines(20),
485
+ stallTail: output.tailLines(200),
486
+ };
487
+ }
488
+
489
+ trackRoot(child.pid);
490
+ let sentinelExited = false;
491
+ const failed = new Promise<string>((resolve) => {
492
+ child.once("error", (error) => resolve(messageOf(error)));
493
+ });
494
+ const exited = new Promise<Exit>((resolve) => {
495
+ child.once("exit", (code, signal) => {
496
+ sentinelExited = true;
497
+ resolve({ code, signal });
498
+ });
499
+ });
500
+
501
+ const stdout = child.stdout;
502
+ const stderr = child.stderr;
503
+ const drained: Promise<void>[] = [];
504
+ if (stdout !== null) drained.push(consume(stdout, output));
505
+ const control = stderr === null ? undefined : new ControlReader(stderr);
506
+ const nextControl = (): Promise<string | null> =>
507
+ control === undefined ? Promise.resolve(null) : control.next();
508
+
509
+ // Opens once the sentinel announced that its TERM trap is installed.
510
+ let openGate = (): void => {};
511
+ const readyGate = new Promise<void>((resolve) => {
512
+ openGate = resolve;
513
+ });
514
+
515
+ let readySeen = false;
516
+ const stop = createGroupStop({
517
+ clock,
518
+ killGroup: options.killGroup ?? killProcessGroup,
519
+ pid: () => child.pid,
520
+ sentinelExited: () => sentinelExited,
521
+ readySeen: () => readySeen,
522
+ ready: readyGate,
523
+ });
524
+
525
+ let finished = false;
526
+ let timedOut = false;
527
+ let stalled = false;
528
+ let cancelled = false;
529
+ let timer: unknown;
530
+ if (options.timeoutMs !== undefined) {
531
+ timer = clock.setTimeout(() => {
532
+ if (finished) return;
533
+ timedOut = true;
534
+ void stop();
535
+ }, options.timeoutMs);
536
+ }
537
+ let stallTimer: unknown;
538
+ const clearStall = (): void => {
539
+ if (stallTimer === undefined) return;
540
+ clock.clearTimeout(stallTimer);
541
+ stallTimer = undefined;
542
+ };
543
+ const resetStall = (): void => {
544
+ if (finished || options.stallMs === undefined || options.stallMs <= 0) return;
545
+ clearStall();
546
+ stallTimer = clock.setTimeout(() => {
547
+ if (finished) return;
548
+ stalled = true;
549
+ void stop();
550
+ }, options.stallMs);
551
+ };
552
+ resetStallForOutput = resetStall;
553
+ const onAbort = (): void => {
554
+ if (finished) return;
555
+ cancelled = true;
556
+ void stop();
557
+ };
558
+ options.signal.addEventListener("abort", onAbort, { once: true });
559
+
560
+ const startup = await Promise.race<Startup>([
561
+ nextControl().then(
562
+ (line): Startup =>
563
+ line === "ready" ? { kind: "ready" } : { kind: "closed" },
564
+ ),
565
+ failed.then((message): Startup => ({ kind: "error", message })),
566
+ exited.then((exit): Startup => ({ kind: "exit", exit })),
567
+ ]);
568
+
569
+ const finish = async (): Promise<{
570
+ readonly tail: readonly string[];
571
+ readonly stallTail: readonly string[];
572
+ }> => {
573
+ const drainedOutput = Promise.all(drained).then(() => undefined);
574
+ let drainTimer: unknown;
575
+ const drainLimit = new Promise<void>((resolve) => {
576
+ drainTimer = clock.setTimeout(resolve, DRAIN_GRACE_MS);
577
+ });
578
+ await Promise.race([drainedOutput, drainLimit]);
579
+ if (drainTimer !== undefined) clock.clearTimeout(drainTimer);
580
+ if (stdout !== null) stdout.destroy();
581
+ control?.destroy();
582
+ await drainedOutput;
583
+ await output.end();
584
+ return { tail: output.tailLines(20), stallTail: output.tailLines(200) };
585
+ };
586
+
587
+ if (startup.kind !== "ready") {
588
+ finished = true;
589
+ if (timer !== undefined) clock.clearTimeout(timer);
590
+ clearStall();
591
+ options.signal.removeEventListener("abort", onAbort);
592
+ await stop();
593
+ await Promise.race([exited, failed]);
594
+ const { tail, stallTail } = await finish();
595
+ const spawnError =
596
+ cancelled || timedOut
597
+ ? undefined
598
+ : startup.kind === "error"
599
+ ? startup.message
600
+ : "the command shell stopped before the command started";
601
+ return {
602
+ exitCode: startup.kind === "exit" ? startup.exit.code : null,
603
+ signal: startup.kind === "exit" ? startup.exit.signal : null,
604
+ timedOut,
605
+ stalled: false,
606
+ cancelled,
607
+ spawnError,
608
+ log: options.logger?.path,
609
+ tail,
610
+ stallTail,
611
+ };
612
+ }
613
+
614
+ readySeen = true;
615
+ openGate();
616
+ resetStall();
617
+
618
+ // One read serves the race and, if the shell's exit wins it, the look for
619
+ // the record afterwards: a second read would queue behind this one and miss
620
+ // the line it takes.
621
+ const endRead = nextControl();
622
+ const ended = await Promise.race<Ended>([
623
+ endRead.then((line): Ended => {
624
+ const status = endStatus(line);
625
+ return status === undefined
626
+ ? { kind: "closed" }
627
+ : { kind: "end", exit: exitFromStatus(status) };
628
+ }),
629
+ exited.then((exit): Ended => ({ kind: "exit", exit })),
630
+ ]);
631
+
632
+ finished = true;
633
+ if (timer !== undefined) clock.clearTimeout(timer);
634
+ clearStall();
635
+ options.signal.removeEventListener("abort", onAbort);
636
+
637
+ let exit: Exit;
638
+ if (ended.kind === "end") exit = ended.exit;
639
+ else {
640
+ // A control pipe that closed with the sentinel still alive leaves nothing
641
+ // that would end it: stop the group before waiting for an exit.
642
+ if (ended.kind === "closed") await stop();
643
+ // The shell's exit event can arrive before the end record it wrote has been
644
+ // read. The record holds the line's own status, so read the pipe to its
645
+ // close before settling for the shell's exit: a deliberate nonzero status
646
+ // must not turn into the shell's own.
647
+ const record = endStatus(await endRead);
648
+ exit = record === undefined ? await exited : exitFromStatus(record);
649
+ }
650
+
651
+ // Stop the group the line left behind: the sentinel and any forked child.
652
+ // A line that reported its own status has already ended, so there is nothing
653
+ // left to give SIGTERM time for; waiting the grace here made every successful
654
+ // line pay 500 ms. A cancellation or timeout still takes the TERM path.
655
+ if (ended.kind === "end" && !cancelled && !timedOut && !stalled) {
656
+ const pid = child.pid;
657
+ if (pid !== undefined) (options.killGroup ?? killProcessGroup)(pid, "SIGKILL");
658
+ } else {
659
+ await stop();
660
+ }
661
+ await Promise.race([exited, failed]);
662
+ const { tail, stallTail } = await finish();
663
+
664
+ return {
665
+ exitCode: exit.code,
666
+ signal: exit.signal,
667
+ timedOut,
668
+ stalled,
669
+ cancelled,
670
+ spawnError: undefined,
671
+ log: options.logger?.path,
672
+ tail,
673
+ stallTail,
674
+ };
675
+ }