@mostra/runtime 0.2.0 → 0.4.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.
- package/dist/bin.js +23 -12
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +20 -18
- package/dist/builder/child/main.js.map +1 -1
- package/dist/{child-xrHmytks.js → child-Chiavhdx.js} +7 -3
- package/dist/child-Chiavhdx.js.map +1 -0
- package/dist/deps/child/install.js +9 -6
- package/dist/deps/child/install.js.map +1 -1
- package/dist/directories-mJ1qlVht.js +322 -0
- package/dist/directories-mJ1qlVht.js.map +1 -0
- package/dist/files-FygSJIzK.js +388 -0
- package/dist/files-FygSJIzK.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-CzBkUyHu.js → instance-DxcGEQj_.js} +1680 -934
- package/dist/instance-DxcGEQj_.js.map +1 -0
- package/package.json +5 -5
- package/src/bin.ts +18 -16
- package/src/builder/child/dev.ts +8 -4
- package/src/builder/child/plugins.ts +12 -7
- package/src/builder/child/spa.ts +15 -9
- package/src/builder/index.ts +3 -6
- package/src/deps/child/install.ts +3 -2
- package/src/deps/index.ts +21 -16
- package/src/deps/warm.ts +3 -16
- package/src/dev/index.ts +37 -19
- package/src/faults.ts +9 -2
- package/src/gateway/capabilities.ts +2 -2
- package/src/gateway/listener.ts +36 -0
- package/src/home/acquire.ts +27 -11
- package/src/home/index.ts +1 -1
- package/src/home/paths.ts +45 -135
- package/src/home/platform.ts +17 -9
- package/src/home/record.ts +3 -3
- package/src/home/settings.ts +5 -16
- package/src/instance/index.ts +41 -9
- package/src/ledger/index.ts +5 -27
- package/src/platform/control.ts +409 -0
- package/src/platform/directories.ts +212 -0
- package/src/platform/environment.ts +64 -0
- package/src/platform/files.ts +386 -0
- package/src/platform/helper.ts +178 -0
- package/src/{processes → platform}/identity.ts +40 -8
- package/src/platform/index.ts +53 -0
- package/src/platform/launch.ts +373 -0
- package/src/processes/child.ts +11 -5
- package/src/processes/environment.ts +22 -3
- package/src/processes/index.ts +2 -1
- package/src/processes/manager.ts +76 -179
- package/src/protocol-server/client.ts +19 -18
- package/src/protocol-server/server.ts +75 -54
- package/src/publish/index.ts +2 -1
- package/src/publish/publisher.ts +17 -10
- package/src/publish/source.ts +7 -4
- package/src/registry/store.ts +7 -65
- package/src/secrets/index.ts +2 -2
- package/src/service/unit.ts +353 -33
- package/src/verify/index.ts +5 -3
- package/src/verify/typecheck.ts +3 -2
- package/src/workers/launcher.ts +3 -1
- package/src/workers/pool.ts +14 -1
- package/dist/child-xrHmytks.js.map +0 -1
- package/dist/instance-CzBkUyHu.js.map +0 -1
- package/dist/types-NjNy7gXX.js +0 -57
- package/dist/types-NjNy7gXX.js.map +0 -1
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform layer (WP-W1, RT-10): the one module that knows which operating system the runtime
|
|
3
|
+
* runs on. Every difference between POSIX and Windows lives here: where homes live, owner-only
|
|
4
|
+
* directories, the control endpoint, process identity, starting, ending and reaping children,
|
|
5
|
+
* and the file operations whose semantics differ. Other modules ask it; none of them reads
|
|
6
|
+
* `process.platform` (a test keeps it so). Windows work goes through `mostra-win`, the helper in
|
|
7
|
+
* `crates/mostra-win`.
|
|
8
|
+
*/
|
|
9
|
+
export {
|
|
10
|
+
ControlConnectError,
|
|
11
|
+
type ControlListener,
|
|
12
|
+
connectControl,
|
|
13
|
+
controlEndpoint,
|
|
14
|
+
type LaunchPipe,
|
|
15
|
+
listenControl,
|
|
16
|
+
} from "./control.ts";
|
|
17
|
+
export {
|
|
18
|
+
defaultHome,
|
|
19
|
+
OS,
|
|
20
|
+
ownedDirectory,
|
|
21
|
+
type PreparedDirectory,
|
|
22
|
+
pathsOf,
|
|
23
|
+
type RuntimeDirChoice,
|
|
24
|
+
runtimeDirFor,
|
|
25
|
+
socketPathLimit,
|
|
26
|
+
WINDOWS,
|
|
27
|
+
} from "./directories.ts";
|
|
28
|
+
export { baseEnvironment, WINDOWS_SYSTEM_VARIABLES } from "./environment.ts";
|
|
29
|
+
export {
|
|
30
|
+
fsyncPath,
|
|
31
|
+
isUnder,
|
|
32
|
+
linkDirectory,
|
|
33
|
+
linkTarget,
|
|
34
|
+
nameKey,
|
|
35
|
+
pathKey,
|
|
36
|
+
realPath,
|
|
37
|
+
removeTree,
|
|
38
|
+
renamePath,
|
|
39
|
+
renamePathSync,
|
|
40
|
+
replaceDirectoryLink,
|
|
41
|
+
samePath,
|
|
42
|
+
sealPlaced,
|
|
43
|
+
sealTree,
|
|
44
|
+
} from "./files.ts";
|
|
45
|
+
export {
|
|
46
|
+
currentUserSid,
|
|
47
|
+
helperPath,
|
|
48
|
+
runtimeRoot,
|
|
49
|
+
serviceLauncherPath,
|
|
50
|
+
stopServiceLauncher,
|
|
51
|
+
} from "./helper.ts";
|
|
52
|
+
export { isSameProcess, listProcesses, readProcess } from "./identity.ts";
|
|
53
|
+
export { adoptable, launch, reapRecorded } from "./launch.ts";
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Starting, ending and reaping children on each operating system (RT-09, RT-10, issue #7, D93,
|
|
3
|
+
* FAILURE_MODEL §2). The process manager keeps the policy (record a child before it runs, end its
|
|
4
|
+
* descendants with it, reap what a crashed supervisor left); this module is how each system does
|
|
5
|
+
* it.
|
|
6
|
+
*
|
|
7
|
+
* - **POSIX.** A child is started detached, as the leader of its own process group, behind a
|
|
8
|
+
* `/bin/sh` gate that waits for "go" on descriptor 3 and then `exec`s the command, keeping its
|
|
9
|
+
* PID, group and start time. It is ended by signalling its group (SIGTERM, then SIGKILL), and
|
|
10
|
+
* the reaper signals a recorded group's members that started no earlier than its leader.
|
|
11
|
+
* - **Windows.** A child is started behind `mostra-win gate`, which creates it suspended in a Job
|
|
12
|
+
* Object of its own that ends every member when its last handle closes, reports its PID and
|
|
13
|
+
* creation time on descriptor 3, and lets it run on "go". Descriptor 3 stays open as the
|
|
14
|
+
* child's lifeline: closing it (a stop, or the supervisor's exit or crash) ends the job, child
|
|
15
|
+
* and descendants at once. Windows has no signals to ask a process to stop, so a stop is that:
|
|
16
|
+
* graceful work goes over the child's own channel first (D87). The reaper ends a recorded
|
|
17
|
+
* child's job, which it opens by the name the gate gave it (`Local\mostra-job-<pid>-<creation>`),
|
|
18
|
+
* and the child itself if it still runs as the recorded process.
|
|
19
|
+
*/
|
|
20
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
21
|
+
import type { Readable, Writable } from "node:stream";
|
|
22
|
+
import { WINDOWS } from "./directories.ts";
|
|
23
|
+
import { helperPath, runHelperAsync } from "./helper.ts";
|
|
24
|
+
import {
|
|
25
|
+
listProcesses,
|
|
26
|
+
type ProcessInfo,
|
|
27
|
+
readProcess,
|
|
28
|
+
sameBoot,
|
|
29
|
+
startedNoEarlier,
|
|
30
|
+
} from "./identity.ts";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The POSIX gate (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and only then replaces
|
|
34
|
+
* itself with the real command. A supervisor killed in between leaves a gate that reads
|
|
35
|
+
* end-of-file and exits 125 without running anything.
|
|
36
|
+
*/
|
|
37
|
+
const GATE_SCRIPT = 'IFS= read -r go <&3 && [ "$go" = go ] || exit 125; exec 3<&-; exec "$@"';
|
|
38
|
+
|
|
39
|
+
/** How long reaping waits between SIGTERM and SIGKILL. */
|
|
40
|
+
const REAP_GRACE_MS = 2000;
|
|
41
|
+
/** How long to wait for SIGKILLed processes to disappear before reporting them. */
|
|
42
|
+
const KILL_WAIT_MS = 5000;
|
|
43
|
+
|
|
44
|
+
/** What a launch needs. */
|
|
45
|
+
export interface LaunchSpec {
|
|
46
|
+
/** What the child is (`builder`, `install` …), shown in process listings. */
|
|
47
|
+
readonly kind: string;
|
|
48
|
+
/** The executable: an absolute path on Windows. */
|
|
49
|
+
readonly command: string;
|
|
50
|
+
readonly args: readonly string[];
|
|
51
|
+
readonly cwd?: string | undefined;
|
|
52
|
+
readonly env: NodeJS.ProcessEnv;
|
|
53
|
+
/** Node's IPC channel or a plain byte channel on descriptor 4, or nothing. */
|
|
54
|
+
readonly extra?: "ipc" | "channel" | undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A child started behind its gate. */
|
|
58
|
+
export interface Launched {
|
|
59
|
+
/** The process Node started (on Windows the gate, which ends when its child does). */
|
|
60
|
+
readonly process: ChildProcess;
|
|
61
|
+
/** The child's identity once known, `undefined` when it is already gone; rejects when unreadable. */
|
|
62
|
+
identify(): Promise<{ readonly pid: number; readonly startTime: string } | undefined>;
|
|
63
|
+
/** Lets the recorded child run. */
|
|
64
|
+
release(): void;
|
|
65
|
+
/** Whether the child or anything it started still runs. */
|
|
66
|
+
running(): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Ends the child and everything it started: POSIX signals its group and `extraGroups` (SIGTERM,
|
|
69
|
+
* SIGKILL after `graceMs`); Windows closes its lifeline and, after `graceMs`, kills the gate.
|
|
70
|
+
*/
|
|
71
|
+
end(graceMs: number, extraGroups: readonly number[]): Promise<void>;
|
|
72
|
+
/** After the child exited, ends what is left of its group (nothing on Windows: its job ended). */
|
|
73
|
+
sweep(extraGroups: readonly number[]): Promise<void>;
|
|
74
|
+
/** At the supervisor's own exit: ends everything at once, without waiting. */
|
|
75
|
+
kill(): void;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
79
|
+
|
|
80
|
+
function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean {
|
|
81
|
+
try {
|
|
82
|
+
process.kill(-pgid, signal);
|
|
83
|
+
return true;
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const groupAlive = (pgid: number): boolean => signalGroup(pgid, 0);
|
|
90
|
+
|
|
91
|
+
/** Starts `spec` behind its gate. */
|
|
92
|
+
export function launch(
|
|
93
|
+
spec: LaunchSpec,
|
|
94
|
+
warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,
|
|
95
|
+
): Launched {
|
|
96
|
+
return WINDOWS ? launchWindows(spec) : launchPosix(spec, warn);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function stdioFor(extra: LaunchSpec["extra"]): ("ignore" | "pipe" | "ipc" | "overlapped")[] {
|
|
100
|
+
const base: ("ignore" | "pipe" | "ipc" | "overlapped")[] = ["ignore", "pipe", "pipe", "pipe"];
|
|
101
|
+
// A byte channel is overlapped on Windows so both ends can read and write at once; the option
|
|
102
|
+
// means "pipe" elsewhere.
|
|
103
|
+
if (extra === "ipc") return [...base, "ipc"];
|
|
104
|
+
if (extra === "channel") return [...base, "overlapped"];
|
|
105
|
+
return base;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function launchPosix(
|
|
109
|
+
spec: LaunchSpec,
|
|
110
|
+
warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,
|
|
111
|
+
): Launched {
|
|
112
|
+
const child = spawn(
|
|
113
|
+
"/bin/sh",
|
|
114
|
+
["-c", GATE_SCRIPT, `mostra-${spec.kind}`, spec.command, ...spec.args],
|
|
115
|
+
{
|
|
116
|
+
cwd: spec.cwd,
|
|
117
|
+
env: spec.env,
|
|
118
|
+
detached: true,
|
|
119
|
+
stdio: stdioFor(spec.extra),
|
|
120
|
+
serialization: "json",
|
|
121
|
+
},
|
|
122
|
+
);
|
|
123
|
+
const gate = child.stdio[3] as Writable | null;
|
|
124
|
+
gate?.on("error", () => {
|
|
125
|
+
// The child exited before reading "go"; its exit is reported through `exit`.
|
|
126
|
+
});
|
|
127
|
+
const pid = (): number => child.pid ?? 0;
|
|
128
|
+
const end = async (pgids: readonly number[], graceMs: number): Promise<void> => {
|
|
129
|
+
for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
|
|
130
|
+
const deadline = Date.now() + graceMs;
|
|
131
|
+
while (Date.now() < deadline && pgids.some(groupAlive)) await delay(25);
|
|
132
|
+
for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
|
|
133
|
+
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
134
|
+
while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay(10);
|
|
135
|
+
const left = pgids.filter(groupAlive);
|
|
136
|
+
if (left.length > 0) warn("process.group_survived_sigkill", { pgids: left });
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
process: child,
|
|
140
|
+
async identify() {
|
|
141
|
+
const info = await readProcess(pid());
|
|
142
|
+
if (info) return { pid: info.pid, startTime: info.startTime };
|
|
143
|
+
// Gone already: nothing is left to record or reap.
|
|
144
|
+
if (child.exitCode !== null || child.signalCode !== null) return undefined;
|
|
145
|
+
// Still waiting at its gate, so it can't have exited by itself: its identity just couldn't
|
|
146
|
+
// be read (D80 Claude review finding 8).
|
|
147
|
+
throw new Error(`Couldn't read the process identity of ${spec.kind} ${pid()}.`);
|
|
148
|
+
},
|
|
149
|
+
release() {
|
|
150
|
+
gate?.end("go\n");
|
|
151
|
+
},
|
|
152
|
+
running: () => child.exitCode === null && child.signalCode === null,
|
|
153
|
+
end: (graceMs, extraGroups) => end([pid(), ...extraGroups], graceMs),
|
|
154
|
+
sweep: (extraGroups) => end([pid(), ...extraGroups], 2000),
|
|
155
|
+
kill() {
|
|
156
|
+
signalGroup(pid(), "SIGKILL");
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function launchWindows(spec: LaunchSpec): Launched {
|
|
162
|
+
// Node.js puts every child it starts, the gate too, into one kill-on-close job of its own
|
|
163
|
+
// (libuv's global job), so a supervisor that dies takes its gates with it, and each gate's death
|
|
164
|
+
// closes its child's job. A gate a test makes miss its lifeline (MOSTRA_TEST_GATE, a hung gate's
|
|
165
|
+
// stand-in) is started outside that job, or nothing would be left for the reaper to find.
|
|
166
|
+
const hung = (spec.env["MOSTRA_TEST_GATE"] ?? "").split(",").includes("ignore-lifeline");
|
|
167
|
+
const child = spawn(helperPath(), ["gate", "--", spec.command, ...spec.args], {
|
|
168
|
+
cwd: spec.cwd,
|
|
169
|
+
env: spec.env,
|
|
170
|
+
windowsHide: true,
|
|
171
|
+
detached: hung,
|
|
172
|
+
stdio: stdioFor(spec.extra),
|
|
173
|
+
serialization: "json",
|
|
174
|
+
});
|
|
175
|
+
const lifeline = child.stdio[3] as (Readable & Writable) | null;
|
|
176
|
+
lifeline?.on("error", () => {});
|
|
177
|
+
const report = new Promise<{ pid: number; startTime: string } | undefined>((resolve, reject) => {
|
|
178
|
+
let text = "";
|
|
179
|
+
const onData = (chunk: Buffer): void => {
|
|
180
|
+
text += chunk.toString("utf8");
|
|
181
|
+
const end = text.indexOf("\n");
|
|
182
|
+
if (end < 0) return;
|
|
183
|
+
lifeline?.off("data", onData);
|
|
184
|
+
try {
|
|
185
|
+
const line = JSON.parse(text.slice(0, end)) as {
|
|
186
|
+
pid?: number;
|
|
187
|
+
startTime?: string;
|
|
188
|
+
error?: string;
|
|
189
|
+
};
|
|
190
|
+
if (line.pid !== undefined && line.startTime !== undefined) {
|
|
191
|
+
resolve({ pid: line.pid, startTime: line.startTime });
|
|
192
|
+
} else {
|
|
193
|
+
reject(
|
|
194
|
+
new Error(`The gate couldn't start ${spec.kind}: ${line.error ?? text.slice(0, end)}`),
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
} catch {
|
|
198
|
+
reject(new Error(`The gate of ${spec.kind} reported ${text.slice(0, 200)}`));
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
lifeline?.on("data", onData);
|
|
202
|
+
child.once("exit", () => resolve(undefined));
|
|
203
|
+
child.once("error", reject);
|
|
204
|
+
});
|
|
205
|
+
const exited = new Promise<void>((resolve) => {
|
|
206
|
+
if (child.exitCode !== null) resolve();
|
|
207
|
+
child.once("exit", () => resolve());
|
|
208
|
+
});
|
|
209
|
+
const running = (): boolean => child.exitCode === null && child.signalCode === null;
|
|
210
|
+
return {
|
|
211
|
+
process: child,
|
|
212
|
+
identify: () => report,
|
|
213
|
+
release() {
|
|
214
|
+
lifeline?.write("go\n");
|
|
215
|
+
},
|
|
216
|
+
running,
|
|
217
|
+
async end(graceMs) {
|
|
218
|
+
// Graceful work travels over the child's own channel before this (D87). Closing the
|
|
219
|
+
// lifeline ends the job; a gate that doesn't exit by itself is killed, which closes the job
|
|
220
|
+
// with its last handle.
|
|
221
|
+
lifeline?.end();
|
|
222
|
+
if (!running()) return;
|
|
223
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
224
|
+
await Promise.race([
|
|
225
|
+
exited,
|
|
226
|
+
new Promise<void>((resolve) => (timer = setTimeout(resolve, graceMs))),
|
|
227
|
+
]);
|
|
228
|
+
clearTimeout(timer);
|
|
229
|
+
if (running()) child.kill();
|
|
230
|
+
await Promise.race([exited, delay(KILL_WAIT_MS)]);
|
|
231
|
+
},
|
|
232
|
+
async sweep() {
|
|
233
|
+
// The gate ended the child's job before it exited.
|
|
234
|
+
},
|
|
235
|
+
kill() {
|
|
236
|
+
lifeline?.destroy();
|
|
237
|
+
child.kill();
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** One recorded child, as the ledger's `child` table holds it. */
|
|
243
|
+
export interface RecordedChild {
|
|
244
|
+
readonly pid: number;
|
|
245
|
+
readonly start_time: string;
|
|
246
|
+
readonly pgid: number;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** What reaping did for one recorded child. */
|
|
250
|
+
export interface ReapOutcome {
|
|
251
|
+
/** The processes it ended: the child if it still ran, and what its group or job held. */
|
|
252
|
+
readonly ended: readonly number[];
|
|
253
|
+
/** Why nothing was ended, when nothing was. */
|
|
254
|
+
readonly skipped?: "gone" | "pid reused" | "other boot";
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Ends what a previous supervisor's children left running, by their recorded identities, and
|
|
259
|
+
* leaves alone processes that only look like them (FAILURE_MODEL §2). Call it only while holding
|
|
260
|
+
* the home's ledger lock.
|
|
261
|
+
*/
|
|
262
|
+
export function reapRecorded(
|
|
263
|
+
rows: readonly RecordedChild[],
|
|
264
|
+
warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,
|
|
265
|
+
): Promise<ReapOutcome[]> {
|
|
266
|
+
return WINDOWS ? reapWindows(rows, warn) : reapPosix(rows, warn);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function reapWindows(
|
|
270
|
+
rows: readonly RecordedChild[],
|
|
271
|
+
warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,
|
|
272
|
+
): Promise<ReapOutcome[]> {
|
|
273
|
+
if (rows.length === 0) return [];
|
|
274
|
+
const answers = await runHelperAsync<
|
|
275
|
+
{ pid: number; job?: boolean; ended?: number[]; reused?: boolean; error?: string }[]
|
|
276
|
+
>(["reap", ...rows.map((row) => `${row.pid}:${row.start_time}`)]);
|
|
277
|
+
return rows.map((row, index): ReapOutcome => {
|
|
278
|
+
const answer = answers[index];
|
|
279
|
+
// A process the helper couldn't end (access, a protected process) is reported, never hidden.
|
|
280
|
+
if (answer?.error !== undefined) {
|
|
281
|
+
warn("process.reap_incomplete", { pid: row.pid, error: answer.error });
|
|
282
|
+
}
|
|
283
|
+
const ended = answer?.ended ?? [];
|
|
284
|
+
if (ended.length > 0) return { ended };
|
|
285
|
+
return { ended: [], skipped: answer?.reused ? "pid reused" : "gone" };
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The processes of a recorded group that are provably the recorded child's. */
|
|
290
|
+
function targetsFor(
|
|
291
|
+
row: RecordedChild,
|
|
292
|
+
processes: readonly ProcessInfo[],
|
|
293
|
+
): number[] | NonNullable<ReapOutcome["skipped"]> {
|
|
294
|
+
const leader = processes.find((info) => info.pid === row.pid);
|
|
295
|
+
if (leader && leader.startTime !== row.start_time) return "pid reused";
|
|
296
|
+
if (!leader) {
|
|
297
|
+
const boot = processes.find((info) => info.pid === process.pid)?.startTime;
|
|
298
|
+
if (boot === undefined || !sameBoot(boot, row.start_time)) return "other boot";
|
|
299
|
+
}
|
|
300
|
+
const members = processes
|
|
301
|
+
.filter((info) => info.pgid === row.pgid && info.pid !== process.pid)
|
|
302
|
+
.filter((info) => startedNoEarlier(info.startTime, row.start_time))
|
|
303
|
+
.map((info) => info.pid);
|
|
304
|
+
return members.length > 0 ? members : "gone";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function signalAll(pids: readonly number[], signal: NodeJS.Signals): void {
|
|
308
|
+
for (const pid of pids) {
|
|
309
|
+
try {
|
|
310
|
+
process.kill(pid, signal);
|
|
311
|
+
} catch {
|
|
312
|
+
// Already gone.
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function reapPosix(
|
|
318
|
+
rows: readonly RecordedChild[],
|
|
319
|
+
warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,
|
|
320
|
+
): Promise<ReapOutcome[]> {
|
|
321
|
+
if (rows.length === 0) return [];
|
|
322
|
+
const before = await listProcesses();
|
|
323
|
+
const plan = rows.map((row) => ({ row, targets: targetsFor(row, before) }));
|
|
324
|
+
// Only groups proven to be the recorded children's are signalled, then watched until they are
|
|
325
|
+
// empty: a member may start more processes in the group while it handles SIGTERM, so every
|
|
326
|
+
// round re-lists the groups instead of trusting the first snapshot (RT-09).
|
|
327
|
+
const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
|
|
328
|
+
const members = (processes: readonly ProcessInfo[]): number[] => [
|
|
329
|
+
...new Set(
|
|
330
|
+
owned.flatMap((row) => {
|
|
331
|
+
const targets = targetsFor(row, processes);
|
|
332
|
+
return Array.isArray(targets) ? targets : [];
|
|
333
|
+
}),
|
|
334
|
+
),
|
|
335
|
+
];
|
|
336
|
+
// A listing is a series of reads, so a process that starts while another exits can slip
|
|
337
|
+
// between them; the groups count as gone only when the kernel has no member left either.
|
|
338
|
+
const groupsLeft = (): boolean => owned.some((row) => groupAlive(row.pgid));
|
|
339
|
+
signalAll(members(before), "SIGTERM");
|
|
340
|
+
const deadline = Date.now() + REAP_GRACE_MS;
|
|
341
|
+
let remaining = members(await listProcesses());
|
|
342
|
+
while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
|
|
343
|
+
await delay(100);
|
|
344
|
+
remaining = members(await listProcesses());
|
|
345
|
+
}
|
|
346
|
+
const killDeadline = Date.now() + KILL_WAIT_MS;
|
|
347
|
+
while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
|
|
348
|
+
signalAll(remaining, "SIGKILL");
|
|
349
|
+
await delay(50);
|
|
350
|
+
remaining = members(await listProcesses());
|
|
351
|
+
}
|
|
352
|
+
if (remaining.length > 0 || groupsLeft()) {
|
|
353
|
+
warn("process.reap_incomplete", { pids: remaining, pgids: owned.map((row) => row.pgid) });
|
|
354
|
+
}
|
|
355
|
+
return plan.map(({ targets }) =>
|
|
356
|
+
Array.isArray(targets) ? { ended: targets } : { ended: [], skipped: targets },
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Whether `pid` can be adopted by a child whose own group is `childPgid`: on POSIX a program the
|
|
362
|
+
* child started in its own session (a PTY program), which only a group leader is; on Windows every
|
|
363
|
+
* descendant is already in the child's job and ends with it, so a running process needs nothing
|
|
364
|
+
* more (it isn't recorded again).
|
|
365
|
+
*/
|
|
366
|
+
export async function adoptable(
|
|
367
|
+
pid: number,
|
|
368
|
+
): Promise<{ info: ProcessInfo; record: boolean } | undefined> {
|
|
369
|
+
const info = await readProcess(pid);
|
|
370
|
+
if (!info) return undefined;
|
|
371
|
+
if (WINDOWS) return { info, record: false };
|
|
372
|
+
return info.pgid === info.pid ? { info, record: true } : undefined;
|
|
373
|
+
}
|
package/src/processes/child.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* ```
|
|
11
11
|
*/
|
|
12
12
|
import { type JsonRpcParams, RpcPeer } from "@mostra/protocol";
|
|
13
|
+
import { WINDOWS } from "../platform/index.ts";
|
|
13
14
|
|
|
14
15
|
/** Options for {@link connectToSupervisor}. */
|
|
15
16
|
export interface SupervisorConnectionOptions {
|
|
@@ -56,12 +57,17 @@ export function connectToSupervisor(
|
|
|
56
57
|
};
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* Signals this child's whole process group (it leads it) and exits. On Windows there is no group
|
|
62
|
+
* to signal: the child's gate ends its Job Object, descendants included, once the child exits.
|
|
63
|
+
*/
|
|
60
64
|
function exitWithGroup(): void {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
+
if (!WINDOWS) {
|
|
66
|
+
try {
|
|
67
|
+
process.kill(-process.pid, "SIGTERM");
|
|
68
|
+
} catch {
|
|
69
|
+
// The group is already gone.
|
|
70
|
+
}
|
|
65
71
|
}
|
|
66
72
|
process.exit(0);
|
|
67
73
|
}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { delimiter, dirname } from "node:path";
|
|
9
9
|
import type { Environment } from "../log.ts";
|
|
10
|
+
import { WINDOWS, WINDOWS_SYSTEM_VARIABLES } from "../platform/index.ts";
|
|
10
11
|
|
|
11
12
|
/** Variables an artifact's processes need to work like an ordinary shell's programs. */
|
|
12
13
|
const PASSED: ReadonlySet<string> = new Set([
|
|
@@ -43,6 +44,12 @@ const PASSED: ReadonlySet<string> = new Set([
|
|
|
43
44
|
"SSL_CERT_DIR",
|
|
44
45
|
]);
|
|
45
46
|
|
|
47
|
+
/** What Windows programs need besides the variables above (`platform`'s one list). */
|
|
48
|
+
const PASSED_WINDOWS: ReadonlySet<string> = new Set(
|
|
49
|
+
WINDOWS_SYSTEM_VARIABLES.map((name) => name.toUpperCase()),
|
|
50
|
+
);
|
|
51
|
+
const PASSED_UPPER: ReadonlySet<string> = new Set([...PASSED].map((name) => name.toUpperCase()));
|
|
52
|
+
|
|
46
53
|
/** npm's own configuration channel: the user's registry, scopes and proxies for installs. */
|
|
47
54
|
const NPM_CONFIG = /^npm_config_/i;
|
|
48
55
|
|
|
@@ -53,12 +60,24 @@ const NPM_CONFIG = /^npm_config_/i;
|
|
|
53
60
|
*/
|
|
54
61
|
export function artifactEnvironment(env: Environment): Environment {
|
|
55
62
|
const result: Record<string, string> = {};
|
|
63
|
+
// On Windows `Path` and `PATH` are one variable; the one given keeps its own name.
|
|
64
|
+
let pathName = "PATH";
|
|
56
65
|
for (const [name, value] of Object.entries(env)) {
|
|
57
66
|
if (value === undefined) continue;
|
|
58
|
-
if (
|
|
67
|
+
if (WINDOWS) {
|
|
68
|
+
const upper = name.toUpperCase();
|
|
69
|
+
if (upper === "PATH") pathName = name;
|
|
70
|
+
if (PASSED_UPPER.has(upper) || PASSED_WINDOWS.has(upper) || NPM_CONFIG.test(name)) {
|
|
71
|
+
result[name] = value;
|
|
72
|
+
}
|
|
73
|
+
} else if (PASSED.has(name) || NPM_CONFIG.test(name)) {
|
|
74
|
+
result[name] = value;
|
|
75
|
+
}
|
|
59
76
|
}
|
|
60
77
|
const own = dirname(process.execPath);
|
|
61
|
-
const path = result[
|
|
62
|
-
|
|
78
|
+
const path = result[pathName] ?? (WINDOWS ? "" : "/usr/bin:/bin");
|
|
79
|
+
const first = path.split(delimiter)[0] ?? "";
|
|
80
|
+
const already = WINDOWS ? first.toLowerCase() === own.toLowerCase() : first === own;
|
|
81
|
+
result[pathName] = already ? path : path === "" ? own : `${own}${delimiter}${path}`;
|
|
63
82
|
return result;
|
|
64
83
|
}
|
package/src/processes/index.ts
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
* The process manager (RT-09): every child in its own process group, recorded with PID and start
|
|
3
3
|
* time, reaped after a supervisor crash, with typed JSON-RPC messages over Node IPC.
|
|
4
4
|
*/
|
|
5
|
+
|
|
6
|
+
export { listProcesses, readProcess } from "../platform/index.ts";
|
|
5
7
|
export {
|
|
6
8
|
connectToSupervisor,
|
|
7
9
|
type SupervisorConnection,
|
|
8
10
|
type SupervisorConnectionOptions,
|
|
9
11
|
} from "./child.ts";
|
|
10
12
|
export { artifactEnvironment } from "./environment.ts";
|
|
11
|
-
export { isSameProcess, listProcesses, readProcess } from "./identity.ts";
|
|
12
13
|
export {
|
|
13
14
|
type ChildExit,
|
|
14
15
|
type ChildHandle,
|