@powerhousedao/host-core 6.4.0-next.3 → 6.4.0-next.4
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/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
- package/dist/compound-BLhEewO6.d.mts.map +1 -0
- package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
- package/dist/compound-g6x_KkWp.mjs.map +1 -0
- package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
- package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
- package/dist/control-channel.d.mts +2 -2
- package/dist/control-channel.mjs +358 -47
- package/dist/control-channel.mjs.map +1 -1
- package/dist/host-entry-B8n_590_.mjs +188 -0
- package/dist/host-entry-B8n_590_.mjs.map +1 -0
- package/dist/index.d.mts +68 -102
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -3
- package/dist/index.mjs.map +1 -1
- package/dist/instance-C6uugZ32.d.mts +165 -0
- package/dist/instance-C6uugZ32.d.mts.map +1 -0
- package/dist/instance.d.mts +3 -0
- package/dist/instance.mjs +145 -0
- package/dist/instance.mjs.map +1 -0
- package/dist/kill-tree.d.mts +2 -0
- package/dist/kill-tree.d.mts.map +1 -1
- package/dist/kill-tree.mjs +1 -1
- package/dist/kill-tree.mjs.map +1 -1
- package/dist/run-record-C6oTZF_C.mjs +1077 -0
- package/dist/run-record-C6oTZF_C.mjs.map +1 -0
- package/dist/runners/compound.d.mts +1 -1
- package/dist/runners/compound.mjs +2 -1
- package/dist/runners/compound.mjs.map +1 -1
- package/dist/spawn-host-DWroRe1S.d.mts +107 -0
- package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
- package/dist/supervisor-record.d.mts +88 -0
- package/dist/supervisor-record.d.mts.map +1 -0
- package/dist/supervisor-record.mjs +127 -0
- package/dist/supervisor-record.mjs.map +1 -0
- package/dist/supervisor.d.mts +205 -0
- package/dist/supervisor.d.mts.map +1 -0
- package/dist/supervisor.mjs +905 -0
- package/dist/supervisor.mjs.map +1 -0
- package/package.json +21 -3
- package/dist/compound-L62ALvYc.d.mts.map +0 -1
- package/dist/compound-Q9sZSEZF.mjs.map +0 -1
- package/dist/control-channel-eqvyUF03.d.mts +0 -123
- package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
import { _ as writeOwnerOnlyFile, a as processStartedAtMs, c as recordKeyOf, n as isPidAlive, p as runRecordSchema, r as listRunRecords, x as instanceRunDir, y as instanceKey } from "./run-record-C6oTZF_C.mjs";
|
|
2
|
+
import { ControlError, callControl, controlProtocolOf, openControlChannel } from "./control-channel.mjs";
|
|
3
|
+
import { instanceOfRecord, restartDecision, runningInstance } from "./instance.mjs";
|
|
4
|
+
import { a as STOP_ON_STDIN_ENV, i as stopsOnStdin, n as phCliEntryVersion, r as resolvePhCliEntry, t as childEnv, u as requestStop } from "./host-entry-B8n_590_.mjs";
|
|
5
|
+
import { killTree, treePids } from "./kill-tree.mjs";
|
|
6
|
+
import { SUPERVISOR_HOME_ENV, findSupervisor, readSupervisorRecord, silentSupervisorMessage, supervisorHome, supervisorLockHolder, supervisorLockPath, supervisorRecordPath, supervisorRecordSchema, supervisorRecorded } from "./supervisor-record.mjs";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { execFile, spawn } from "node:child_process";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
//#region src/process-tree.ts
|
|
14
|
+
/**
|
|
15
|
+
* The processes below a supervised one, so that those it leaves behind when
|
|
16
|
+
* it ends by itself can be ended too. A process that exits takes no
|
|
17
|
+
* descendant with it: on Windows `taskkill /T` no longer finds them once
|
|
18
|
+
* their parent is gone, elsewhere they are handed to init.
|
|
19
|
+
*/
|
|
20
|
+
/** Windows: every process as `pid parent created`, created in ticks. */
|
|
21
|
+
function windowsProcessTable() {
|
|
22
|
+
const powershell = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
execFile(powershell, [
|
|
25
|
+
"-NoProfile",
|
|
26
|
+
"-NonInteractive",
|
|
27
|
+
"-Command",
|
|
28
|
+
"Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.Ticks)\" }"
|
|
29
|
+
], {
|
|
30
|
+
windowsHide: true,
|
|
31
|
+
timeout: 2e4,
|
|
32
|
+
encoding: "utf8"
|
|
33
|
+
}, (error, stdout) => {
|
|
34
|
+
if (error) {
|
|
35
|
+
resolve([]);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
resolve(stdout.split(/\r?\n/).map((line) => line.trim().split(/\s+/).map(Number)).filter((row) => Number.isInteger(row[0]) && Number.isInteger(row[1])).map(([pid, parent, created]) => [
|
|
39
|
+
pid,
|
|
40
|
+
parent,
|
|
41
|
+
created || 0
|
|
42
|
+
]));
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The pids of every descendant of `root`, without `root`. Empty when the
|
|
48
|
+
* process table cannot be read.
|
|
49
|
+
*/
|
|
50
|
+
async function descendantPids(root) {
|
|
51
|
+
if (process.platform !== "win32") return treePids(root).slice(1);
|
|
52
|
+
const table = await windowsProcessTable();
|
|
53
|
+
const created = new Map(table.map(([pid, , at]) => [pid, at]));
|
|
54
|
+
const tree = [root];
|
|
55
|
+
for (let i = 0; i < tree.length; i++) {
|
|
56
|
+
const parent = tree[i];
|
|
57
|
+
const parentCreated = created.get(parent) ?? 0;
|
|
58
|
+
for (const [pid, ppid, at] of table) {
|
|
59
|
+
if (ppid !== parent || tree.includes(pid) || at < parentCreated) continue;
|
|
60
|
+
tree.push(pid);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return tree.slice(1);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Ends, with their trees, the processes of `pids` that still run and started
|
|
67
|
+
* before `listedAt` (when the list was taken: a pid given to a newer process
|
|
68
|
+
* since is left alone). Returns the pids it ended.
|
|
69
|
+
*/
|
|
70
|
+
function killSurvivors(pids, listedAt) {
|
|
71
|
+
const killed = [];
|
|
72
|
+
for (const pid of pids) {
|
|
73
|
+
if (!isPidAlive(pid)) continue;
|
|
74
|
+
const started = processStartedAtMs(pid);
|
|
75
|
+
if (started === void 0 || started > listedAt) continue;
|
|
76
|
+
killTree(pid, "SIGKILL");
|
|
77
|
+
killed.push(pid);
|
|
78
|
+
}
|
|
79
|
+
return killed;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/supervisor-client.ts
|
|
83
|
+
/** Takes a lease. The connection does not keep this process running. */
|
|
84
|
+
function holdSupervisorLease(control) {
|
|
85
|
+
const id = randomUUID();
|
|
86
|
+
const abort = new AbortController();
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
let held = false;
|
|
89
|
+
const waiting = setInterval(() => void 0, 1e3);
|
|
90
|
+
const ended = callControl(control, "lease", { id }, {
|
|
91
|
+
unref: true,
|
|
92
|
+
signal: abort.signal,
|
|
93
|
+
onOutput: () => {
|
|
94
|
+
if (held) return;
|
|
95
|
+
held = true;
|
|
96
|
+
clearInterval(waiting);
|
|
97
|
+
resolve({
|
|
98
|
+
id,
|
|
99
|
+
ended,
|
|
100
|
+
release: () => {
|
|
101
|
+
abort.abort();
|
|
102
|
+
return ended;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}).then(() => {
|
|
107
|
+
clearInterval(waiting);
|
|
108
|
+
if (!held) reject(/* @__PURE__ */ new Error("The supervisor did not hold the lease."));
|
|
109
|
+
}, (error) => {
|
|
110
|
+
clearInterval(waiting);
|
|
111
|
+
if (!held) reject(error instanceof Error ? error : new Error(String(error)));
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** What the supervisor holds, and what else runs on `dataDir`. */
|
|
116
|
+
async function listSupervised(control, dataDir, options = {}) {
|
|
117
|
+
return await callControl(control, "list", dataDir === void 0 ? {} : { dataDir }, options);
|
|
118
|
+
}
|
|
119
|
+
async function startSupervised(control, params, options = {}) {
|
|
120
|
+
return await callControl(control, "start", params, options);
|
|
121
|
+
}
|
|
122
|
+
async function stopSupervised(control, handle) {
|
|
123
|
+
return (await callControl(control, "stop", { handle })).instance;
|
|
124
|
+
}
|
|
125
|
+
async function restartSupervised(control, handle, options = {}) {
|
|
126
|
+
return (await callControl(control, "restart", { handle }, options)).instance;
|
|
127
|
+
}
|
|
128
|
+
async function supervisedLogs(control, handle, lines) {
|
|
129
|
+
return await callControl(control, "logs", {
|
|
130
|
+
handle,
|
|
131
|
+
...lines === void 0 ? {} : { lines }
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** Stops the supervisor, and with it what it holds. */
|
|
135
|
+
async function shutdownSupervisor(control) {
|
|
136
|
+
return await callControl(control, "shutdown");
|
|
137
|
+
}
|
|
138
|
+
const EXITED_POLL_MS = 500;
|
|
139
|
+
/**
|
|
140
|
+
* `spawnHost` through the supervisor: the instance is the supervisor's
|
|
141
|
+
* child, not this process's. `existing` is set when the key ran already;
|
|
142
|
+
* its `stop()` then leaves it running, as `spawnHost`'s does. Aborting
|
|
143
|
+
* `signal` while it starts stops it.
|
|
144
|
+
*/
|
|
145
|
+
async function startSupervisedHost(control, params, options = {}) {
|
|
146
|
+
const { instance, started } = await startSupervised(control, params, { ...options.signal ? { signal: options.signal } : {} });
|
|
147
|
+
if (!instance.record) throw new Error(`${params.host} runs under the supervisor (pid ${instance.pid}) without a run record this version reads: ${instance.missing.join("; ")}.`);
|
|
148
|
+
const record = instance.record;
|
|
149
|
+
const exit = {
|
|
150
|
+
code: null,
|
|
151
|
+
signal: null,
|
|
152
|
+
forced: false
|
|
153
|
+
};
|
|
154
|
+
const exited = new Promise((resolve) => {
|
|
155
|
+
const timer = setInterval(() => {
|
|
156
|
+
if (isPidAlive(instance.pid)) return;
|
|
157
|
+
clearInterval(timer);
|
|
158
|
+
resolve(exit);
|
|
159
|
+
}, EXITED_POLL_MS);
|
|
160
|
+
timer.unref();
|
|
161
|
+
});
|
|
162
|
+
const mine = started && instance.mine;
|
|
163
|
+
return {
|
|
164
|
+
handle: instance.handle,
|
|
165
|
+
lifetime: instance.lifetime,
|
|
166
|
+
instance,
|
|
167
|
+
pid: instance.pid,
|
|
168
|
+
dataDir: instance.dataDir,
|
|
169
|
+
record,
|
|
170
|
+
outputs: record.outputs,
|
|
171
|
+
members: record.members,
|
|
172
|
+
...mine ? {} : { existing: true },
|
|
173
|
+
exited,
|
|
174
|
+
stop: async () => {
|
|
175
|
+
if (!mine) return exit;
|
|
176
|
+
try {
|
|
177
|
+
const stopped = await stopSupervised(control, instance.handle);
|
|
178
|
+
if (stopped.exit) {
|
|
179
|
+
exit.code = stopped.exit.code;
|
|
180
|
+
exit.signal = stopped.exit.signal;
|
|
181
|
+
exit.forced = stopped.exit.forced;
|
|
182
|
+
}
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (!(error instanceof ControlError && error.code === "unreachable")) throw error;
|
|
185
|
+
}
|
|
186
|
+
return exit;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/supervisor.ts
|
|
192
|
+
const startParamsSchema = z.object({
|
|
193
|
+
host: z.string().min(1),
|
|
194
|
+
projectDir: z.string().min(1),
|
|
195
|
+
/** The instance's data folder (default: the project folder). */
|
|
196
|
+
dataDir: z.string().min(1).optional(),
|
|
197
|
+
verb: z.string().min(1).optional(),
|
|
198
|
+
/** What follows `ph run <host> [verb]`. */
|
|
199
|
+
argv: z.array(z.string()).optional(),
|
|
200
|
+
/** The entry's arguments in place of `run <host> [verb] -- <argv>`, for a
|
|
201
|
+
* project whose version starts the host another way. */
|
|
202
|
+
args: z.array(z.string()).optional(),
|
|
203
|
+
/** Merged over the base env; may not set PH_USER_DATA_DIR. */
|
|
204
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
205
|
+
/** The env the instance starts from, as the caller has it (default: a
|
|
206
|
+
* clean one, see `childEnv`). */
|
|
207
|
+
baseEnv: z.record(z.string(), z.string()).optional(),
|
|
208
|
+
lifetime: z.enum(["caller", "supervisor"]).optional(),
|
|
209
|
+
/** The caller's lease; needed to start with the caller. */
|
|
210
|
+
lease: z.string().min(1).optional(),
|
|
211
|
+
readyTimeoutMs: z.number().int().positive().optional(),
|
|
212
|
+
stopTimeoutMs: z.number().int().positive().optional(),
|
|
213
|
+
/** Both output streams are appended here (default: a file under the
|
|
214
|
+
* supervisor's `logs/`). */
|
|
215
|
+
logFile: z.string().min(1).optional(),
|
|
216
|
+
/** `optional`: a host that has written no run record when the ready
|
|
217
|
+
* timeout ends counts as running (default: it is stopped, and the start
|
|
218
|
+
* fails). */
|
|
219
|
+
record: z.enum(["required", "optional"]).optional(),
|
|
220
|
+
/** Applied here when it ends on its own after it was ready (see
|
|
221
|
+
* `restartDecision`). The supervisor is then the one party that restarts
|
|
222
|
+
* it: its caller must not. */
|
|
223
|
+
restart: z.object({
|
|
224
|
+
enabled: z.boolean().optional(),
|
|
225
|
+
maxRetries: z.number().int().min(0),
|
|
226
|
+
delay: z.number().min(0)
|
|
227
|
+
}).optional()
|
|
228
|
+
});
|
|
229
|
+
const handleParamsSchema = z.object({ handle: z.string().min(1) });
|
|
230
|
+
const listParamsSchema = z.object({
|
|
231
|
+
/** Also lists what runs on this data folder. */
|
|
232
|
+
dataDir: z.string().min(1).optional() });
|
|
233
|
+
const logsParamsSchema = handleParamsSchema.extend({ lines: z.number().int().positive().optional() });
|
|
234
|
+
const leaseParamsSchema = z.object({ id: z.string().min(1) });
|
|
235
|
+
function parse(schema, params) {
|
|
236
|
+
const parsed = schema.safeParse(params ?? {});
|
|
237
|
+
if (!parsed.success) throw new Error(`Bad parameters: ${parsed.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`).join("; ")}`);
|
|
238
|
+
return parsed.data;
|
|
239
|
+
}
|
|
240
|
+
const READY_TIMEOUT_MS = 12e4;
|
|
241
|
+
const STOP_TIMEOUT_MS = 3e4;
|
|
242
|
+
/** How long a host that reads no stdin is given before it is asked again. */
|
|
243
|
+
const STOP_ASK_AGAIN_MS = 3e3;
|
|
244
|
+
const POLL_MS = 100;
|
|
245
|
+
const TAIL_BYTES = 8192;
|
|
246
|
+
/** Ended instances kept for `list` and `logs`. */
|
|
247
|
+
const MAX_EXITED = 20;
|
|
248
|
+
const LOCK_WAIT_MS = 1e4;
|
|
249
|
+
const sleep = (ms) => new Promise((resolve) => {
|
|
250
|
+
setTimeout(resolve, ms);
|
|
251
|
+
});
|
|
252
|
+
/** The record files under a data folder's `.ph/run/`, any version. */
|
|
253
|
+
function runFiles(dataDir) {
|
|
254
|
+
const files = [];
|
|
255
|
+
const walk = (dir, depth) => {
|
|
256
|
+
let entries;
|
|
257
|
+
try {
|
|
258
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
259
|
+
} catch {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
for (const entry of entries) {
|
|
263
|
+
const at = path.join(dir, entry.name);
|
|
264
|
+
if (entry.isFile() && entry.name.endsWith(".json")) files.push(at);
|
|
265
|
+
else if (entry.isDirectory() && depth < 2) walk(at, depth + 1);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
walk(instanceRunDir({ dataDir }), 0);
|
|
269
|
+
return files;
|
|
270
|
+
}
|
|
271
|
+
/** The record the process `pid` wrote under `dataDir`: `record` when this
|
|
272
|
+
* version reads it, `file` alone when it is of another shape. */
|
|
273
|
+
function recordOfPid(dataDir, pid) {
|
|
274
|
+
let other;
|
|
275
|
+
for (const file of runFiles(dataDir)) {
|
|
276
|
+
let raw;
|
|
277
|
+
try {
|
|
278
|
+
raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
279
|
+
} catch {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (raw?.pid !== pid) continue;
|
|
283
|
+
const parsed = runRecordSchema.safeParse(raw);
|
|
284
|
+
if (parsed.success) return {
|
|
285
|
+
file,
|
|
286
|
+
record: parsed.data
|
|
287
|
+
};
|
|
288
|
+
other = { file };
|
|
289
|
+
}
|
|
290
|
+
return other;
|
|
291
|
+
}
|
|
292
|
+
function tailOf(file, from) {
|
|
293
|
+
try {
|
|
294
|
+
const { size } = fs.statSync(file);
|
|
295
|
+
const start = Math.max(from, size - TAIL_BYTES);
|
|
296
|
+
const fd = fs.openSync(file, "r");
|
|
297
|
+
try {
|
|
298
|
+
const buffer = Buffer.alloc(Math.max(0, size - start));
|
|
299
|
+
fs.readSync(fd, buffer, 0, buffer.length, start);
|
|
300
|
+
return buffer.toString("utf8");
|
|
301
|
+
} finally {
|
|
302
|
+
fs.closeSync(fd);
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
305
|
+
return "";
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const NO_CHANNEL = "no control channel: commands are not forwarded to it (it is listed, and stopped through its stdin or by its process tree)";
|
|
309
|
+
/** What cannot be done with an instance, from what it recorded. */
|
|
310
|
+
function missingOf(found) {
|
|
311
|
+
if (!found) return ["no run record: readiness, ports and endpoints are unknown", NO_CHANNEL];
|
|
312
|
+
if (!found.record) return ["a run record of another version: ports and endpoints are not read", NO_CHANNEL];
|
|
313
|
+
const protocol = controlProtocolOf(found.record);
|
|
314
|
+
if (protocol === void 0) return [NO_CHANNEL];
|
|
315
|
+
if (protocol !== 2) return [`control protocol ${protocol}, this supervisor speaks 2: commands are not forwarded to it from this version`];
|
|
316
|
+
return [];
|
|
317
|
+
}
|
|
318
|
+
/** Takes the user's supervisor lock; returns the process that holds it. */
|
|
319
|
+
async function takeLock(env) {
|
|
320
|
+
const file = supervisorLockPath(env);
|
|
321
|
+
fs.mkdirSync(path.dirname(file), {
|
|
322
|
+
recursive: true,
|
|
323
|
+
mode: 448
|
|
324
|
+
});
|
|
325
|
+
const mine = JSON.stringify({
|
|
326
|
+
pid: process.pid,
|
|
327
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
328
|
+
});
|
|
329
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
330
|
+
try {
|
|
331
|
+
fs.writeFileSync(file, mine, { flag: "wx" });
|
|
332
|
+
} catch {
|
|
333
|
+
const holder = supervisorLockHolder(env);
|
|
334
|
+
if (holder) return holder;
|
|
335
|
+
fs.rmSync(file, { force: true });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
await sleep(50);
|
|
339
|
+
const holder = supervisorLockHolder(env);
|
|
340
|
+
if (holder && holder.pid !== process.pid) return holder;
|
|
341
|
+
if (holder) return void 0;
|
|
342
|
+
}
|
|
343
|
+
throw new Error(`Cannot take the supervisor lock ${file}.`);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Makes this process the supervisor of its OS user. With one running
|
|
347
|
+
* already (or recorded and silent) nothing is started and it is returned as
|
|
348
|
+
* `existing`.
|
|
349
|
+
*/
|
|
350
|
+
async function startSupervisor(options = {}) {
|
|
351
|
+
const env = options.env ?? process.env;
|
|
352
|
+
const home = supervisorHome(env);
|
|
353
|
+
const log = options.log ?? (() => void 0);
|
|
354
|
+
const mode = options.mode ?? "standalone";
|
|
355
|
+
const version = options.version ?? "unknown";
|
|
356
|
+
const holder = await takeLock(env);
|
|
357
|
+
if (holder) {
|
|
358
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
359
|
+
for (;;) {
|
|
360
|
+
const found = await findSupervisor(env);
|
|
361
|
+
if (found.status === "running" && found.record.pid === holder.pid) return { existing: found };
|
|
362
|
+
if (Date.now() >= deadline) return { existing: found.status === "silent" ? found : {
|
|
363
|
+
status: "silent",
|
|
364
|
+
pid: holder.pid,
|
|
365
|
+
reason: "it holds the lock and has recorded no channel."
|
|
366
|
+
} };
|
|
367
|
+
if (!isPidAlive(holder.pid)) return startSupervisor(options);
|
|
368
|
+
await sleep(200);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const lockFile = supervisorLockPath(env);
|
|
372
|
+
const recordFile = supervisorRecordPath(env);
|
|
373
|
+
let channel;
|
|
374
|
+
try {
|
|
375
|
+
channel = await openControlChannel({ mode });
|
|
376
|
+
} catch (error) {
|
|
377
|
+
fs.rmSync(lockFile, { force: true });
|
|
378
|
+
throw error;
|
|
379
|
+
}
|
|
380
|
+
const instances = /* @__PURE__ */ new Map();
|
|
381
|
+
const leases = /* @__PURE__ */ new Set();
|
|
382
|
+
/** Data folders an instance was started on, by key, with a project. */
|
|
383
|
+
const folders = /* @__PURE__ */ new Map();
|
|
384
|
+
let counter = 0;
|
|
385
|
+
let closing = false;
|
|
386
|
+
const view = (m) => {
|
|
387
|
+
const record = m.status === "exited" ? m.found?.record : currentRecord(m)?.record;
|
|
388
|
+
const facts = record ? instanceOfRecord(m.projectDir, record, { PH_USER_DATA_DIR: m.dataDir }) : void 0;
|
|
389
|
+
const protocol = controlProtocolOf(record);
|
|
390
|
+
return {
|
|
391
|
+
handle: m.handle,
|
|
392
|
+
host: m.params.host,
|
|
393
|
+
...m.params.verb === void 0 ? {} : { verb: m.params.verb },
|
|
394
|
+
projectDir: m.projectDir,
|
|
395
|
+
dataDir: m.dataDir,
|
|
396
|
+
pid: m.pid,
|
|
397
|
+
status: m.status !== "exited" ? m.status : m.restarts?.timer ? "restarting" : m.restarts?.failed !== void 0 ? "failed" : "exited",
|
|
398
|
+
mine: true,
|
|
399
|
+
lifetime: m.lifetime,
|
|
400
|
+
startedAt: m.startedAt,
|
|
401
|
+
logFile: m.logFile,
|
|
402
|
+
...m.runnerVersion === void 0 ? {} : { runnerVersion: m.runnerVersion },
|
|
403
|
+
...record ? { record } : {},
|
|
404
|
+
...facts ? {
|
|
405
|
+
ports: facts.ports,
|
|
406
|
+
endpoints: facts.endpoints
|
|
407
|
+
} : {},
|
|
408
|
+
...protocol === void 0 ? {} : { controlProtocol: protocol },
|
|
409
|
+
missing: m.status === "starting" ? [] : [...missingOf(m.recordless ? void 0 : m.found ?? {}), ...m.stopsOnStdin ? [] : [`a host of ${m.runnerVersion}: it does not stop with its stdin, so it is asked over its stop channel`]],
|
|
410
|
+
...m.exit ? { exit: m.exit } : {},
|
|
411
|
+
...m.restarts ? { restart: {
|
|
412
|
+
maxRetries: m.restarts.policy.maxRetries,
|
|
413
|
+
delay: m.restarts.policy.delay,
|
|
414
|
+
attempt: m.restarts.attempt,
|
|
415
|
+
...m.restarts.lastExit ? { lastExit: m.restarts.lastExit } : {},
|
|
416
|
+
...m.restarts.nextAt === void 0 ? {} : { nextAt: m.restarts.nextAt },
|
|
417
|
+
...m.restarts.failed === void 0 ? {} : { failed: m.restarts.failed }
|
|
418
|
+
} } : {}
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
const leaseHeld = (m) => m.lifetime !== "caller" || m.lease !== void 0 && leases.has(m.lease);
|
|
422
|
+
/** Drops the restart `m` waits for; true when there was one. */
|
|
423
|
+
const cancelRestart = (m) => {
|
|
424
|
+
const waiting = m.restarts?.timer;
|
|
425
|
+
if (!m.restarts || !waiting) return false;
|
|
426
|
+
clearTimeout(waiting);
|
|
427
|
+
delete m.restarts.timer;
|
|
428
|
+
delete m.restarts.nextAt;
|
|
429
|
+
return true;
|
|
430
|
+
};
|
|
431
|
+
/**
|
|
432
|
+
* The restart policy of an instance, applied here and nowhere else: the
|
|
433
|
+
* run `m` ended on its own. Not after a stop that was asked for, while the
|
|
434
|
+
* supervisor stops, or for a caller that has left.
|
|
435
|
+
*/
|
|
436
|
+
const afterOwnExit = (m) => {
|
|
437
|
+
const restarts = m.restarts;
|
|
438
|
+
if (!restarts || m.stopAsked || instances.get(m.handle) !== m) return;
|
|
439
|
+
restarts.lastExit = {
|
|
440
|
+
code: m.exit?.code ?? null,
|
|
441
|
+
signal: m.exit?.signal ?? null,
|
|
442
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
443
|
+
};
|
|
444
|
+
if (!leaseHeld(m)) return;
|
|
445
|
+
const decision = restartDecision(restarts.policy, {
|
|
446
|
+
attempt: restarts.attempt,
|
|
447
|
+
wasReady: restarts.everReady,
|
|
448
|
+
closing
|
|
449
|
+
});
|
|
450
|
+
if (decision.action === "give-up") {
|
|
451
|
+
if (!restarts.everReady) return;
|
|
452
|
+
restarts.failed = `it ended on its own (${restarts.lastExit.signal !== null ? `signal ${restarts.lastExit.signal}` : `code ${restarts.lastExit.code}`}) after ${decision.attempts} restart(s) in a row; its restart policy allows ${restarts.policy.maxRetries}`;
|
|
453
|
+
log(`[${m.handle}] ${m.params.host} is left ended: ${restarts.failed}.`);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (decision.action !== "restart") return;
|
|
457
|
+
restarts.attempt = decision.attempt;
|
|
458
|
+
restarts.nextAt = new Date(Date.now() + decision.delayMs).toISOString();
|
|
459
|
+
log(`[${m.handle}] ${m.params.host} ended on its own: restart ${decision.attempt} of ${restarts.policy.maxRetries} in ${decision.delayMs} ms.`);
|
|
460
|
+
restarts.timer = setTimeout(() => {
|
|
461
|
+
delete restarts.timer;
|
|
462
|
+
delete restarts.nextAt;
|
|
463
|
+
if (closing || m.stopAsked || instances.get(m.handle) !== m) return;
|
|
464
|
+
if (!leaseHeld(m)) return;
|
|
465
|
+
if ([...instances.values()].some((x) => x !== m && x.key === m.key && x.status !== "exited")) return;
|
|
466
|
+
try {
|
|
467
|
+
const next = launch(m.params, m.handle, void 0, restarts);
|
|
468
|
+
instances.set(m.handle, next);
|
|
469
|
+
log(`[${m.handle}] restarting ${m.params.host} (pid ${next.pid}).`);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
restarts.failed = `it could not be started again: ${error instanceof Error ? error.message : String(error)}`;
|
|
472
|
+
log(`[${m.handle}] ${m.params.host} is left ended: ${restarts.failed}`);
|
|
473
|
+
}
|
|
474
|
+
}, decision.delayMs);
|
|
475
|
+
};
|
|
476
|
+
const currentRecord = (m) => {
|
|
477
|
+
if (!m.found) return void 0;
|
|
478
|
+
const now = recordOfPid(m.dataDir, m.pid);
|
|
479
|
+
if (now) m.found = now;
|
|
480
|
+
return m.found;
|
|
481
|
+
};
|
|
482
|
+
/** Instances on the known data folders that something else started. */
|
|
483
|
+
const notMine = (extraDataDir) => {
|
|
484
|
+
const known = new Map(folders);
|
|
485
|
+
if (extraDataDir) {
|
|
486
|
+
const dataDir = path.resolve(extraDataDir);
|
|
487
|
+
known.set(instanceKey("", dataDir, {}).id, {
|
|
488
|
+
dataDir,
|
|
489
|
+
projectDir: dataDir
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const listed = [];
|
|
493
|
+
for (const { dataDir, projectDir } of known.values()) {
|
|
494
|
+
const readerEnv = { PH_USER_DATA_DIR: dataDir };
|
|
495
|
+
const own = [...instances.values()].filter((m) => m.dataDir === dataDir && m.status !== "exited");
|
|
496
|
+
const ownPids = new Set(own.map((m) => m.pid));
|
|
497
|
+
const memberHosts = new Set(own.flatMap((m) => Object.values(m.found?.record?.members ?? {}).map((x) => x.host)));
|
|
498
|
+
let records = [];
|
|
499
|
+
try {
|
|
500
|
+
records = listRunRecords(projectDir, readerEnv);
|
|
501
|
+
} catch {}
|
|
502
|
+
for (const record of records) {
|
|
503
|
+
const key = recordKeyOf(record);
|
|
504
|
+
if (ownPids.has(record.pid) || memberHosts.has(key)) continue;
|
|
505
|
+
if (!isPidAlive(record.pid)) continue;
|
|
506
|
+
const facts = instanceOfRecord(projectDir, record, readerEnv);
|
|
507
|
+
const protocol = controlProtocolOf(record);
|
|
508
|
+
listed.push({
|
|
509
|
+
handle: "-",
|
|
510
|
+
host: key,
|
|
511
|
+
verb: record.verb,
|
|
512
|
+
projectDir,
|
|
513
|
+
dataDir,
|
|
514
|
+
pid: record.pid,
|
|
515
|
+
status: "running",
|
|
516
|
+
mine: false,
|
|
517
|
+
startedAt: record.startedAt,
|
|
518
|
+
record,
|
|
519
|
+
ports: facts.ports,
|
|
520
|
+
endpoints: facts.endpoints,
|
|
521
|
+
...protocol === void 0 ? {} : { controlProtocol: protocol },
|
|
522
|
+
missing: ["not started by this supervisor: it is not stopped or restarted here"]
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return listed;
|
|
527
|
+
};
|
|
528
|
+
const find = (ref) => {
|
|
529
|
+
const exact = instances.get(ref);
|
|
530
|
+
if (exact) return exact;
|
|
531
|
+
const named = [...instances.values()].filter((m) => m.status !== "exited").filter((m) => m.params.host === ref || path.basename(m.projectDir) === ref);
|
|
532
|
+
if (named.length === 1) return named[0];
|
|
533
|
+
throw new Error(named.length > 1 ? `"${ref}" names ${named.length} instances (${named.map((m) => m.handle).join(", ")}): give the handle.` : `No instance "${ref}" is held by this supervisor.`);
|
|
534
|
+
};
|
|
535
|
+
const prune = () => {
|
|
536
|
+
const ended = [...instances.values()].filter((m) => m.status === "exited" && !m.restarts?.timer);
|
|
537
|
+
for (const m of ended.slice(0, Math.max(0, ended.length - MAX_EXITED))) instances.delete(m.handle);
|
|
538
|
+
};
|
|
539
|
+
function launch(params, handle, signal, carried) {
|
|
540
|
+
const projectDir = path.resolve(params.projectDir);
|
|
541
|
+
const dataDir = path.resolve(params.dataDir ?? projectDir);
|
|
542
|
+
const key = instanceKey(params.host, projectDir, { PH_USER_DATA_DIR: dataDir }).id;
|
|
543
|
+
const lifetime = params.lifetime ?? "caller";
|
|
544
|
+
const readyTimeoutMs = params.readyTimeoutMs ?? READY_TIMEOUT_MS;
|
|
545
|
+
const stopTimeoutMs = params.stopTimeoutMs ?? STOP_TIMEOUT_MS;
|
|
546
|
+
let entry;
|
|
547
|
+
try {
|
|
548
|
+
entry = resolvePhCliEntry(projectDir);
|
|
549
|
+
} catch {
|
|
550
|
+
throw new Error(`${projectDir} has neither @powerhousedao/ph-cli nor @powerhousedao/ph-run installed: there is nothing to start ${params.host} with.`);
|
|
551
|
+
}
|
|
552
|
+
const runnerVersion = phCliEntryVersion(entry);
|
|
553
|
+
const childEnvironment = childEnv(dataDir, {
|
|
554
|
+
...params.env,
|
|
555
|
+
[STOP_ON_STDIN_ENV]: "1"
|
|
556
|
+
}, params.baseEnv);
|
|
557
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
558
|
+
const logFile = params.logFile ?? path.join(home, "logs", `${handle}-${params.host.replace(/[^\w.-]+/g, "_")}.log`);
|
|
559
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
560
|
+
const args = params.args ?? [
|
|
561
|
+
"run",
|
|
562
|
+
params.host,
|
|
563
|
+
...params.verb === void 0 ? [] : [params.verb],
|
|
564
|
+
...params.argv?.length ? ["--", ...params.argv] : []
|
|
565
|
+
];
|
|
566
|
+
const logFd = fs.openSync(logFile, "a");
|
|
567
|
+
const logStart = fs.fstatSync(logFd).size;
|
|
568
|
+
let child;
|
|
569
|
+
try {
|
|
570
|
+
child = spawn(process.execPath, [entry, ...args], {
|
|
571
|
+
cwd: projectDir,
|
|
572
|
+
env: childEnvironment,
|
|
573
|
+
stdio: [
|
|
574
|
+
"pipe",
|
|
575
|
+
logFd,
|
|
576
|
+
logFd
|
|
577
|
+
],
|
|
578
|
+
windowsHide: true
|
|
579
|
+
});
|
|
580
|
+
} finally {
|
|
581
|
+
fs.closeSync(logFd);
|
|
582
|
+
}
|
|
583
|
+
child.stdin?.on("error", () => void 0);
|
|
584
|
+
if (child.pid === void 0) throw new Error(`${params.host} could not be started in ${projectDir}.`);
|
|
585
|
+
const pid = child.pid;
|
|
586
|
+
let forced = false;
|
|
587
|
+
let resolveExited;
|
|
588
|
+
const exited = new Promise((resolve) => resolveExited = resolve);
|
|
589
|
+
const what = `ph run ${params.host}`;
|
|
590
|
+
const m = {
|
|
591
|
+
handle,
|
|
592
|
+
key,
|
|
593
|
+
params,
|
|
594
|
+
projectDir,
|
|
595
|
+
dataDir,
|
|
596
|
+
lifetime,
|
|
597
|
+
...params.lease === void 0 ? {} : { lease: params.lease },
|
|
598
|
+
child,
|
|
599
|
+
pid,
|
|
600
|
+
status: "starting",
|
|
601
|
+
...carried ? { restarts: carried } : params.restart?.enabled ? { restarts: {
|
|
602
|
+
policy: params.restart,
|
|
603
|
+
attempt: 0,
|
|
604
|
+
everReady: false
|
|
605
|
+
} } : {},
|
|
606
|
+
stopAsked: false,
|
|
607
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
608
|
+
logFile,
|
|
609
|
+
...runnerVersion === void 0 ? {} : { runnerVersion },
|
|
610
|
+
stopsOnStdin: stopsOnStdin(runnerVersion),
|
|
611
|
+
recordless: false,
|
|
612
|
+
ready: Promise.resolve(),
|
|
613
|
+
exited,
|
|
614
|
+
stop: () => {
|
|
615
|
+
m.stopAsked = true;
|
|
616
|
+
cancelRestart(m);
|
|
617
|
+
return stop();
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
const clearRecords = () => {
|
|
621
|
+
for (const file of runFiles(dataDir)) try {
|
|
622
|
+
if (JSON.parse(fs.readFileSync(file, "utf8"))?.pid === pid) fs.rmSync(file, { force: true });
|
|
623
|
+
} catch {}
|
|
624
|
+
};
|
|
625
|
+
child.once("exit", (code, sig) => {
|
|
626
|
+
m.exit = {
|
|
627
|
+
code,
|
|
628
|
+
signal: sig,
|
|
629
|
+
forced
|
|
630
|
+
};
|
|
631
|
+
m.status = "exited";
|
|
632
|
+
clearRecords();
|
|
633
|
+
log(`[${handle}] ${params.host} ended (${sig !== null ? `signal ${sig}` : `code ${code}`}${forced ? ", killed" : ""}).`);
|
|
634
|
+
resolveExited();
|
|
635
|
+
if (!m.restarts) prune();
|
|
636
|
+
});
|
|
637
|
+
child.once("error", () => void 0);
|
|
638
|
+
let stopping;
|
|
639
|
+
function stop() {
|
|
640
|
+
stopping ??= (async () => {
|
|
641
|
+
if (m.status === "exited") return;
|
|
642
|
+
m.status = "stopping";
|
|
643
|
+
const listedAt = Date.now();
|
|
644
|
+
const below = await descendantPids(pid);
|
|
645
|
+
if (m.status !== "exited") {
|
|
646
|
+
let timers = [];
|
|
647
|
+
if (m.stopsOnStdin) child.stdin?.end();
|
|
648
|
+
else requestStop(pid);
|
|
649
|
+
if (m.stopsOnStdin && !m.found?.record) timers.push(setTimeout(() => void requestStop(pid), STOP_ASK_AGAIN_MS));
|
|
650
|
+
const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
|
|
651
|
+
timers.push(setTimeout(() => resolve(true), stopTimeoutMs));
|
|
652
|
+
})]);
|
|
653
|
+
for (const timer of timers) clearTimeout(timer);
|
|
654
|
+
timers = [];
|
|
655
|
+
if (timedOut) {
|
|
656
|
+
forced = true;
|
|
657
|
+
killTree(pid, "SIGKILL");
|
|
658
|
+
}
|
|
659
|
+
await exited;
|
|
660
|
+
}
|
|
661
|
+
const left = killSurvivors(below, listedAt);
|
|
662
|
+
if (left.length > 0) log(`[${handle}] ${params.host} left ${left.length} process(es) behind (${left.join(", ")}): ended.`);
|
|
663
|
+
clearRecords();
|
|
664
|
+
})();
|
|
665
|
+
return stopping;
|
|
666
|
+
}
|
|
667
|
+
m.ready = (async () => {
|
|
668
|
+
const deadline = Date.now() + readyTimeoutMs;
|
|
669
|
+
for (;;) {
|
|
670
|
+
if (m.status === "exited") {
|
|
671
|
+
const how = m.exit?.signal != null ? `signal ${m.exit.signal}` : `code ${m.exit?.code}`;
|
|
672
|
+
throw new StartFailed(`supervisor: ${what} exited (${how}) before writing its run record.`, tailOf(logFile, logStart));
|
|
673
|
+
}
|
|
674
|
+
if (m.status === "stopping" || signal?.aborted) {
|
|
675
|
+
await stop();
|
|
676
|
+
throw new StartFailed(`supervisor: ${what} was stopped before it was ready.`, tailOf(logFile, logStart));
|
|
677
|
+
}
|
|
678
|
+
const found = recordOfPid(dataDir, pid);
|
|
679
|
+
if (found) {
|
|
680
|
+
m.found = found;
|
|
681
|
+
m.status = "running";
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
if (Date.now() >= deadline) {
|
|
685
|
+
if (params.record === "optional") {
|
|
686
|
+
m.recordless = true;
|
|
687
|
+
m.status = "running";
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const tail = tailOf(logFile, logStart);
|
|
691
|
+
await stop();
|
|
692
|
+
throw new StartFailed(`supervisor: ${what} wrote no run record within ${readyTimeoutMs} ms.`, tail);
|
|
693
|
+
}
|
|
694
|
+
await Promise.race([sleep(POLL_MS), exited]);
|
|
695
|
+
}
|
|
696
|
+
})();
|
|
697
|
+
m.ready.catch(() => void 0);
|
|
698
|
+
const { restarts } = m;
|
|
699
|
+
if (restarts) m.ready.then(() => {
|
|
700
|
+
restarts.everReady = true;
|
|
701
|
+
restarts.attempt = 0;
|
|
702
|
+
}, () => void 0).then(() => exited).then(() => {
|
|
703
|
+
afterOwnExit(m);
|
|
704
|
+
prune();
|
|
705
|
+
});
|
|
706
|
+
return m;
|
|
707
|
+
}
|
|
708
|
+
async function start(params, call) {
|
|
709
|
+
if (closing) throw new Error("The supervisor is stopping.");
|
|
710
|
+
const projectDir = path.resolve(params.projectDir);
|
|
711
|
+
const dataDir = path.resolve(params.dataDir ?? projectDir);
|
|
712
|
+
const readerEnv = { PH_USER_DATA_DIR: dataDir };
|
|
713
|
+
const key = instanceKey(params.host, projectDir, readerEnv).id;
|
|
714
|
+
const lifetime = params.lifetime ?? "caller";
|
|
715
|
+
folders.set(instanceKey("", projectDir, readerEnv).id, {
|
|
716
|
+
dataDir,
|
|
717
|
+
projectDir
|
|
718
|
+
});
|
|
719
|
+
for (;;) {
|
|
720
|
+
const held = [...instances.values()].find((m) => m.key === key && m.status !== "exited");
|
|
721
|
+
if (!held) break;
|
|
722
|
+
if (held.status === "stopping") {
|
|
723
|
+
await held.exited;
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
await held.ready.catch(() => void 0);
|
|
727
|
+
if (held.status !== "running") continue;
|
|
728
|
+
return {
|
|
729
|
+
instance: view(held),
|
|
730
|
+
started: false
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
for (const m of instances.values()) if (m.key === key && cancelRestart(m)) log(`[${m.handle}] ${m.params.host} is started anew: its restart is dropped.`);
|
|
734
|
+
let theirs;
|
|
735
|
+
try {
|
|
736
|
+
theirs = runningInstance(projectDir, params.host, { env: readerEnv });
|
|
737
|
+
} catch {}
|
|
738
|
+
if (theirs) {
|
|
739
|
+
const other = notMine(dataDir).find((i) => i.pid === theirs.pid);
|
|
740
|
+
if (other) return {
|
|
741
|
+
instance: other,
|
|
742
|
+
started: false
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
if (lifetime === "caller" && !(params.lease && leases.has(params.lease))) throw new Error(`${params.host} was not started: an instance that lives with its caller needs the caller's lease (a "lease" request held open), and "${params.lease ?? ""}" is not held.`);
|
|
746
|
+
const handle = String(++counter);
|
|
747
|
+
const managed = launch({
|
|
748
|
+
...params,
|
|
749
|
+
lifetime
|
|
750
|
+
}, handle, call?.signal);
|
|
751
|
+
instances.set(handle, managed);
|
|
752
|
+
log(`[${handle}] starting ${params.host} in ${projectDir} (pid ${managed.pid}, with the ${lifetime}).`);
|
|
753
|
+
await managed.ready;
|
|
754
|
+
if (managed.lease && !leases.has(managed.lease) && lifetime === "caller") {
|
|
755
|
+
await managed.stop();
|
|
756
|
+
throw new Error(`${params.host} was stopped: its caller ended while it started.`);
|
|
757
|
+
}
|
|
758
|
+
log(`[${handle}] ${params.host} is running.`);
|
|
759
|
+
return {
|
|
760
|
+
instance: view(managed),
|
|
761
|
+
started: true
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
const stopAll = async (which) => {
|
|
765
|
+
const targets = [...instances.values()].filter((m) => (m.status !== "exited" || m.restarts?.timer) && which(m));
|
|
766
|
+
await Promise.all(targets.map((m) => m.stop()));
|
|
767
|
+
return targets.length;
|
|
768
|
+
};
|
|
769
|
+
channel.describe({
|
|
770
|
+
supervisor: true,
|
|
771
|
+
version
|
|
772
|
+
});
|
|
773
|
+
channel.handle("start", (params, call) => start(parse(startParamsSchema, params), call));
|
|
774
|
+
channel.handle("stop", async (params) => {
|
|
775
|
+
const m = find(parse(handleParamsSchema, params).handle);
|
|
776
|
+
await m.stop();
|
|
777
|
+
return { instance: view(m) };
|
|
778
|
+
});
|
|
779
|
+
channel.handle("restart", async (params, call) => {
|
|
780
|
+
const m = find(parse(handleParamsSchema, params).handle);
|
|
781
|
+
await m.stop();
|
|
782
|
+
if (m.lifetime === "caller" && !(m.lease && leases.has(m.lease))) throw new Error(`${m.params.host} was stopped and not started again: its caller has ended.`);
|
|
783
|
+
if (closing) throw new Error("The supervisor is stopping.");
|
|
784
|
+
const next = launch(m.params, m.handle, call.signal);
|
|
785
|
+
instances.set(m.handle, next);
|
|
786
|
+
log(`[${m.handle}] restarting ${m.params.host} (pid ${next.pid}).`);
|
|
787
|
+
await next.ready;
|
|
788
|
+
return { instance: view(next) };
|
|
789
|
+
});
|
|
790
|
+
channel.handle("list", (params) => {
|
|
791
|
+
const { dataDir } = parse(listParamsSchema, params);
|
|
792
|
+
return {
|
|
793
|
+
supervisor: {
|
|
794
|
+
pid: process.pid,
|
|
795
|
+
mode,
|
|
796
|
+
version,
|
|
797
|
+
home
|
|
798
|
+
},
|
|
799
|
+
instances: [...[...instances.values()].map(view), ...notMine(dataDir)]
|
|
800
|
+
};
|
|
801
|
+
});
|
|
802
|
+
channel.handle("logs", (params) => {
|
|
803
|
+
const { handle, lines } = parse(logsParamsSchema, params);
|
|
804
|
+
const m = find(handle);
|
|
805
|
+
let text = "";
|
|
806
|
+
try {
|
|
807
|
+
text = fs.readFileSync(m.logFile, "utf8").split("\n").slice(-(lines ?? 50) - 1).join("\n");
|
|
808
|
+
} catch {}
|
|
809
|
+
return {
|
|
810
|
+
text,
|
|
811
|
+
logFile: m.logFile
|
|
812
|
+
};
|
|
813
|
+
});
|
|
814
|
+
channel.handle("lease", async (params, call) => {
|
|
815
|
+
const { id } = parse(leaseParamsSchema, params);
|
|
816
|
+
if (leases.has(id)) throw new Error(`The lease "${id}" is held already.`);
|
|
817
|
+
leases.add(id);
|
|
818
|
+
call.write("stdout", "held\n");
|
|
819
|
+
await new Promise((resolve) => {
|
|
820
|
+
if (call.signal.aborted) resolve();
|
|
821
|
+
else call.signal.addEventListener("abort", () => resolve(), { once: true });
|
|
822
|
+
});
|
|
823
|
+
leases.delete(id);
|
|
824
|
+
const stopped = await stopAll((m) => m.lifetime === "caller" && m.lease === id);
|
|
825
|
+
if (stopped > 0) log(`A caller ended: ${stopped} instance(s) that lived with it stopped.`);
|
|
826
|
+
return { stopped };
|
|
827
|
+
});
|
|
828
|
+
let resolveStopped;
|
|
829
|
+
const stopped = new Promise((resolve) => resolveStopped = resolve);
|
|
830
|
+
const removeOwn = () => {
|
|
831
|
+
try {
|
|
832
|
+
if (JSON.parse(fs.readFileSync(recordFile, "utf8")).pid === process.pid) fs.rmSync(recordFile, { force: true });
|
|
833
|
+
} catch {}
|
|
834
|
+
try {
|
|
835
|
+
if (JSON.parse(fs.readFileSync(lockFile, "utf8")).pid === process.pid) fs.rmSync(lockFile, { force: true });
|
|
836
|
+
} catch {}
|
|
837
|
+
};
|
|
838
|
+
const onExit = () => {
|
|
839
|
+
for (const m of instances.values()) {
|
|
840
|
+
if (m.status === "exited") continue;
|
|
841
|
+
if (!m.found?.record || !m.stopsOnStdin) killTree(m.pid, "SIGKILL");
|
|
842
|
+
}
|
|
843
|
+
removeOwn();
|
|
844
|
+
};
|
|
845
|
+
process.once("exit", onExit);
|
|
846
|
+
let stoppingAll;
|
|
847
|
+
const stop = () => stoppingAll ??= (async () => {
|
|
848
|
+
closing = true;
|
|
849
|
+
const held = await stopAll(() => true);
|
|
850
|
+
if (held > 0) log(`Stopped ${held} instance(s).`);
|
|
851
|
+
removeOwn();
|
|
852
|
+
process.off("exit", onExit);
|
|
853
|
+
await channel.close();
|
|
854
|
+
resolveStopped();
|
|
855
|
+
})();
|
|
856
|
+
channel.handle("shutdown", () => {
|
|
857
|
+
const held = [...instances.values()].filter((m) => m.status !== "exited").length;
|
|
858
|
+
setTimeout(() => void stop(), 20);
|
|
859
|
+
return {
|
|
860
|
+
pid: process.pid,
|
|
861
|
+
held
|
|
862
|
+
};
|
|
863
|
+
});
|
|
864
|
+
let user = "";
|
|
865
|
+
try {
|
|
866
|
+
user = os.userInfo().username;
|
|
867
|
+
} catch {}
|
|
868
|
+
const record = {
|
|
869
|
+
version: 1,
|
|
870
|
+
pid: process.pid,
|
|
871
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
872
|
+
supervisorVersion: version,
|
|
873
|
+
mode,
|
|
874
|
+
user,
|
|
875
|
+
control: channel.record
|
|
876
|
+
};
|
|
877
|
+
try {
|
|
878
|
+
writeOwnerOnlyFile(recordFile, `${JSON.stringify(record, null, 2)}\n`);
|
|
879
|
+
} catch (error) {
|
|
880
|
+
process.off("exit", onExit);
|
|
881
|
+
removeOwn();
|
|
882
|
+
await channel.close();
|
|
883
|
+
throw error;
|
|
884
|
+
}
|
|
885
|
+
return { supervisor: {
|
|
886
|
+
record,
|
|
887
|
+
home,
|
|
888
|
+
ownerOnly: channel.ownerOnly,
|
|
889
|
+
instances: () => [...instances.values()].map(view),
|
|
890
|
+
stop,
|
|
891
|
+
stopped
|
|
892
|
+
} };
|
|
893
|
+
}
|
|
894
|
+
/** A start that failed, with the end of the instance's output. The message
|
|
895
|
+
* holds both, as `SpawnHostError`'s does. */
|
|
896
|
+
var StartFailed = class extends Error {
|
|
897
|
+
constructor(message, outputTail) {
|
|
898
|
+
super(outputTail ? `${message}\n--- output tail ---\n${outputTail}` : message);
|
|
899
|
+
this.name = "StartFailed";
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
//#endregion
|
|
903
|
+
export { SUPERVISOR_HOME_ENV, findSupervisor, holdSupervisorLease, listSupervised, readSupervisorRecord, restartSupervised, shutdownSupervisor, silentSupervisorMessage, startSupervised, startSupervisedHost, startSupervisor, stopSupervised, supervisedLogs, supervisorHome, supervisorLockHolder, supervisorLockPath, supervisorRecordPath, supervisorRecordSchema, supervisorRecorded };
|
|
904
|
+
|
|
905
|
+
//# sourceMappingURL=supervisor.mjs.map
|