@mark1russell7/service 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +114 -5
  2. package/build/{builder-BNAkpeTT.d.ts → builder-bXJqMe2p.d.ts} +3 -2
  3. package/build/{core-CWsGgr9J.d.ts → core-B1zbS4WY.d.ts} +4 -3
  4. package/build/{dial-JEJavY0U.d.ts → dial-CSGKVlZe.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/grpc.js +1 -1
  7. package/build/host.d.ts +556 -0
  8. package/build/host.js +1738 -0
  9. package/build/host.js.map +1 -0
  10. package/build/http-client.d.ts +3 -3
  11. package/build/http-client.js +1 -1
  12. package/build/http.d.ts +17 -3
  13. package/build/http.js +53 -10
  14. package/build/http.js.map +1 -1
  15. package/build/index.d.ts +44 -6
  16. package/build/index.js +78 -158
  17. package/build/index.js.map +1 -1
  18. package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
  19. package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
  20. package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
  21. package/build/limiter-CmC4vCjk.js.map +1 -0
  22. package/build/limiter.d.ts +3 -3
  23. package/build/limiter.js +1 -1
  24. package/build/{lifecycle-CCDLvXLF.d.ts → logger-DhFgh48y.d.ts} +25 -367
  25. package/build/{machine-DZMb_QEU.js → machine-DKWLZOqu.js} +7 -19
  26. package/build/machine-DKWLZOqu.js.map +1 -0
  27. package/build/mongodb.d.ts +3 -3
  28. package/build/mongodb.js +1 -1
  29. package/build/pg.d.ts +2 -2
  30. package/build/pg.js +1 -1
  31. package/build/ports-CZLzYK5d.d.ts +125 -0
  32. package/build/process-DG_im2zc.js +171 -0
  33. package/build/process-DG_im2zc.js.map +1 -0
  34. package/build/{queue-eLs5IruM.d.ts → queue-BjiGodqh.d.ts} +3 -2
  35. package/build/rabbitmq.d.ts +4 -4
  36. package/build/rabbitmq.js +1 -1
  37. package/build/redis.d.ts +3 -3
  38. package/build/redis.js +1 -1
  39. package/build/retrier-Bzkme_yM.js +51 -0
  40. package/build/retrier-Bzkme_yM.js.map +1 -0
  41. package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
  42. package/build/testing.d.ts +86 -3
  43. package/build/testing.js +238 -2
  44. package/build/testing.js.map +1 -1
  45. package/build/websocket.d.ts +3 -3
  46. package/build/websocket.js +1 -1
  47. package/package.json +6 -2
  48. package/build/limiter-pkBZUp-t.js.map +0 -1
  49. package/build/machine-DZMb_QEU.js.map +0 -1
package/build/host.js ADDED
@@ -0,0 +1,1738 @@
1
+ import { realClock } from "./clock.js";
2
+ import { s as isMessageShape } from "./process-DG_im2zc.js";
3
+ import { backoffProblems } from "./backoff.js";
4
+ import { t as retrier } from "./retrier-Bzkme_yM.js";
5
+ import { convertible, isQuantity, valueIn } from "@mark1russell7/quantity";
6
+ import { connect } from "node:net";
7
+ import { execFile, spawn } from "node:child_process";
8
+ import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { homedir, userInfo } from "node:os";
10
+ import { dirname } from "node:path";
11
+ //#region src/host/ports.ts
12
+ /** This function joins the parts of a path with the separator of the platform. */
13
+ const joinPath = (platform, ...parts) => {
14
+ const separator = platform === "win32" ? "\\" : "/";
15
+ const isSeparator = (char) => char === "/" || char === "\\";
16
+ const trim = (part, head) => {
17
+ let start = 0;
18
+ let end = part.length;
19
+ while (head && start < end && isSeparator(part[start])) start += 1;
20
+ while (end > start && isSeparator(part[end - 1])) end -= 1;
21
+ return part.slice(start, end);
22
+ };
23
+ return parts.map((part, at) => trim(part, at !== 0)).filter((part, at) => at === 0 || part !== "").join(separator);
24
+ };
25
+ //#endregion
26
+ //#region src/host/render.ts
27
+ const NAME$1 = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
28
+ const DAILY = /^([01]\d|2[0-3]):([0-5]\d)$/;
29
+ /** This function tells if a text has a control character. Such a character can add a line to a unit, or break the task file. */
30
+ const hasControl = (text) => {
31
+ for (let at = 0; at < text.length; at += 1) {
32
+ const code = text.charCodeAt(at);
33
+ if (code < 32 || code === 127) return true;
34
+ }
35
+ return false;
36
+ };
37
+ /** This function gives the time of a daily start, or null when the text is not `HH:MM`. */
38
+ const dailyTime = (text) => {
39
+ const found = DAILY.exec(text);
40
+ return found === null ? null : {
41
+ hour: found[1],
42
+ minute: found[2]
43
+ };
44
+ };
45
+ /** This function tells if a value is a time: a quantity in a unit of time. */
46
+ const isTime = (value) => isQuantity(value) && convertible(value.unit, "ms");
47
+ /** This function gives the problems of a service spec: each value that the task or the unit cannot use. */
48
+ const serviceProblems = (spec) => {
49
+ const problems = [];
50
+ if (!NAME$1.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, ".", "_" and "-"`);
51
+ const fields = [
52
+ ["description", spec.description],
53
+ ["program", spec.program],
54
+ ["stateDir", spec.stateDir],
55
+ ...spec.args.map((arg, at) => [`argument ${at}`, arg]),
56
+ ...spec.cwd === void 0 ? [] : [["cwd", spec.cwd]]
57
+ ];
58
+ for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);
59
+ if (spec.program === "") problems.push("the program is empty");
60
+ if (spec.stateDir === "") problems.push("the stateDir is empty");
61
+ if (spec.start !== "logon" && dailyTime(spec.start.daily) === null) problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);
62
+ if (spec.start !== "logon" && spec.restart !== null) problems.push("a daily job has no restart: give null");
63
+ if (spec.restart !== null && !(isTime(spec.restart.after) && valueIn(spec.restart.after, "ms") >= 0)) problems.push("the restart wait is not a time of zero or more");
64
+ if (spec.timeLimit !== void 0 && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, "ms") > 0)) problems.push("the time limit is not a time above zero");
65
+ if (spec.console !== void 0 && spec.console !== "hidden" && spec.console !== "visible") problems.push(`the console ${JSON.stringify(spec.console)} is not "hidden" or "visible"`);
66
+ return problems;
67
+ };
68
+ /**
69
+ * This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.
70
+ * It doubles each backslash before a quote and at the end. One pass keeps the time linear.
71
+ */
72
+ const windowsArg = (arg) => {
73
+ if (arg !== "" && !/[\s"]/.test(arg)) return arg;
74
+ let quoted = "\"";
75
+ let slashes = 0;
76
+ for (const char of arg) {
77
+ if (char === "\\") {
78
+ slashes += 1;
79
+ continue;
80
+ }
81
+ quoted += char === "\"" ? `${"\\".repeat(slashes * 2 + 1)}"` : `${"\\".repeat(slashes)}${char}`;
82
+ slashes = 0;
83
+ }
84
+ return `${quoted}${"\\".repeat(slashes * 2)}"`;
85
+ };
86
+ /**
87
+ * This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as
88
+ * `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,
89
+ * a quote, a backslash or a `;` goes in double quotes.
90
+ */
91
+ const systemdArg = (arg) => {
92
+ const escaped = arg.replace(/%/g, () => "%%").replace(/\$/g, () => "$$");
93
+ if (escaped !== "" && !/[\s"'\\;]/.test(escaped)) return escaped;
94
+ return `"${escaped.replace(/\\/g, () => "\\\\").replace(/"/g, () => "\\\"")}"`;
95
+ };
96
+ /** This function escapes a text for the content or an attribute of an XML element. */
97
+ const xmlText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
98
+ /** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */
99
+ const isoSeconds = (time) => `PT${Math.max(1, Math.ceil(valueIn(time, "s")))}S`;
100
+ /** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */
101
+ const repeatMinutes = (time) => Math.max(1, Math.ceil(valueIn(time, "min")));
102
+ /** This function gives the seconds of a restart wait for systemd, a whole number. */
103
+ const restartSeconds = (time) => Math.max(0, Math.ceil(valueIn(time, "s")));
104
+ const refuse = (spec) => {
105
+ const problems = serviceProblems(spec);
106
+ if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join("; ")}`);
107
+ };
108
+ /**
109
+ * This function gives the task file of Windows for a spec, as text. It is a pure function: the same
110
+ * spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.
111
+ * - A start at logon gets a logon trigger. With a restart, a time trigger also starts the task each few
112
+ * minutes. The task ignores a start while its program runs (`IgnoreNew`).
113
+ * - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).
114
+ * Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.
115
+ */
116
+ const renderTaskXml = (spec, context) => {
117
+ refuse(spec);
118
+ const user = xmlText(context.user);
119
+ const hidden = (spec.console ?? "hidden") === "hidden";
120
+ const command = hidden ? context.conhost : spec.program;
121
+ const args = (hidden ? [
122
+ "--headless",
123
+ spec.program,
124
+ ...spec.args
125
+ ] : [...spec.args]).map(windowsArg).join(" ");
126
+ const triggers = [];
127
+ if (spec.start === "logon") {
128
+ triggers.push(` <LogonTrigger>
129
+ <Enabled>true</Enabled>
130
+ <UserId>${user}</UserId>
131
+ </LogonTrigger>`);
132
+ if (spec.restart !== null) triggers.push(` <TimeTrigger>
133
+ <Enabled>true</Enabled>
134
+ <StartBoundary>2000-01-01T00:00:00</StartBoundary>
135
+ <Repetition>
136
+ <Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>
137
+ <StopAtDurationEnd>false</StopAtDurationEnd>
138
+ </Repetition>
139
+ </TimeTrigger>`);
140
+ } else {
141
+ const time = dailyTime(spec.start.daily);
142
+ triggers.push(` <CalendarTrigger>
143
+ <Enabled>true</Enabled>
144
+ <StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>
145
+ <ScheduleByDay>
146
+ <DaysInterval>1</DaysInterval>
147
+ </ScheduleByDay>
148
+ </CalendarTrigger>`);
149
+ }
150
+ const cwd = spec.cwd === void 0 ? "" : `\n <WorkingDirectory>${xmlText(spec.cwd)}</WorkingDirectory>`;
151
+ const limit = spec.timeLimit === void 0 ? "PT0S" : isoSeconds(spec.timeLimit);
152
+ return `<?xml version="1.0" encoding="UTF-16"?>
153
+ <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
154
+ <RegistrationInfo>
155
+ <Description>${xmlText(spec.description)}</Description>
156
+ <URI>\\${xmlText(spec.name)}</URI>
157
+ </RegistrationInfo>
158
+ <Triggers>
159
+ ${triggers.join("\n")}
160
+ </Triggers>
161
+ <Principals>
162
+ <Principal id="Author">
163
+ <UserId>${user}</UserId>
164
+ <LogonType>InteractiveToken</LogonType>
165
+ <RunLevel>LeastPrivilege</RunLevel>
166
+ </Principal>
167
+ </Principals>
168
+ <Settings>
169
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
170
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
171
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
172
+ <AllowHardTerminate>true</AllowHardTerminate>
173
+ <StartWhenAvailable>true</StartWhenAvailable>
174
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
175
+ <IdleSettings>
176
+ <StopOnIdleEnd>false</StopOnIdleEnd>
177
+ <RestartOnIdle>false</RestartOnIdle>
178
+ </IdleSettings>
179
+ <AllowStartOnDemand>true</AllowStartOnDemand>
180
+ <Enabled>true</Enabled>
181
+ <Hidden>false</Hidden>
182
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
183
+ <WakeToRun>false</WakeToRun>
184
+ <ExecutionTimeLimit>${limit}</ExecutionTimeLimit>
185
+ <Priority>5</Priority>
186
+ </Settings>
187
+ <Actions Context="Author">
188
+ <Exec>
189
+ <Command>${xmlText(windowsArg(command))}</Command>
190
+ <Arguments>${xmlText(args)}</Arguments>${cwd}
191
+ </Exec>
192
+ </Actions>
193
+ </Task>
194
+ `;
195
+ };
196
+ /** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */
197
+ const utf16le = (text) => {
198
+ const bytes = new Uint8Array(2 + text.length * 2);
199
+ bytes[0] = 255;
200
+ bytes[1] = 254;
201
+ for (let at = 0; at < text.length; at += 1) {
202
+ const unit = text.charCodeAt(at);
203
+ bytes[2 + at * 2] = unit & 255;
204
+ bytes[3 + at * 2] = unit >> 8;
205
+ }
206
+ return bytes;
207
+ };
208
+ /**
209
+ * This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.
210
+ * - A start at logon is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.
211
+ * - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.
212
+ */
213
+ const renderSystemdUnit = (spec) => {
214
+ refuse(spec);
215
+ const lines = [
216
+ "[Unit]",
217
+ `Description=${spec.description.replace(/%/g, "%%")}`,
218
+ "",
219
+ "[Service]"
220
+ ];
221
+ lines.push(spec.start === "logon" ? "Type=simple" : "Type=oneshot");
222
+ lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(" ")}`);
223
+ if (spec.cwd !== void 0) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, "%%")}`);
224
+ if (spec.restart !== null) lines.push("Restart=on-failure", `RestartSec=${restartSeconds(spec.restart.after)}`);
225
+ if (spec.timeLimit !== void 0) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, "s")))}`);
226
+ if (spec.start === "logon") lines.push("", "[Install]", "WantedBy=default.target");
227
+ return `${lines.join("\n")}\n`;
228
+ };
229
+ /** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon. It is a pure function. */
230
+ const renderSystemdTimer = (spec) => {
231
+ refuse(spec);
232
+ if (spec.start === "logon") return null;
233
+ const time = dailyTime(spec.start.daily);
234
+ return `${[
235
+ "[Unit]",
236
+ `Description=${spec.description.replace(/%/g, "%%")}`,
237
+ "",
238
+ "[Timer]",
239
+ `OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,
240
+ "Persistent=true",
241
+ "",
242
+ "[Install]",
243
+ "WantedBy=timers.target"
244
+ ].join("\n")}\n`;
245
+ };
246
+ //#endregion
247
+ //#region src/host/processes.ts
248
+ /**
249
+ * This margin is the time after a recorded start in which a process can start and still be the same
250
+ * process, in milliseconds. A start time on Linux comes in ticks of 10 ms, and a step of the wall clock moves a time.
251
+ */
252
+ const START_MARGIN_MS = 1e3;
253
+ /**
254
+ * This function tells if the process of a mark is alive and is the same process. Windows and Linux
255
+ * use a process ID again after a process stops. Thus a live process that started after the mark is a
256
+ * different process. A start time that the system does not give proves nothing, and the process counts as the same.
257
+ */
258
+ const sameProcess = async (mark, ports) => {
259
+ if (!Number.isInteger(mark.pid) || mark.pid <= 0) return false;
260
+ if (mark.pid === ports.self.pid) return Math.abs(mark.startedAt - ports.self.startedAt) <= START_MARGIN_MS;
261
+ if (!ports.processes.alive(mark.pid)) return false;
262
+ let started;
263
+ try {
264
+ started = await ports.processes.startOf(mark.pid);
265
+ } catch {
266
+ started = null;
267
+ }
268
+ return started === null || started <= mark.startedAt + 1e3;
269
+ };
270
+ /**
271
+ * This function stops a process and each process under it, by its ID only. It does not find a process by
272
+ * its name or its command line. On Windows, it starts `taskkill /T /F /PID <pid>`. On Linux, it sends
273
+ * SIGKILL to the process group of the ID, or to the process when it leads no group. It does not throw.
274
+ */
275
+ const stopTree = async (pid, ports) => {
276
+ if (!Number.isInteger(pid) || pid <= 0) return {
277
+ kind: "failed",
278
+ problem: `${pid} is not a process ID`
279
+ };
280
+ if (pid === ports.self.pid) return {
281
+ kind: "failed",
282
+ problem: "the host does not stop its own process"
283
+ };
284
+ if (!ports.processes.alive(pid)) return { kind: "absent" };
285
+ if (ports.platform === "win32") {
286
+ const result = await ports.commands.run("taskkill", [
287
+ "/T",
288
+ "/F",
289
+ "/PID",
290
+ String(pid)
291
+ ]).catch((error) => ({
292
+ code: 127,
293
+ out: error instanceof Error ? error.message : String(error)
294
+ }));
295
+ if (result.code === 0 || !ports.processes.alive(pid)) return { kind: "stopped" };
296
+ return {
297
+ kind: "failed",
298
+ problem: `taskkill gave the code ${result.code}: ${result.out}`
299
+ };
300
+ }
301
+ if (ports.processes.signalGroup(pid, "SIGKILL") || ports.processes.signal(pid, "SIGKILL")) return { kind: "stopped" };
302
+ return ports.processes.alive(pid) ? {
303
+ kind: "failed",
304
+ problem: `the signal SIGKILL did not go to the process ${pid}`
305
+ } : { kind: "absent" };
306
+ };
307
+ //#endregion
308
+ //#region src/host/discovery.ts
309
+ const isPort = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
310
+ /** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
311
+ const parseDiscovery = (text) => {
312
+ let value;
313
+ try {
314
+ value = JSON.parse(text);
315
+ } catch (error) {
316
+ return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;
317
+ }
318
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return "the file is not a JSON object";
319
+ const { pid, startedAt, port, url, extra } = value;
320
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return "the field pid is not a process ID";
321
+ if (typeof startedAt !== "string" || !Number.isFinite(Date.parse(startedAt))) return "the field startedAt is not an ISO time";
322
+ if (port !== null && port !== void 0 && !isPort(port)) return "the field port is not a port from 1 to 65535";
323
+ if (url !== null && url !== void 0 && typeof url !== "string") return "the field url is not a text";
324
+ if (extra !== void 0 && (typeof extra !== "object" || extra === null || Array.isArray(extra))) return "the field extra is not an object";
325
+ return {
326
+ pid,
327
+ startedAt,
328
+ port: isPort(port) ? port : null,
329
+ url: typeof url === "string" ? url : null,
330
+ ...extra === void 0 ? {} : { extra }
331
+ };
332
+ };
333
+ /** This function gives the discovery record of the process of the host, with its start time. */
334
+ const discoveryOf = (fields, ports) => ({
335
+ pid: ports.self.pid,
336
+ startedAt: new Date(ports.self.startedAt).toISOString(),
337
+ port: fields.port ?? null,
338
+ url: fields.url ?? null,
339
+ ...fields.extra === void 0 ? {} : { extra: fields.extra }
340
+ });
341
+ /** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
342
+ const writeDiscovery = async (path, record, ports) => {
343
+ await ports.files.write(path, `${JSON.stringify(record, null, 2)}\n`);
344
+ };
345
+ /**
346
+ * This function reads a discovery file and examines its process. It does not throw: a file that is not
347
+ * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
348
+ */
349
+ const readDiscovery = async (path, ports, options = {}) => {
350
+ const found = await examine(path, ports);
351
+ if (options.clean === true && (found.kind === "stale" || found.kind === "malformed")) try {
352
+ await ports.files.remove(path);
353
+ ports.logger?.log("info", `the host removed the ${found.kind} discovery file ${path}`, {
354
+ path,
355
+ kind: found.kind
356
+ });
357
+ } catch {}
358
+ return found;
359
+ };
360
+ const examine = async (path, ports) => {
361
+ let text;
362
+ try {
363
+ text = await ports.files.read(path);
364
+ } catch (error) {
365
+ return {
366
+ kind: "malformed",
367
+ problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
368
+ };
369
+ }
370
+ if (text === null) return { kind: "absent" };
371
+ const record = parseDiscovery(text);
372
+ if (typeof record === "string") return {
373
+ kind: "malformed",
374
+ problem: record
375
+ };
376
+ const mark = {
377
+ pid: record.pid,
378
+ startedAt: Date.parse(record.startedAt)
379
+ };
380
+ if (await sameProcess(mark, ports)) return {
381
+ kind: "running",
382
+ record
383
+ };
384
+ return {
385
+ kind: "stale",
386
+ record,
387
+ why: ports.processes.alive(record.pid) ? `the process ${record.pid} started after the record, thus it is a different process` : `the process ${record.pid} stopped`
388
+ };
389
+ };
390
+ /** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
391
+ const removeDiscovery = async (path, ports, pid = ports.self.pid) => {
392
+ try {
393
+ const text = await ports.files.read(path);
394
+ if (text === null) return false;
395
+ const record = parseDiscovery(text);
396
+ if (typeof record === "string" || record.pid !== pid) return false;
397
+ await ports.files.remove(path);
398
+ return true;
399
+ } catch {
400
+ return false;
401
+ }
402
+ };
403
+ //#endregion
404
+ //#region src/host/lock.ts
405
+ const isMark = (value) => {
406
+ if (typeof value !== "object" || value === null) return false;
407
+ const { pid, startedAt } = value;
408
+ return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && typeof startedAt === "number" && Number.isFinite(startedAt);
409
+ };
410
+ /** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */
411
+ const parseLockOwner = (text) => {
412
+ try {
413
+ const value = JSON.parse(text);
414
+ if (!isMark(value)) return null;
415
+ const child = value.child;
416
+ if (child !== void 0 && child !== null && !isMark(child)) return null;
417
+ return {
418
+ pid: value.pid,
419
+ startedAt: value.startedAt,
420
+ ...isMark(child) ? { child: {
421
+ pid: child.pid,
422
+ startedAt: child.startedAt
423
+ } } : {}
424
+ };
425
+ } catch {
426
+ return null;
427
+ }
428
+ };
429
+ /** This function gives the text of a lock file for an owner. */
430
+ const lockText = (owner) => `${JSON.stringify(owner)}\n`;
431
+ /** This function tells if the owner of a lock is alive: its process, or its child. */
432
+ const ownerAlive = async (owner, ports) => await sameProcess(owner, ports) || owner.child !== void 0 && await sameProcess(owner.child, ports);
433
+ const sleep = (ports, ms) => new Promise((resolve) => ports.clock.after(ms, resolve));
434
+ /**
435
+ * This function removes a lock file only when it has this text. The removal holds the removal lock
436
+ * `<path>.rm` for its read and its delete. Thus two processes that find the same stale lock do not
437
+ * remove each other's new lock. A removal lock whose owner stopped goes first.
438
+ */
439
+ const removeIfSame = async (path, text, ports) => {
440
+ const removal = `${path}.rm`;
441
+ const mine = lockText({
442
+ pid: ports.self.pid,
443
+ startedAt: ports.self.startedAt
444
+ });
445
+ if (!await ports.files.create(removal, mine)) {
446
+ const other = parseLockOwner(await ports.files.read(removal) ?? "");
447
+ if (other !== null && await ownerAlive(other, ports)) return false;
448
+ await ports.files.remove(removal);
449
+ if (!await ports.files.create(removal, mine)) return false;
450
+ }
451
+ try {
452
+ if (await ports.files.read(path) !== text) return false;
453
+ await ports.files.remove(path);
454
+ return true;
455
+ } finally {
456
+ if (await ports.files.read(removal) === mine) await ports.files.remove(removal);
457
+ }
458
+ };
459
+ /** This function examines a lock file. It does not throw. */
460
+ const inspectInstanceLock = async (path, ports) => {
461
+ try {
462
+ const text = await ports.files.read(path);
463
+ if (text === null) return { kind: "free" };
464
+ const owner = parseLockOwner(text);
465
+ if (owner === null) return {
466
+ kind: "malformed",
467
+ problem: "the lock file is not a lock record"
468
+ };
469
+ if (await ownerAlive(owner, ports)) return {
470
+ kind: "held",
471
+ owner
472
+ };
473
+ return {
474
+ kind: "stale",
475
+ owner,
476
+ why: `the owner process ${owner.pid} stopped`
477
+ };
478
+ } catch (error) {
479
+ return {
480
+ kind: "malformed",
481
+ problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
482
+ };
483
+ }
484
+ };
485
+ /**
486
+ * This function takes the lock of one instance: a lock file with the record of this process. Thus a
487
+ * second instance does not start. It does not throw.
488
+ * - A file whose owner and child stopped is stale: it goes, and the take tries again.
489
+ * - A malformed file can be the file of a take that writes at this time. The take reads it again after
490
+ * a pause, and after `tries` reads, it removes it.
491
+ * - A file whose owner or child is alive gives `held`.
492
+ */
493
+ const acquireInstanceLock = async (path, ports, options = {}) => {
494
+ const tries = options.tries ?? 3;
495
+ const pause = options.pause ?? 100;
496
+ const owner = {
497
+ pid: ports.self.pid,
498
+ startedAt: ports.self.startedAt,
499
+ ...options.child === void 0 ? {} : { child: options.child }
500
+ };
501
+ let recovered = null;
502
+ let malformed = 0;
503
+ try {
504
+ for (let attempt = 0; attempt < tries + 3; attempt += 1) {
505
+ const text = lockText(owner);
506
+ if (await ports.files.create(path, text)) {
507
+ ports.logger?.log("info", `the host took the lock ${path}`, {
508
+ path,
509
+ pid: owner.pid,
510
+ ...recovered === null ? {} : { recovered }
511
+ });
512
+ return {
513
+ kind: "acquired",
514
+ lock: held(path, owner, text, ports),
515
+ recovered
516
+ };
517
+ }
518
+ const found = await ports.files.read(path);
519
+ if (found === null) continue;
520
+ const other = parseLockOwner(found);
521
+ if (other === null) {
522
+ malformed += 1;
523
+ if (malformed < tries) {
524
+ await sleep(ports, pause);
525
+ continue;
526
+ }
527
+ if (await removeIfSame(path, found, ports)) recovered = "the lock file was not a lock record";
528
+ continue;
529
+ }
530
+ if (await ownerAlive(other, ports)) return {
531
+ kind: "held",
532
+ owner: other
533
+ };
534
+ if (await removeIfSame(path, found, ports)) {
535
+ recovered = `the owner process ${other.pid} stopped`;
536
+ ports.logger?.log("warn", `the host removed the stale lock ${path}: ${recovered}`, {
537
+ path,
538
+ owner: other
539
+ });
540
+ }
541
+ }
542
+ return {
543
+ kind: "failed",
544
+ problem: `the lock ${path} did not come free after ${tries + 3} tries`
545
+ };
546
+ } catch (error) {
547
+ return {
548
+ kind: "failed",
549
+ problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}`
550
+ };
551
+ }
552
+ };
553
+ /** This function gives the handle of a lock that this process holds. */
554
+ const held = (path, first, firstText, ports) => {
555
+ let owner = first;
556
+ let text = firstText;
557
+ let released = false;
558
+ let queue = Promise.resolve();
559
+ const enqueue = (work) => {
560
+ const next = queue.then(work);
561
+ queue = next.catch(() => {});
562
+ return next;
563
+ };
564
+ return {
565
+ path,
566
+ get owner() {
567
+ return owner;
568
+ },
569
+ update: (child) => enqueue(async () => {
570
+ if (released) return;
571
+ const next = {
572
+ pid: owner.pid,
573
+ startedAt: owner.startedAt,
574
+ ...child === null ? {} : { child }
575
+ };
576
+ const nextText = lockText(next);
577
+ await ports.files.write(path, nextText);
578
+ owner = next;
579
+ text = nextText;
580
+ }),
581
+ release: () => enqueue(async () => {
582
+ if (released) return;
583
+ released = true;
584
+ try {
585
+ await removeIfSame(path, text, ports);
586
+ } catch {}
587
+ })
588
+ };
589
+ };
590
+ //#endregion
591
+ //#region src/host/install.ts
592
+ /** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */
593
+ const unitDir = (ports) => {
594
+ const config = ports.env["XDG_CONFIG_HOME"];
595
+ return joinPath("linux", config === void 0 || config === "" ? joinPath("linux", ports.homeDir, ".config") : config, "systemd", "user");
596
+ };
597
+ /** This function gives the files of a service on the platform of the ports. */
598
+ const servicePaths = (spec, ports) => {
599
+ if (ports.platform === "win32") return {
600
+ unit: joinPath("win32", spec.stateDir, `${spec.name}.task.xml`),
601
+ timer: null
602
+ };
603
+ const dir = unitDir(ports);
604
+ return {
605
+ unit: joinPath("linux", dir, `${spec.name}.service`),
606
+ timer: spec.start === "logon" ? null : joinPath("linux", dir, `${spec.name}.timer`)
607
+ };
608
+ };
609
+ /** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */
610
+ const enabledUnit = (spec) => spec.start === "logon" ? `${spec.name}.service` : `${spec.name}.timer`;
611
+ /** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */
612
+ const conhostPath = (ports) => joinPath("win32", ports.env["SystemRoot"] ?? "%SystemRoot%", "System32", "conhost.exe");
613
+ const runner = (ports) => {
614
+ const commands = [];
615
+ return {
616
+ commands,
617
+ async run(file, args) {
618
+ let record;
619
+ try {
620
+ const result = await ports.commands.run(file, args);
621
+ record = {
622
+ file,
623
+ args,
624
+ code: result.code,
625
+ out: result.out.trim()
626
+ };
627
+ } catch (error) {
628
+ record = {
629
+ file,
630
+ args,
631
+ code: 127,
632
+ out: error instanceof Error ? error.message : String(error)
633
+ };
634
+ }
635
+ commands.push(record);
636
+ ports.logger?.log(record.code === 0 ? "debug" : "warn", `${file} ${args.join(" ")} gave the code ${record.code}`, { ...record });
637
+ return record;
638
+ }
639
+ };
640
+ };
641
+ const failed = (commands, record) => ({
642
+ kind: "failed",
643
+ commands,
644
+ problem: `${record.file} ${record.args.join(" ")} gave the code ${record.code}${record.out === "" ? "" : `: ${record.out}`}`
645
+ });
646
+ const problemOf = (error) => error instanceof Error ? error.message : String(error);
647
+ /**
648
+ * This function runs the steps of an operation. It refuses a spec with problems and a platform that
649
+ * is not Windows or Linux, and it catches each failure of the file system.
650
+ */
651
+ const operate = async (spec, ports, steps) => {
652
+ const problems = serviceProblems(spec);
653
+ if (problems.length > 0) return {
654
+ kind: "refused",
655
+ problems
656
+ };
657
+ if (ports.platform !== "win32" && ports.platform !== "linux") return {
658
+ kind: "unsupported",
659
+ platform: ports.platform
660
+ };
661
+ const run = runner(ports);
662
+ const files = [];
663
+ try {
664
+ const failure = await steps(run, files);
665
+ if (failure !== null) return failed(run.commands, failure);
666
+ } catch (error) {
667
+ return {
668
+ kind: "failed",
669
+ commands: run.commands,
670
+ problem: `the file system failed: ${problemOf(error)}`
671
+ };
672
+ }
673
+ return {
674
+ kind: "done",
675
+ commands: run.commands,
676
+ files
677
+ };
678
+ };
679
+ /** This function gives the first record whose code is not 0, or null. */
680
+ const firstFailure = (...records) => records.find((record) => record.code !== 0) ?? null;
681
+ /**
682
+ * This function installs a service of the user, and by default starts it. It does not throw.
683
+ * - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.
684
+ * - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.
685
+ * A second install replaces the first. Give it the ports of a test, thus no test installs a real task.
686
+ */
687
+ const installService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
688
+ const start = options.start ?? true;
689
+ const paths = servicePaths(spec, ports);
690
+ if (ports.platform === "win32") {
691
+ await ports.files.write(paths.unit, utf16le(renderTaskXml(spec, {
692
+ user: ports.user(),
693
+ conhost: conhostPath(ports)
694
+ })));
695
+ files.push(paths.unit);
696
+ const created = await run.run("schtasks", [
697
+ "/Create",
698
+ "/TN",
699
+ spec.name,
700
+ "/XML",
701
+ paths.unit,
702
+ "/F"
703
+ ]);
704
+ if (created.code !== 0 || !start) return firstFailure(created);
705
+ return firstFailure(await run.run("schtasks", [
706
+ "/Run",
707
+ "/TN",
708
+ spec.name
709
+ ]));
710
+ }
711
+ await ports.files.write(paths.unit, renderSystemdUnit(spec));
712
+ files.push(paths.unit);
713
+ const timer = renderSystemdTimer(spec);
714
+ if (paths.timer !== null && timer !== null) {
715
+ await ports.files.write(paths.timer, timer);
716
+ files.push(paths.timer);
717
+ }
718
+ const reloaded = await run.run("systemctl", ["--user", "daemon-reload"]);
719
+ if (reloaded.code !== 0) return reloaded;
720
+ return firstFailure(await run.run("systemctl", [
721
+ "--user",
722
+ "enable",
723
+ ...start ? ["--now"] : [],
724
+ enabledUnit(spec)
725
+ ]));
726
+ });
727
+ /** This function stops the instance of a discovery file, when it is alive and is the same process. */
728
+ const stopInstance = async (ports, options) => {
729
+ if (options.discovery === void 0) return;
730
+ const found = await readDiscovery(options.discovery, ports, { clean: true });
731
+ if (found.kind !== "running") return;
732
+ const stopped = await stopTree(found.record.pid, ports);
733
+ ports.logger?.log(stopped.kind === "failed" ? "warn" : "info", `the host stopped the instance ${found.record.pid}: ${stopped.kind}`, {
734
+ pid: found.record.pid,
735
+ outcome: stopped.kind
736
+ });
737
+ };
738
+ /**
739
+ * This function removes a service. It does not throw. On Windows, it ends the task and deletes it. On
740
+ * Linux, it disables and stops the unit, removes its files and reloads systemd. With a discovery file,
741
+ * it then stops the process tree of an instance that stays.
742
+ */
743
+ const uninstallService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
744
+ const paths = servicePaths(spec, ports);
745
+ let failure;
746
+ if (ports.platform === "win32") {
747
+ await run.run("schtasks", [
748
+ "/End",
749
+ "/TN",
750
+ spec.name
751
+ ]);
752
+ failure = firstFailure(await run.run("schtasks", [
753
+ "/Delete",
754
+ "/TN",
755
+ spec.name,
756
+ "/F"
757
+ ]));
758
+ await ports.files.remove(paths.unit);
759
+ } else {
760
+ failure = firstFailure(await run.run("systemctl", [
761
+ "--user",
762
+ "disable",
763
+ "--now",
764
+ enabledUnit(spec)
765
+ ]));
766
+ if (paths.timer !== null) await run.run("systemctl", [
767
+ "--user",
768
+ "stop",
769
+ `${spec.name}.service`
770
+ ]);
771
+ await ports.files.remove(paths.unit);
772
+ if (paths.timer !== null) await ports.files.remove(paths.timer);
773
+ await run.run("systemctl", ["--user", "daemon-reload"]);
774
+ }
775
+ files.push(paths.unit, ...paths.timer === null ? [] : [paths.timer]);
776
+ await stopInstance(ports, options);
777
+ return failure;
778
+ });
779
+ /** This function enables a service and starts it. It does not throw. On Windows, it enables the task and runs it. */
780
+ const startService = (spec, ports) => operate(spec, ports, async (run) => {
781
+ if (ports.platform === "win32") {
782
+ const enabled = await run.run("schtasks", [
783
+ "/Change",
784
+ "/TN",
785
+ spec.name,
786
+ "/ENABLE"
787
+ ]);
788
+ if (enabled.code !== 0) return enabled;
789
+ return firstFailure(await run.run("schtasks", [
790
+ "/Run",
791
+ "/TN",
792
+ spec.name
793
+ ]));
794
+ }
795
+ return firstFailure(await run.run("systemctl", [
796
+ "--user",
797
+ "start",
798
+ spec.start === "logon" ? `${spec.name}.service` : `${spec.name}.timer`
799
+ ]));
800
+ });
801
+ /**
802
+ * This function stops a service, and keeps it stopped until `startService`. It does not throw.
803
+ * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
804
+ * With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
805
+ * - On Linux, `systemctl --user stop` sends SIGTERM, thus `run()` stops in its stages.
806
+ */
807
+ const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
808
+ if (ports.platform === "win32") {
809
+ const disabled = await run.run("schtasks", [
810
+ "/Change",
811
+ "/TN",
812
+ spec.name,
813
+ "/DISABLE"
814
+ ]);
815
+ if (disabled.code !== 0) return disabled;
816
+ await run.run("schtasks", [
817
+ "/End",
818
+ "/TN",
819
+ spec.name
820
+ ]);
821
+ await stopInstance(ports, options);
822
+ return null;
823
+ }
824
+ return firstFailure(await run.run("systemctl", [
825
+ "--user",
826
+ "stop",
827
+ `${spec.name}.service`
828
+ ]));
829
+ });
830
+ /** This function gives the value of a line `Key: value` of the list of `schtasks /Query /FO LIST`. */
831
+ const listValue = (out, key) => {
832
+ for (const line of out.split(/\r?\n/)) {
833
+ const at = line.indexOf(":");
834
+ if (at > 0 && line.slice(0, at).trim() === key) return line.slice(at + 1).trim();
835
+ }
836
+ return null;
837
+ };
838
+ /**
839
+ * This function gives the status of a service. It does not throw. A service that the system does not
840
+ * have gives `installed: false`. A malformed or stale discovery file gives its read, and not a throw.
841
+ */
842
+ const serviceStatus = async (spec, ports, options = {}) => {
843
+ const run = runner(ports);
844
+ const instance = options.discovery === void 0 ? null : await readDiscovery(options.discovery, ports);
845
+ if (serviceProblems(spec).length > 0 || ports.platform !== "win32" && ports.platform !== "linux") return {
846
+ installed: false,
847
+ state: "unknown",
848
+ instance,
849
+ commands: run.commands
850
+ };
851
+ if (ports.platform === "win32") {
852
+ const query = await run.run("schtasks", [
853
+ "/Query",
854
+ "/TN",
855
+ spec.name,
856
+ "/V",
857
+ "/FO",
858
+ "LIST"
859
+ ]);
860
+ if (query.code !== 0) return {
861
+ installed: false,
862
+ state: "unknown",
863
+ instance,
864
+ commands: run.commands
865
+ };
866
+ return {
867
+ installed: true,
868
+ state: listValue(query.out, "Status") ?? "unknown",
869
+ instance,
870
+ commands: run.commands
871
+ };
872
+ }
873
+ let installed;
874
+ try {
875
+ installed = await ports.files.read(servicePaths(spec, ports).unit) !== null;
876
+ } catch {
877
+ installed = false;
878
+ }
879
+ const state = (await run.run("systemctl", [
880
+ "--user",
881
+ "is-active",
882
+ `${spec.name}.service`
883
+ ])).out.split(/\r?\n/)[0]?.trim() ?? "";
884
+ return {
885
+ installed,
886
+ state: state === "" ? "unknown" : state,
887
+ instance,
888
+ commands: run.commands
889
+ };
890
+ };
891
+ //#endregion
892
+ //#region src/host/probes.ts
893
+ /** This function gives the problems of a probe: each value that a probe cannot use. */
894
+ const probeProblems = (probe) => {
895
+ if (probe.kind === "http") {
896
+ const problems = [];
897
+ if (!/^https?:\/\//.test(probe.url)) problems.push(`the address ${JSON.stringify(probe.url)} is not an http or https address`);
898
+ if (probe.status !== void 0 && !(Number.isInteger(probe.status) && probe.status >= 100 && probe.status <= 599)) problems.push(`the status ${probe.status} is not an HTTP status`);
899
+ return problems;
900
+ }
901
+ if (probe.kind === "tcp") return Number.isInteger(probe.port) && probe.port >= 1 && probe.port <= 65535 ? [] : [`the port ${probe.port} is not a port from 1 to 65535`];
902
+ if (probe.kind === "command") return probe.program === "" ? ["the program of the command probe is empty"] : [];
903
+ return [`the probe kind ${JSON.stringify(probe.kind)} is not http, tcp or command`];
904
+ };
905
+ /** This function uses a probe one time, in a timeout of milliseconds. It does not throw. */
906
+ const probeOnce = async (probe, timeout, ports) => {
907
+ try {
908
+ if (probe.kind === "http") {
909
+ const want = probe.status ?? 200;
910
+ const status = await ports.net.httpStatus(probe.url, timeout);
911
+ if (status === want) return { ok: true };
912
+ return {
913
+ ok: false,
914
+ why: status === null ? `${probe.url} gave no answer in ${timeout} ms` : `${probe.url} gave ${status}, not ${want}`
915
+ };
916
+ }
917
+ if (probe.kind === "tcp") {
918
+ const host = probe.host ?? "127.0.0.1";
919
+ if (await ports.net.tcpConnect(host, probe.port, timeout)) return { ok: true };
920
+ return {
921
+ ok: false,
922
+ why: `no TCP connection to ${host}:${probe.port} in ${timeout} ms`
923
+ };
924
+ }
925
+ const result = await ports.commands.run(probe.program, probe.args, {
926
+ cwd: probe.cwd,
927
+ timeout
928
+ });
929
+ return result.code === 0 ? { ok: true } : {
930
+ ok: false,
931
+ why: `${probe.program} gave the code ${result.code}`
932
+ };
933
+ } catch (error) {
934
+ return {
935
+ ok: false,
936
+ why: `the probe failed: ${error instanceof Error ? error.message : String(error)}`
937
+ };
938
+ }
939
+ };
940
+ //#endregion
941
+ //#region src/host/env.ts
942
+ const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
943
+ /** This function reads a value in double quotes: `\n`, `\t`, `\"` and `\\` are escapes. */
944
+ const doubleQuoted = (body) => body.replace(/\\(.)/g, (_match, char) => char === "n" ? "\n" : char === "t" ? " " : char === "r" ? "\r" : char);
945
+ /**
946
+ * This function reads a file of environment variables, one `KEY=value` on each line. It is a pure
947
+ * function. It does not throw: it skips a bad line and gives its problem.
948
+ * - A blank line and a line that starts with `#` are skipped. A line can start with `export `.
949
+ * - A value in single quotes is literal. A value in double quotes has the escapes `\n`, `\t`, `\"` and `\\`.
950
+ * - A value without quotes ends at ` #`, and its spaces at the two ends go.
951
+ * - A key that comes again replaces its value.
952
+ */
953
+ const parseEnvFile = (text) => {
954
+ const env = {};
955
+ const problems = [];
956
+ (text.charCodeAt(0) === 65279 ? text.slice(1) : text).split(/\r?\n/).forEach((raw, at) => {
957
+ const line = raw.trim();
958
+ if (line === "" || line.startsWith("#")) return;
959
+ const body = line.startsWith("export ") ? line.slice(7).trimStart() : line;
960
+ const equals = body.indexOf("=");
961
+ if (equals <= 0) {
962
+ problems.push(`line ${at + 1} has no KEY=value`);
963
+ return;
964
+ }
965
+ const key = body.slice(0, equals).trim();
966
+ if (!KEY.test(key)) {
967
+ problems.push(`line ${at + 1}: ${JSON.stringify(key)} is not a name of a variable`);
968
+ return;
969
+ }
970
+ const rest = body.slice(equals + 1).trim();
971
+ const quote = rest[0];
972
+ if (quote === "\"" || quote === "'") {
973
+ const end = quote === "'" ? rest.indexOf("'", 1) : closingQuote(rest);
974
+ if (end < 0) {
975
+ problems.push(`line ${at + 1}: the value of ${key} has no closing quote`);
976
+ return;
977
+ }
978
+ env[key] = quote === "'" ? rest.slice(1, end) : doubleQuoted(rest.slice(1, end));
979
+ return;
980
+ }
981
+ const comment = rest.search(/\s#/);
982
+ env[key] = (comment < 0 ? rest : rest.slice(0, comment)).trim();
983
+ });
984
+ return {
985
+ env,
986
+ problems
987
+ };
988
+ };
989
+ /** This function gives the place of the double quote that closes a value, or -1. A quote after a backslash does not close it. */
990
+ const closingQuote = (text) => {
991
+ for (let at = 1; at < text.length; at += 1) if (text[at] === "\\") at += 1;
992
+ else if (text[at] === "\"") return at;
993
+ return -1;
994
+ };
995
+ //#endregion
996
+ //#region src/host/logs.ts
997
+ const byteLength = (chunk) => typeof chunk === "string" ? new TextEncoder().encode(chunk).length : chunk.length;
998
+ /**
999
+ * This function makes a rotating log on a file port. Before a write that makes the file larger than
1000
+ * `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the
1001
+ * file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.
1002
+ */
1003
+ const rotatingLog = (spec, files) => {
1004
+ const max = valueIn(spec.maxSize, "B");
1005
+ let chain = Promise.resolve();
1006
+ let size = null;
1007
+ let failures = 0;
1008
+ const rotate = async () => {
1009
+ if (spec.keep <= 0) {
1010
+ await files.remove(spec.path);
1011
+ return;
1012
+ }
1013
+ await files.remove(`${spec.path}.${spec.keep}`);
1014
+ for (let at = spec.keep - 1; at >= 1; at -= 1) if (await files.size(`${spec.path}.${at}`) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);
1015
+ await files.rename(spec.path, `${spec.path}.1`);
1016
+ };
1017
+ const append = async (chunk) => {
1018
+ const length = byteLength(chunk);
1019
+ size ??= await files.size(spec.path) ?? 0;
1020
+ if (size > 0 && size + length > max) {
1021
+ await rotate();
1022
+ size = 0;
1023
+ }
1024
+ await files.append(spec.path, chunk);
1025
+ size += length;
1026
+ };
1027
+ return {
1028
+ write(chunk) {
1029
+ chain = chain.then(() => append(chunk)).catch(() => {
1030
+ failures += 1;
1031
+ size = null;
1032
+ });
1033
+ },
1034
+ flush: () => chain,
1035
+ get failures() {
1036
+ return failures;
1037
+ }
1038
+ };
1039
+ };
1040
+ //#endregion
1041
+ //#region src/host/group.ts
1042
+ /**
1043
+ * This restart is the default. The first wait is 1 s, and each wait after it is two times longer, to 1 min.
1044
+ * The jitter subtracts up to half of each wait. The count of tries goes back to 0 after 1 min ready.
1045
+ */
1046
+ const DEFAULT_RESTART = {
1047
+ backoff: {
1048
+ base: 1e3,
1049
+ factor: 2,
1050
+ cap: 6e4,
1051
+ jitter: {
1052
+ kind: "subtract",
1053
+ fraction: .5
1054
+ }
1055
+ },
1056
+ resetAfter: {
1057
+ value: 60,
1058
+ unit: "s"
1059
+ }
1060
+ };
1061
+ const DEFAULT_GRACE = {
1062
+ value: 10,
1063
+ unit: "s"
1064
+ };
1065
+ const DEFAULT_LOG_SIZE = {
1066
+ value: 10,
1067
+ unit: "MB"
1068
+ };
1069
+ const DEFAULT_LOG_KEEP = 3;
1070
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1071
+ const ms = (time) => valueIn(time, "ms");
1072
+ /**
1073
+ * This function gives the start sequence of a group, as layers of names. Each program of a layer needs only programs of the
1074
+ * layers before it. A program in a cycle, or after an unknown program, is in no layer. `groupProblems` names it.
1075
+ */
1076
+ const startOrder = (spec) => {
1077
+ const names = new Set(spec.programs.map((program) => program.name));
1078
+ const placed = /* @__PURE__ */ new Set();
1079
+ const layers = [];
1080
+ for (;;) {
1081
+ const layer = spec.programs.filter((program) => !placed.has(program.name)).filter((program) => (program.after ?? []).every((name) => names.has(name) && placed.has(name))).map((program) => program.name);
1082
+ if (layer.length === 0) return layers;
1083
+ for (const name of layer) placed.add(name);
1084
+ layers.push([...new Set(layer)]);
1085
+ }
1086
+ };
1087
+ const isTimeAtLeast = (value, floor, strict) => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);
1088
+ /** This function gives the problems of a group spec: each value that the supervisor cannot use. */
1089
+ const groupProblems = (spec) => {
1090
+ const problems = [];
1091
+ if (!NAME.test(spec.name)) problems.push(`the group name ${JSON.stringify(spec.name)} is not letters, digits, ".", "_" and "-"`);
1092
+ if (spec.stateDir === "") problems.push("the stateDir is empty");
1093
+ if (spec.programs.length === 0) problems.push("the group has no programs");
1094
+ const seen = /* @__PURE__ */ new Set();
1095
+ const names = new Set(spec.programs.map((program) => program.name));
1096
+ for (const program of spec.programs) {
1097
+ const name = program.name;
1098
+ const of = `the program ${JSON.stringify(name)}`;
1099
+ if (!NAME.test(name)) problems.push(`${of}: the name is not letters, digits, ".", "_" and "-"`);
1100
+ if (seen.has(name)) problems.push(`${of} comes two times`);
1101
+ seen.add(name);
1102
+ if (program.program === "") problems.push(`${of}: the program is empty`);
1103
+ for (const need of program.after ?? []) if (need === name) problems.push(`${of} is after itself`);
1104
+ else if (!names.has(need)) problems.push(`${of} is after ${JSON.stringify(need)}, which is not in the group`);
1105
+ if (program.ready !== void 0) {
1106
+ problems.push(...probeProblems(program.ready.probe).map((problem) => `${of}: ${problem}`));
1107
+ for (const field of [
1108
+ "interval",
1109
+ "timeout",
1110
+ "within"
1111
+ ]) if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);
1112
+ }
1113
+ if (program.restart !== void 0 && program.restart !== null) {
1114
+ problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));
1115
+ if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);
1116
+ }
1117
+ if (program.log !== void 0 && program.log !== null) {
1118
+ const size = program.log.maxSize;
1119
+ if (!(isQuantity(size) && convertible(size.unit, "B") && valueIn(size, "B") > 0)) problems.push(`${of}: the maxSize of the log is not a size above zero`);
1120
+ if (!(Number.isInteger(program.log.keep) && program.log.keep >= 0)) problems.push(`${of}: the keep of the log is not a whole number of zero or more`);
1121
+ if (program.log.path === "") problems.push(`${of}: the path of the log is empty`);
1122
+ }
1123
+ if (program.stop !== void 0) {
1124
+ if (!isTimeAtLeast(program.stop.grace, 0, false)) problems.push(`${of}: the grace of the stop is not a time of zero or more`);
1125
+ if (program.stop.message !== void 0 && !isMessageShape(program.stop.message)) problems.push(`${of}: the stop message is not a value of JSON`);
1126
+ const signal = program.stop.signal;
1127
+ if (signal !== void 0 && signal !== "SIGINT" && signal !== "SIGTERM") problems.push(`${of}: the stop signal ${JSON.stringify(signal)} is not SIGINT or SIGTERM`);
1128
+ }
1129
+ const port = program.listen?.port;
1130
+ if (port !== void 0 && port !== null && !(Number.isInteger(port) && port >= 1 && port <= 65535)) problems.push(`${of}: the port ${port} is not a port from 1 to 65535`);
1131
+ }
1132
+ const placed = new Set(startOrder(spec).flat());
1133
+ const left = spec.programs.filter((program) => !placed.has(program.name) && (program.after ?? []).every((need) => names.has(need) && need !== program.name));
1134
+ if (left.length > 0) problems.push(`the programs ${left.map((program) => JSON.stringify(program.name)).join(", ")} are in a cycle of "after", or after a program in one`);
1135
+ return problems;
1136
+ };
1137
+ /**
1138
+ * This function makes the supervisor of a group. It refuses a spec with problems. Each effect goes
1139
+ * through the ports, thus a test gives `fakeHost()` and starts no process.
1140
+ * - A program starts when each program of its `after` is ready. It takes its lock first, thus a second instance does not start.
1141
+ * - A program with a probe is ready when its probe passes. A program that is not ready in `within` stops, and starts again.
1142
+ * - A program that stops starts again after the backoff of its `retrier`, when its programs are ready.
1143
+ * - Its output goes to its rotating log. Its environment is the host, then its env file, then its `env`.
1144
+ * - The stop goes in the reverse sequence: the staged stop first, and after the grace, the stop of the process tree by its ID.
1145
+ */
1146
+ const superviseGroup = (spec, ports, options = {}) => {
1147
+ const problems = groupProblems(spec);
1148
+ if (problems.length > 0) throw new Error(`the group ${spec.name} has problems: ${problems.join("; ")}`);
1149
+ const abort = new AbortController();
1150
+ const layers = startOrder(spec);
1151
+ let started = false;
1152
+ let stopping = false;
1153
+ let stopped = null;
1154
+ const say = (level, message, fields) => {
1155
+ try {
1156
+ ports.logger?.log(level, message, {
1157
+ group: spec.name,
1158
+ ...fields
1159
+ });
1160
+ } catch {}
1161
+ };
1162
+ const units = /* @__PURE__ */ new Map();
1163
+ for (const program of spec.programs) {
1164
+ const restart = program.restart === void 0 ? DEFAULT_RESTART : program.restart;
1165
+ const logSpec = program.log === void 0 ? {
1166
+ path: joinPath(ports.platform, spec.stateDir, "logs", `${program.name}.log`),
1167
+ maxSize: DEFAULT_LOG_SIZE,
1168
+ keep: DEFAULT_LOG_KEEP
1169
+ } : program.log;
1170
+ units.set(program.name, {
1171
+ spec: program,
1172
+ lockPath: joinPath(ports.platform, spec.stateDir, `${program.name}.lock`),
1173
+ discoveryPath: joinPath(ports.platform, spec.stateDir, `${program.name}.json`),
1174
+ log: logSpec === null ? null : rotatingLog(logSpec, ports.files),
1175
+ retry: restart === null ? null : retrier({
1176
+ ...restart.backoff,
1177
+ clock: ports.clock,
1178
+ signal: abort.signal,
1179
+ ...options.random === void 0 ? {} : { random: options.random }
1180
+ }),
1181
+ phase: "waiting",
1182
+ child: null,
1183
+ lock: null,
1184
+ timers: [],
1185
+ restarts: 0,
1186
+ detail: null,
1187
+ reason: null,
1188
+ waiters: []
1189
+ });
1190
+ }
1191
+ const unitOf = (name) => units.get(name);
1192
+ const clearTimers = (unit) => {
1193
+ for (const cancel of unit.timers.splice(0)) cancel();
1194
+ };
1195
+ const environment = async (unit) => {
1196
+ const env = {};
1197
+ for (const [key, value] of Object.entries(ports.env)) if (value !== void 0) env[key] = value;
1198
+ const file = unit.spec.envFile;
1199
+ if (file !== void 0) try {
1200
+ const text = await ports.files.read(file);
1201
+ if (text === null) say("warn", `the env file ${file} of ${unit.spec.name} does not exist`, {
1202
+ program: unit.spec.name,
1203
+ file
1204
+ });
1205
+ else {
1206
+ const parsed = parseEnvFile(text);
1207
+ Object.assign(env, parsed.env);
1208
+ for (const problem of parsed.problems) say("warn", `the env file ${file} of ${unit.spec.name}: ${problem}`, {
1209
+ program: unit.spec.name,
1210
+ file
1211
+ });
1212
+ }
1213
+ } catch (error) {
1214
+ say("warn", `the read of the env file ${file} of ${unit.spec.name} failed`, {
1215
+ program: unit.spec.name,
1216
+ file,
1217
+ error
1218
+ });
1219
+ }
1220
+ return Object.assign(env, unit.spec.env ?? {});
1221
+ };
1222
+ const consider = (unit) => {
1223
+ if (!started || stopping || unit.phase !== "waiting") return;
1224
+ if (!(unit.spec.after ?? []).every((name) => unitOf(name).phase === "ready")) return;
1225
+ launch(unit);
1226
+ };
1227
+ const considerAll = () => {
1228
+ for (const layer of layers) for (const name of layer) consider(unitOf(name));
1229
+ };
1230
+ /** This function starts the program again after the backoff, or ends it when it has no restart. */
1231
+ const later = (unit, phase) => {
1232
+ const delay = unit.retry?.schedule(() => {
1233
+ if (stopping) return;
1234
+ unit.phase = "waiting";
1235
+ unit.restarts += 1;
1236
+ consider(unit);
1237
+ });
1238
+ if (delay === void 0 || delay === null) {
1239
+ unit.phase = phase === "held" ? "held" : "exited";
1240
+ unit.lock?.release();
1241
+ unit.lock = null;
1242
+ return;
1243
+ }
1244
+ unit.phase = phase;
1245
+ say("info", `${unit.spec.name} starts again in ${delay} ms`, {
1246
+ program: unit.spec.name,
1247
+ delay: {
1248
+ value: delay,
1249
+ unit: "ms"
1250
+ },
1251
+ attempt: unit.retry?.attempts
1252
+ });
1253
+ };
1254
+ const markReady = (unit, child) => {
1255
+ if (unit.child !== child || stopping) return;
1256
+ unit.phase = "ready";
1257
+ unit.detail = null;
1258
+ say("info", `${unit.spec.name} is ready`, {
1259
+ program: unit.spec.name,
1260
+ pid: child.pid
1261
+ });
1262
+ const restart = unit.spec.restart === void 0 ? DEFAULT_RESTART : unit.spec.restart;
1263
+ if (unit.retry !== null && restart !== null) unit.timers.push(ports.clock.after(ms(restart.resetAfter), () => {
1264
+ if (unit.child === child && unit.phase === "ready") unit.retry?.reset();
1265
+ }));
1266
+ considerAll();
1267
+ };
1268
+ const probe = (unit, child, ready) => {
1269
+ const deadline = ports.clock.now() + ms(ready.within);
1270
+ const attempt = async () => {
1271
+ if (unit.child !== child || stopping) return;
1272
+ const result = await probeOnce(ready.probe, ms(ready.timeout), ports);
1273
+ if (unit.child !== child || stopping) return;
1274
+ if (result.ok) {
1275
+ markReady(unit, child);
1276
+ return;
1277
+ }
1278
+ unit.detail = result.why;
1279
+ if (ports.clock.now() >= deadline) {
1280
+ unit.reason = `it was not ready in ${ms(ready.within)} ms (${result.why})`;
1281
+ unit.detail = unit.reason;
1282
+ say("warn", `${unit.spec.name} is not ready in its time, thus it stops`, {
1283
+ program: unit.spec.name,
1284
+ pid: child.pid,
1285
+ why: result.why
1286
+ });
1287
+ stagedStop(unit, child);
1288
+ return;
1289
+ }
1290
+ unit.timers.push(ports.clock.after(ms(ready.interval), () => void attempt()));
1291
+ };
1292
+ attempt();
1293
+ };
1294
+ const exited = (unit, child, code, signal) => {
1295
+ if (unit.child !== child) return;
1296
+ clearTimers(unit);
1297
+ unit.child = null;
1298
+ for (const waiter of unit.waiters.splice(0)) waiter();
1299
+ if (child.pid !== null) removeDiscovery(unit.discoveryPath, ports, child.pid);
1300
+ unit.lock?.update(null).catch(() => {});
1301
+ if (stopping || unit.phase === "stopping") {
1302
+ unit.phase = "stopped";
1303
+ return;
1304
+ }
1305
+ const end = child.pid === null ? `${unit.spec.program} did not start` : `it exited with ${code === null ? `the signal ${signal ?? "unknown"}` : `the code ${code}`}`;
1306
+ unit.detail = unit.reason === null ? end : `${unit.reason}, then ${end}`;
1307
+ unit.reason = null;
1308
+ say("warn", `${unit.spec.name} stopped: ${unit.detail}`, {
1309
+ program: unit.spec.name,
1310
+ pid: child.pid,
1311
+ code,
1312
+ signal
1313
+ });
1314
+ later(unit, "backoff");
1315
+ };
1316
+ const launch = async (unit) => {
1317
+ unit.phase = "starting";
1318
+ unit.detail = null;
1319
+ const name = unit.spec.name;
1320
+ if (unit.lock === null) {
1321
+ const taken = await acquireInstanceLock(unit.lockPath, ports);
1322
+ if (stopping) {
1323
+ if (taken.kind === "acquired") await taken.lock.release();
1324
+ return;
1325
+ }
1326
+ if (taken.kind !== "acquired") {
1327
+ unit.detail = taken.kind === "held" ? `the process ${taken.owner.child?.pid ?? taken.owner.pid} holds the lock ${unit.lockPath}` : taken.problem;
1328
+ say("warn", `${name} does not start: ${unit.detail}`, {
1329
+ program: name,
1330
+ lock: unit.lockPath
1331
+ });
1332
+ later(unit, "held");
1333
+ return;
1334
+ }
1335
+ unit.lock = taken.lock;
1336
+ }
1337
+ const lock = unit.lock;
1338
+ const env = await environment(unit);
1339
+ if (stopping) {
1340
+ await lock.release();
1341
+ unit.lock = null;
1342
+ return;
1343
+ }
1344
+ const child = ports.processes.spawn({
1345
+ program: unit.spec.program,
1346
+ args: unit.spec.args ?? [],
1347
+ cwd: unit.spec.cwd,
1348
+ env,
1349
+ ipc: unit.spec.ipc ?? false
1350
+ });
1351
+ const startedAt = ports.wall();
1352
+ unit.child = child;
1353
+ child.onOutput((_stream, chunk) => unit.log?.write(chunk));
1354
+ child.onExit((code, signal) => exited(unit, child, code, signal));
1355
+ const pid = child.pid;
1356
+ if (pid === null) return;
1357
+ say("info", `${name} started`, {
1358
+ program: name,
1359
+ pid
1360
+ });
1361
+ const mark = {
1362
+ pid,
1363
+ startedAt
1364
+ };
1365
+ try {
1366
+ await lock.update(mark);
1367
+ await writeDiscovery(unit.discoveryPath, {
1368
+ pid,
1369
+ startedAt: new Date(startedAt).toISOString(),
1370
+ port: unit.spec.listen?.port ?? null,
1371
+ url: unit.spec.listen?.url ?? null,
1372
+ extra: {
1373
+ group: spec.name,
1374
+ program: name
1375
+ }
1376
+ }, ports);
1377
+ } catch (error) {
1378
+ say("warn", `the files of ${name} were not written`, {
1379
+ program: name,
1380
+ error
1381
+ });
1382
+ }
1383
+ if (unit.child !== child) await removeDiscovery(unit.discoveryPath, ports, pid);
1384
+ if (unit.child !== child || stopping) return;
1385
+ if (unit.spec.ready === void 0) markReady(unit, child);
1386
+ else probe(unit, child, unit.spec.ready);
1387
+ };
1388
+ /** This function waits for the end of a child, for at most `wait` milliseconds. It tells if the child ended. */
1389
+ const ended = (unit, child, wait) => new Promise((resolve) => {
1390
+ if (unit.child !== child) {
1391
+ resolve(true);
1392
+ return;
1393
+ }
1394
+ const cancel = ports.clock.after(wait, () => resolve(unit.child !== child));
1395
+ unit.waiters.push(() => {
1396
+ cancel();
1397
+ resolve(true);
1398
+ });
1399
+ });
1400
+ /**
1401
+ * This function stops a child in stages. The message goes on its IPC channel when it has one. Else
1402
+ * Linux gets SIGTERM, and Windows gets `taskkill /T` without `/F`. After the grace, the process tree stops by its ID.
1403
+ */
1404
+ const stagedStop = async (unit, child) => {
1405
+ const pid = child.pid;
1406
+ if (pid === null || unit.child !== child) return;
1407
+ const grace = ms(unit.spec.stop?.grace ?? DEFAULT_GRACE);
1408
+ const gone = ended(unit, child, grace);
1409
+ let asked = null;
1410
+ if (child.ipc && child.send(unit.spec.stop?.message ?? "shutdown")) asked = "the IPC message";
1411
+ else if (ports.platform === "win32") {
1412
+ if ((await ports.commands.run("taskkill", [
1413
+ "/T",
1414
+ "/PID",
1415
+ String(pid)
1416
+ ]).catch(() => null))?.code === 0) asked = "taskkill";
1417
+ } else {
1418
+ const signal = unit.spec.stop?.signal ?? "SIGTERM";
1419
+ if (ports.processes.signal(pid, signal)) asked = signal;
1420
+ }
1421
+ say("info", `${unit.spec.name} stops${asked === null ? "" : ` through ${asked}`}`, {
1422
+ program: unit.spec.name,
1423
+ pid,
1424
+ grace: {
1425
+ value: grace,
1426
+ unit: "ms"
1427
+ }
1428
+ });
1429
+ if (asked !== null && await gone) return;
1430
+ const tree = await stopTree(pid, ports);
1431
+ const why = asked === null ? "the staged stop did not go" : "it did not stop in its grace";
1432
+ say(tree.kind === "failed" ? "error" : "warn", `${unit.spec.name}: ${why}, thus its process tree stops: ${tree.kind}`, {
1433
+ program: unit.spec.name,
1434
+ pid,
1435
+ outcome: tree.kind
1436
+ });
1437
+ if (!await ended(unit, child, grace)) say("error", `${unit.spec.name} did not end after the stop of its process tree`, {
1438
+ program: unit.spec.name,
1439
+ pid
1440
+ });
1441
+ };
1442
+ const stopUnit = async (unit) => {
1443
+ clearTimers(unit);
1444
+ const child = unit.child;
1445
+ const pid = child?.pid ?? null;
1446
+ if (child !== null && pid !== null) {
1447
+ unit.phase = "stopping";
1448
+ await stagedStop(unit, child);
1449
+ await removeDiscovery(unit.discoveryPath, ports, pid);
1450
+ }
1451
+ unit.phase = "stopped";
1452
+ await unit.lock?.release();
1453
+ unit.lock = null;
1454
+ };
1455
+ return {
1456
+ start() {
1457
+ if (started || stopping) return;
1458
+ started = true;
1459
+ say("info", `the group ${spec.name} starts`, { layers });
1460
+ considerAll();
1461
+ },
1462
+ stop() {
1463
+ if (stopped !== null) return stopped;
1464
+ stopping = true;
1465
+ abort.abort();
1466
+ stopped = (async () => {
1467
+ for (const layer of [...layers].reverse()) await Promise.all(layer.map((name) => stopUnit(unitOf(name))));
1468
+ await Promise.all([...units.values()].map((unit) => unit.log?.flush()));
1469
+ say("info", `the group ${spec.name} stopped`, {});
1470
+ })();
1471
+ return stopped;
1472
+ },
1473
+ states() {
1474
+ return spec.programs.map((program) => {
1475
+ const unit = unitOf(program.name);
1476
+ return {
1477
+ name: program.name,
1478
+ phase: unit.phase,
1479
+ pid: unit.child?.pid ?? null,
1480
+ restarts: unit.restarts,
1481
+ detail: unit.detail
1482
+ };
1483
+ });
1484
+ }
1485
+ };
1486
+ };
1487
+ //#endregion
1488
+ //#region src/host/node.ts
1489
+ const codeOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
1490
+ const missing = (error) => codeOf(error) === "ENOENT";
1491
+ const nodeCommands = { run: (file, args, options = {}) => new Promise((resolve) => {
1492
+ execFile(file, [...args], {
1493
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd },
1494
+ timeout: options.timeout ?? 0,
1495
+ windowsHide: true,
1496
+ encoding: "utf8",
1497
+ maxBuffer: 16777216
1498
+ }, (error, stdout, stderr) => {
1499
+ const out = `${stdout}${stderr}`;
1500
+ if (error === null) {
1501
+ resolve({
1502
+ code: 0,
1503
+ out
1504
+ });
1505
+ return;
1506
+ }
1507
+ if (missing(error)) resolve({
1508
+ code: 127,
1509
+ out: error.message
1510
+ });
1511
+ else if (error.killed === true && options.timeout !== void 0) resolve({
1512
+ code: 124,
1513
+ out
1514
+ });
1515
+ else resolve({
1516
+ code: typeof error.code === "number" ? error.code : 1,
1517
+ out: out === "" ? error.message : out
1518
+ });
1519
+ });
1520
+ }) };
1521
+ let serial = 0;
1522
+ const nodeFiles = {
1523
+ async read(path) {
1524
+ try {
1525
+ return await readFile(path, "utf8");
1526
+ } catch (error) {
1527
+ if (missing(error)) return null;
1528
+ throw error;
1529
+ }
1530
+ },
1531
+ async write(path, data) {
1532
+ await mkdir(dirname(path), { recursive: true });
1533
+ serial += 1;
1534
+ const temporary = `${path}.${process.pid}.${serial}.tmp`;
1535
+ await writeFile(temporary, data);
1536
+ try {
1537
+ await rename(temporary, path);
1538
+ } catch (error) {
1539
+ await rm(temporary, { force: true });
1540
+ throw error;
1541
+ }
1542
+ },
1543
+ async create(path, data) {
1544
+ await mkdir(dirname(path), { recursive: true });
1545
+ try {
1546
+ await writeFile(path, data, { flag: "wx" });
1547
+ return true;
1548
+ } catch (error) {
1549
+ if (codeOf(error) === "EEXIST") return false;
1550
+ throw error;
1551
+ }
1552
+ },
1553
+ async append(path, data) {
1554
+ await mkdir(dirname(path), { recursive: true });
1555
+ await appendFile(path, data);
1556
+ },
1557
+ async size(path) {
1558
+ try {
1559
+ return (await stat(path)).size;
1560
+ } catch (error) {
1561
+ if (missing(error)) return null;
1562
+ throw error;
1563
+ }
1564
+ },
1565
+ rename: (from, to) => rename(from, to),
1566
+ remove: (path) => rm(path, { force: true })
1567
+ };
1568
+ /** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */
1569
+ const FILETIME_EPOCH_MS = 11644473600000n;
1570
+ /** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */
1571
+ const windowsStart = async (pid) => {
1572
+ const result = await nodeCommands.run("powershell.exe", [
1573
+ "-NoProfile",
1574
+ "-NonInteractive",
1575
+ "-Command",
1576
+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`
1577
+ ], { timeout: 1e4 });
1578
+ const text = result.out.trim();
1579
+ if (result.code !== 0 || !/^\d+$/.test(text)) return null;
1580
+ return Number(BigInt(text) / 10000n - FILETIME_EPOCH_MS);
1581
+ };
1582
+ /** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */
1583
+ const LINUX_TICKS = 100;
1584
+ /** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */
1585
+ const linuxStart = async (pid) => {
1586
+ const record = await readFile(`/proc/${pid}/stat`, "utf8");
1587
+ const fields = record.slice(record.lastIndexOf(")") + 2).split(" ");
1588
+ const ticks = Number(fields[19]);
1589
+ const boot = /^btime (\d+)$/m.exec(await readFile("/proc/stat", "utf8"));
1590
+ if (!Number.isFinite(ticks) || boot === null) return null;
1591
+ return Number(boot[1]) * 1e3 + ticks * 1e3 / LINUX_TICKS;
1592
+ };
1593
+ const sendSignal = (pid, signal) => {
1594
+ try {
1595
+ return process.kill(pid, signal);
1596
+ } catch {
1597
+ return false;
1598
+ }
1599
+ };
1600
+ const nodeSpawn = (request) => {
1601
+ const outputs = [];
1602
+ const exits = [];
1603
+ let end = null;
1604
+ const finish = (code, signal) => {
1605
+ if (end !== null) return;
1606
+ end = {
1607
+ code,
1608
+ signal
1609
+ };
1610
+ for (const handler of exits) handler(code, signal);
1611
+ };
1612
+ const child = spawn(request.program, [...request.args], {
1613
+ ...request.cwd === void 0 ? {} : { cwd: request.cwd },
1614
+ env: { ...request.env },
1615
+ stdio: request.ipc ? [
1616
+ "ignore",
1617
+ "pipe",
1618
+ "pipe",
1619
+ "ipc"
1620
+ ] : [
1621
+ "ignore",
1622
+ "pipe",
1623
+ "pipe"
1624
+ ],
1625
+ detached: process.platform !== "win32",
1626
+ windowsHide: true
1627
+ });
1628
+ child.stdout?.on("data", (chunk) => {
1629
+ for (const handler of outputs) handler("stdout", chunk);
1630
+ });
1631
+ child.stderr?.on("data", (chunk) => {
1632
+ for (const handler of outputs) handler("stderr", chunk);
1633
+ });
1634
+ child.on("error", () => {
1635
+ if (child.pid === void 0) finish(null, null);
1636
+ });
1637
+ child.on("exit", (code, signal) => finish(code, signal));
1638
+ return {
1639
+ pid: child.pid ?? null,
1640
+ ipc: request.ipc,
1641
+ onOutput(handler) {
1642
+ outputs.push(handler);
1643
+ },
1644
+ onExit(handler) {
1645
+ exits.push(handler);
1646
+ if (end !== null) handler(end.code, end.signal);
1647
+ },
1648
+ send(message) {
1649
+ if (!child.connected) return false;
1650
+ try {
1651
+ return child.send(message);
1652
+ } catch {
1653
+ return false;
1654
+ }
1655
+ }
1656
+ };
1657
+ };
1658
+ const nodeProcesses = {
1659
+ alive(pid) {
1660
+ try {
1661
+ process.kill(pid, 0);
1662
+ return true;
1663
+ } catch (error) {
1664
+ return codeOf(error) === "EPERM";
1665
+ }
1666
+ },
1667
+ async startOf(pid) {
1668
+ try {
1669
+ if (process.platform === "win32") return await windowsStart(pid);
1670
+ if (process.platform === "linux") return await linuxStart(pid);
1671
+ return null;
1672
+ } catch {
1673
+ return null;
1674
+ }
1675
+ },
1676
+ signal: (pid, signal) => sendSignal(pid, signal),
1677
+ signalGroup: (pid, signal) => process.platform !== "win32" && sendSignal(-pid, signal),
1678
+ spawn: nodeSpawn
1679
+ };
1680
+ const nodeNet = {
1681
+ async httpStatus(url, timeout) {
1682
+ try {
1683
+ const response = await fetch(url, {
1684
+ signal: AbortSignal.timeout(timeout),
1685
+ redirect: "manual"
1686
+ });
1687
+ await response.body?.cancel();
1688
+ return response.status;
1689
+ } catch {
1690
+ return null;
1691
+ }
1692
+ },
1693
+ tcpConnect: (host, port, timeout) => new Promise((resolve) => {
1694
+ const socket = connect({
1695
+ host,
1696
+ port
1697
+ });
1698
+ const done = (open) => {
1699
+ socket.destroy();
1700
+ resolve(open);
1701
+ };
1702
+ socket.setTimeout(timeout, () => done(false));
1703
+ socket.once("connect", () => done(true));
1704
+ socket.once("error", () => done(false));
1705
+ })
1706
+ };
1707
+ /**
1708
+ * This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.
1709
+ * Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.
1710
+ */
1711
+ const nodeHostPorts = (options = {}) => {
1712
+ const user = () => {
1713
+ const name = userInfo().username;
1714
+ const domain = process.env["USERDOMAIN"];
1715
+ return process.platform === "win32" && domain !== void 0 && domain !== "" ? `${domain}\\${name}` : name;
1716
+ };
1717
+ return {
1718
+ platform: process.platform,
1719
+ commands: nodeCommands,
1720
+ files: nodeFiles,
1721
+ processes: nodeProcesses,
1722
+ net: nodeNet,
1723
+ clock: options.clock ?? realClock,
1724
+ wall: () => Date.now(),
1725
+ self: {
1726
+ pid: process.pid,
1727
+ startedAt: Math.round(Date.now() - process.uptime() * 1e3)
1728
+ },
1729
+ env: process.env,
1730
+ homeDir: homedir(),
1731
+ user,
1732
+ ...options.logger === void 0 ? {} : { logger: options.logger }
1733
+ };
1734
+ };
1735
+ //#endregion
1736
+ export { DEFAULT_RESTART, START_MARGIN_MS, acquireInstanceLock, discoveryOf, groupProblems, inspectInstanceLock, installService, joinPath, lockText, nodeHostPorts, parseDiscovery, parseEnvFile, parseLockOwner, probeOnce, probeProblems, readDiscovery, removeDiscovery, renderSystemdTimer, renderSystemdUnit, renderTaskXml, rotatingLog, sameProcess, servicePaths, serviceProblems, serviceStatus, startOrder, startService, stopService, stopTree, superviseGroup, systemdArg, uninstallService, utf16le, windowsArg, writeDiscovery };
1737
+
1738
+ //# sourceMappingURL=host.js.map