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