@mark1russell7/service 0.8.9 → 0.8.11
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/README.md +52 -7
- package/build/host.d.ts +145 -11
- package/build/host.js +400 -28
- package/build/host.js.map +1 -1
- package/build/index.js +1 -267
- package/build/index.js.map +1 -1
- package/build/{ports-DZoipkSD.d.ts → ports-B1ayTL-j.d.ts} +13 -1
- package/build/process-7R9M29wN.js +437 -0
- package/build/process-7R9M29wN.js.map +1 -0
- package/build/testing.d.ts +3 -1
- package/build/testing.js +11 -0
- package/build/testing.js.map +1 -1
- package/package.json +5 -5
- package/build/process-Oe0Abbsm.js +0 -170
- package/build/process-Oe0Abbsm.js.map +0 -1
package/build/host.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { d as poller, f as latch, s as isMessageShape } from "./process-7R9M29wN.js";
|
|
1
2
|
import { backoffProblems } from "./backoff.js";
|
|
2
|
-
import { s as isMessageShape } from "./process-Oe0Abbsm.js";
|
|
3
3
|
import { t as retrier } from "./retrier-BObZq10-.js";
|
|
4
4
|
import { realClock } from "./clock.js";
|
|
5
|
-
import { convertible, isQuantity, valueIn } from "@mark1russell7/quantity";
|
|
5
|
+
import { convertible, formatDuration, isQuantity, valueIn } from "@mark1russell7/quantity";
|
|
6
6
|
import { connect } from "node:net";
|
|
7
7
|
import { escapeAttribute } from "@mark1russell7/text";
|
|
8
8
|
import { execFile, spawn } from "node:child_process";
|
|
@@ -42,6 +42,10 @@ const dailyTime = (text) => {
|
|
|
42
42
|
minute: found[2]
|
|
43
43
|
};
|
|
44
44
|
};
|
|
45
|
+
/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */
|
|
46
|
+
const runsUntilStop = (start) => start === "logon" || start === "boot";
|
|
47
|
+
/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */
|
|
48
|
+
const inBackground = (spec) => spec.background ?? spec.start === "boot";
|
|
45
49
|
/** This function tells if a value is a time: a quantity in a unit of time. */
|
|
46
50
|
const isTime = (value) => isQuantity(value) && convertible(value.unit, "ms");
|
|
47
51
|
/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */
|
|
@@ -58,8 +62,11 @@ const serviceProblems = (spec) => {
|
|
|
58
62
|
for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);
|
|
59
63
|
if (spec.program === "") problems.push("the program is empty");
|
|
60
64
|
if (spec.stateDir === "") problems.push("the stateDir is empty");
|
|
61
|
-
if (spec.start
|
|
62
|
-
if (spec.start
|
|
65
|
+
if (!runsUntilStop(spec.start) && dailyTime(spec.start.daily) === null) problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);
|
|
66
|
+
if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push("a daily job has no restart: give null");
|
|
67
|
+
if (spec.background !== void 0 && typeof spec.background !== "boolean") problems.push("the background is not true or false");
|
|
68
|
+
if (spec.start === "boot" && spec.background === false) problems.push("a boot start runs before a logon: give background true, or leave it out");
|
|
69
|
+
if (inBackground(spec) && spec.console === "visible") problems.push("a program in the background has no desktop: give the console hidden, or leave it out");
|
|
63
70
|
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
71
|
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
72
|
if (spec.console !== void 0 && spec.console !== "hidden" && spec.console !== "visible") problems.push(`the console ${JSON.stringify(spec.console)} is not "hidden" or "visible"`);
|
|
@@ -106,9 +113,11 @@ const refuse = (spec) => {
|
|
|
106
113
|
/**
|
|
107
114
|
* This function gives the task file of Windows for a spec, as text. It is a pure function: the same
|
|
108
115
|
* spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.
|
|
109
|
-
* - A start at logon gets a logon trigger
|
|
110
|
-
* minutes. The task ignores a start while its program runs (`IgnoreNew`).
|
|
116
|
+
* - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger
|
|
117
|
+
* also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).
|
|
111
118
|
* - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).
|
|
119
|
+
* - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.
|
|
120
|
+
* Otherwise the task runs only in the session of the user (`InteractiveToken`).
|
|
112
121
|
* Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.
|
|
113
122
|
*/
|
|
114
123
|
const renderTaskXml = (spec, context) => {
|
|
@@ -122,11 +131,13 @@ const renderTaskXml = (spec, context) => {
|
|
|
122
131
|
...spec.args
|
|
123
132
|
] : [...spec.args]).map(windowsArg).join(" ");
|
|
124
133
|
const triggers = [];
|
|
125
|
-
if (spec.start
|
|
126
|
-
triggers.push(` <LogonTrigger>
|
|
134
|
+
if (runsUntilStop(spec.start)) {
|
|
135
|
+
triggers.push(spec.start === "logon" ? ` <LogonTrigger>
|
|
127
136
|
<Enabled>true</Enabled>
|
|
128
137
|
<UserId>${user}</UserId>
|
|
129
|
-
</LogonTrigger>`
|
|
138
|
+
</LogonTrigger>` : ` <BootTrigger>
|
|
139
|
+
<Enabled>true</Enabled>
|
|
140
|
+
</BootTrigger>`);
|
|
130
141
|
if (spec.restart !== null) triggers.push(` <TimeTrigger>
|
|
131
142
|
<Enabled>true</Enabled>
|
|
132
143
|
<StartBoundary>2000-01-01T00:00:00</StartBoundary>
|
|
@@ -159,7 +170,7 @@ ${triggers.join("\n")}
|
|
|
159
170
|
<Principals>
|
|
160
171
|
<Principal id="Author">
|
|
161
172
|
<UserId>${user}</UserId>
|
|
162
|
-
<LogonType
|
|
173
|
+
<LogonType>${inBackground(spec) ? "S4U" : "InteractiveToken"}</LogonType>
|
|
163
174
|
<RunLevel>LeastPrivilege</RunLevel>
|
|
164
175
|
</Principal>
|
|
165
176
|
</Principals>
|
|
@@ -205,7 +216,8 @@ const utf16le = (text) => {
|
|
|
205
216
|
};
|
|
206
217
|
/**
|
|
207
218
|
* This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.
|
|
208
|
-
* - A start at logon is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.
|
|
219
|
+
* - A start at logon or at boot is a service of the type `simple`, wanted by `default.target`. With a restart, it has `Restart=on-failure`.
|
|
220
|
+
* The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.
|
|
209
221
|
* - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.
|
|
210
222
|
*/
|
|
211
223
|
const renderSystemdUnit = (spec) => {
|
|
@@ -216,18 +228,18 @@ const renderSystemdUnit = (spec) => {
|
|
|
216
228
|
"",
|
|
217
229
|
"[Service]"
|
|
218
230
|
];
|
|
219
|
-
lines.push(spec.start
|
|
231
|
+
lines.push(runsUntilStop(spec.start) ? "Type=simple" : "Type=oneshot");
|
|
220
232
|
lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(" ")}`);
|
|
221
233
|
if (spec.cwd !== void 0) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, "%%")}`);
|
|
222
234
|
if (spec.restart !== null) lines.push("Restart=on-failure", `RestartSec=${restartSeconds(spec.restart.after)}`);
|
|
223
235
|
if (spec.timeLimit !== void 0) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, "s")))}`);
|
|
224
|
-
if (spec.start
|
|
236
|
+
if (runsUntilStop(spec.start)) lines.push("", "[Install]", "WantedBy=default.target");
|
|
225
237
|
return `${lines.join("\n")}\n`;
|
|
226
238
|
};
|
|
227
|
-
/** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon. It is a pure function. */
|
|
239
|
+
/** This function gives the systemd timer (`<name>.timer`) of a daily spec, or null for a start at logon or at boot. It is a pure function. */
|
|
228
240
|
const renderSystemdTimer = (spec) => {
|
|
229
241
|
refuse(spec);
|
|
230
|
-
if (spec.start
|
|
242
|
+
if (runsUntilStop(spec.start)) return null;
|
|
231
243
|
const time = dailyTime(spec.start.daily);
|
|
232
244
|
return `${[
|
|
233
245
|
"[Unit]",
|
|
@@ -610,11 +622,16 @@ const servicePaths = (spec, ports) => {
|
|
|
610
622
|
const dir = unitDir(ports);
|
|
611
623
|
return {
|
|
612
624
|
unit: joinPath("linux", dir, `${spec.name}.service`),
|
|
613
|
-
timer: spec.start
|
|
625
|
+
timer: runsUntilStop(spec.start) ? null : joinPath("linux", dir, `${spec.name}.timer`)
|
|
614
626
|
};
|
|
615
627
|
};
|
|
616
628
|
/** This function gives the unit that `systemctl` enables: the timer of a daily job, or the service. */
|
|
617
|
-
const enabledUnit = (spec) => spec.start
|
|
629
|
+
const enabledUnit = (spec) => runsUntilStop(spec.start) ? `${spec.name}.service` : `${spec.name}.timer`;
|
|
630
|
+
/**
|
|
631
|
+
* This text goes with a failure of `schtasks` for a spec in the background. Task Scheduler refuses a boot trigger
|
|
632
|
+
* and an S4U logon from a shell that is not elevated: `Access is denied`, with the code 1 (Windows 11, 2026-11).
|
|
633
|
+
*/
|
|
634
|
+
const ELEVATION = "Task Scheduler refuses a boot trigger and an S4U logon from a shell that is not elevated: start the same operation in a shell of an administrator";
|
|
618
635
|
/** This function gives the path of `conhost.exe` from `SystemRoot`. Without it, Task Scheduler expands `%SystemRoot%` at the start. */
|
|
619
636
|
const conhostPath = (ports) => joinPath("win32", ports.env["SystemRoot"] ?? "%SystemRoot%", "System32", "conhost.exe");
|
|
620
637
|
const runner = (ports) => {
|
|
@@ -645,11 +662,13 @@ const runner = (ports) => {
|
|
|
645
662
|
}
|
|
646
663
|
};
|
|
647
664
|
};
|
|
648
|
-
const failed = (commands, record) => ({
|
|
665
|
+
const failed = (commands, record, note) => ({
|
|
649
666
|
kind: "failed",
|
|
650
667
|
commands,
|
|
651
|
-
problem: `${record.file} ${record.args.join(" ")} gave the code ${record.code}${record.out === "" ? "" : `: ${record.out}`}`
|
|
668
|
+
problem: `${record.file} ${record.args.join(" ")} gave the code ${record.code}${record.out === "" ? "" : `: ${record.out}`}${note === null ? "" : ` (${note})`}`
|
|
652
669
|
});
|
|
670
|
+
/** This function gives the note of a failed command: the elevation of Task Scheduler for a spec in the background, or null. */
|
|
671
|
+
const noteOf = (spec, ports, record) => ports.platform === "win32" && record.file === "schtasks" && inBackground(spec) ? ELEVATION : null;
|
|
653
672
|
const problemOf = (error) => error instanceof Error ? error.message : String(error);
|
|
654
673
|
/**
|
|
655
674
|
* This function runs the steps of an operation. It refuses a spec with problems and a platform that
|
|
@@ -669,7 +688,7 @@ const operate = async (spec, ports, steps) => {
|
|
|
669
688
|
const files = [];
|
|
670
689
|
try {
|
|
671
690
|
const failure = await steps(run, files);
|
|
672
|
-
if (failure !== null) return failed(run.commands, failure);
|
|
691
|
+
if (failure !== null) return failed(run.commands, failure, noteOf(spec, ports, failure));
|
|
673
692
|
} catch (error) {
|
|
674
693
|
return {
|
|
675
694
|
kind: "failed",
|
|
@@ -689,7 +708,9 @@ const firstFailure = (...records) => records.find((record) => record.code !== 0)
|
|
|
689
708
|
* This function installs a service of the user, and by default starts it. It does not throw.
|
|
690
709
|
* - On Windows, it writes the task file in UTF-16 to `stateDir`, and starts `schtasks /Create /XML <file> /F`, then `schtasks /Run`.
|
|
691
710
|
* - On Linux, it writes the unit (and the timer of a daily job), then starts `systemctl --user daemon-reload` and `enable`.
|
|
711
|
+
* For a spec in the background, it first starts `loginctl enable-linger` for the user.
|
|
692
712
|
* A second install replaces the first. Give it the ports of a test, thus no test installs a real task.
|
|
713
|
+
* On Windows, Task Scheduler refuses a spec in the background from a shell that is not elevated: the problem then tells so.
|
|
693
714
|
*/
|
|
694
715
|
const installService = (spec, ports, options = {}) => operate(spec, ports, async (run, files) => {
|
|
695
716
|
const start = options.start ?? true;
|
|
@@ -722,6 +743,10 @@ const installService = (spec, ports, options = {}) => operate(spec, ports, async
|
|
|
722
743
|
await ports.files.write(paths.timer, timer);
|
|
723
744
|
files.push(paths.timer);
|
|
724
745
|
}
|
|
746
|
+
if (inBackground(spec)) {
|
|
747
|
+
const lingered = await run.run("loginctl", ["enable-linger"]);
|
|
748
|
+
if (lingered.code !== 0) return lingered;
|
|
749
|
+
}
|
|
725
750
|
const reloaded = await run.run("systemctl", ["--user", "daemon-reload"]);
|
|
726
751
|
if (reloaded.code !== 0) return reloaded;
|
|
727
752
|
return firstFailure(await run.run("systemctl", [
|
|
@@ -810,8 +835,8 @@ const startService = (spec, ports) => operate(spec, ports, async (run) => {
|
|
|
810
835
|
* This function stops a service, and keeps it stopped until `startService`. It does not throw.
|
|
811
836
|
* - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
|
|
812
837
|
* With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
|
|
813
|
-
* - On Linux, it disables the unit of a logon
|
|
814
|
-
* Thus the next login or the next calendar time does not start it again. The stop sends SIGTERM,
|
|
838
|
+
* - On Linux, it disables the unit of a service at logon or at boot, or the timer of a daily job, and stops it.
|
|
839
|
+
* Thus the next login, the next boot or the next calendar time does not start it again. The stop sends SIGTERM,
|
|
815
840
|
* thus `run()` stops in its stages. A daily job that operates stops too.
|
|
816
841
|
*/
|
|
817
842
|
const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
|
|
@@ -837,7 +862,7 @@ const stopService = (spec, ports, options = {}) => operate(spec, ports, async (r
|
|
|
837
862
|
"--now",
|
|
838
863
|
enabledUnit(spec)
|
|
839
864
|
]);
|
|
840
|
-
if (disabled.code !== 0 || spec.start
|
|
865
|
+
if (disabled.code !== 0 || runsUntilStop(spec.start)) return firstFailure(disabled);
|
|
841
866
|
return firstFailure(await run.run("systemctl", [
|
|
842
867
|
"--user",
|
|
843
868
|
"stop",
|
|
@@ -906,23 +931,110 @@ const serviceStatus = async (spec, ports, options = {}) => {
|
|
|
906
931
|
};
|
|
907
932
|
};
|
|
908
933
|
// src/host/probes.ts
|
|
934
|
+
/** This size is the largest answer that a probe with freshness bounds reads: 1 MiB. */
|
|
935
|
+
const PROBE_BODY_LIMIT = 1048576;
|
|
936
|
+
const isPointer = (pointer) => typeof pointer === "string" && (pointer === "" || pointer.startsWith("/") && !/~[^01]|~$/.test(pointer));
|
|
909
937
|
/** This function gives the problems of a probe: each value that a probe cannot use. */
|
|
910
938
|
const probeProblems = (probe) => {
|
|
911
939
|
if (probe.kind === "http") {
|
|
912
940
|
const problems = [];
|
|
913
941
|
if (!/^https?:\/\//.test(probe.url)) problems.push(`the address ${JSON.stringify(probe.url)} is not an http or https address`);
|
|
914
942
|
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`);
|
|
943
|
+
if (probe.now !== void 0 && !isPointer(probe.now)) problems.push(`the now ${JSON.stringify(probe.now)} is not a JSON Pointer`);
|
|
944
|
+
if (probe.now !== void 0 && probe.fresh === void 0) problems.push("the probe has a now, but no fresh list");
|
|
945
|
+
if (probe.fresh !== void 0 && probe.fresh.length === 0) problems.push("the fresh list is empty");
|
|
946
|
+
for (const bound of probe.fresh ?? []) {
|
|
947
|
+
if (!isPointer(bound.pointer)) problems.push(`the freshness pointer ${JSON.stringify(bound.pointer)} is not a JSON Pointer`);
|
|
948
|
+
if (!(isQuantity(bound.within) && convertible(bound.within.unit, "ms") && valueIn(bound.within, "ms") >= 0)) problems.push(`the freshness bound of ${JSON.stringify(bound.pointer)} is not a time of zero or more`);
|
|
949
|
+
}
|
|
915
950
|
return problems;
|
|
916
951
|
}
|
|
917
952
|
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`];
|
|
918
953
|
if (probe.kind === "command") return probe.program === "" ? ["the program of the command probe is empty"] : [];
|
|
919
954
|
return [`the probe kind ${JSON.stringify(probe.kind)} is not http, tcp or command`];
|
|
920
955
|
};
|
|
956
|
+
/** This function gives the value at a JSON Pointer (RFC 6901), or undefined when the document does not have it. */
|
|
957
|
+
const pointAt = (document, pointer) => {
|
|
958
|
+
if (pointer === "") return document;
|
|
959
|
+
let at = document;
|
|
960
|
+
for (const token of pointer.slice(1).split("/")) {
|
|
961
|
+
const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
962
|
+
if (Array.isArray(at)) {
|
|
963
|
+
if (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= at.length) return void 0;
|
|
964
|
+
at = at[Number(key)];
|
|
965
|
+
} else if (at !== null && typeof at === "object" && Object.hasOwn(at, key)) at = at[key];
|
|
966
|
+
else return void 0;
|
|
967
|
+
}
|
|
968
|
+
return at;
|
|
969
|
+
};
|
|
970
|
+
/** This function gives the time of a value in epoch milliseconds: a finite number, or an ISO 8601 text. */
|
|
971
|
+
const timeOf = (value) => {
|
|
972
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
973
|
+
if (typeof value === "string") {
|
|
974
|
+
const time = Date.parse(value);
|
|
975
|
+
return Number.isNaN(time) ? null : time;
|
|
976
|
+
}
|
|
977
|
+
return null;
|
|
978
|
+
};
|
|
979
|
+
/** This function examines the JSON answer of an http probe against its freshness bounds. */
|
|
980
|
+
const freshness = (url, body, bounds, nowPointer, wall) => {
|
|
981
|
+
let document;
|
|
982
|
+
try {
|
|
983
|
+
document = JSON.parse(body);
|
|
984
|
+
} catch {
|
|
985
|
+
return {
|
|
986
|
+
ok: false,
|
|
987
|
+
why: `${url} did not give JSON`
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
const now = nowPointer === void 0 ? wall : timeOf(pointAt(document, nowPointer));
|
|
991
|
+
if (now === null) return {
|
|
992
|
+
ok: false,
|
|
993
|
+
why: `${url} has no time at ${nowPointer}`
|
|
994
|
+
};
|
|
995
|
+
const stale = [];
|
|
996
|
+
for (const bound of bounds) {
|
|
997
|
+
const time = timeOf(pointAt(document, bound.pointer));
|
|
998
|
+
if (time === null) {
|
|
999
|
+
stale.push(`${bound.pointer} has no time`);
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
const age = Math.max(0, now - time);
|
|
1003
|
+
if (age > valueIn(bound.within, "ms")) stale.push(`${bound.pointer} is ${formatDuration({
|
|
1004
|
+
value: age,
|
|
1005
|
+
unit: "ms"
|
|
1006
|
+
})} old, above ${formatDuration(bound.within)}`);
|
|
1007
|
+
}
|
|
1008
|
+
return stale.length === 0 ? { ok: true } : {
|
|
1009
|
+
ok: false,
|
|
1010
|
+
why: `${url}: ${stale.join("; ")}`
|
|
1011
|
+
};
|
|
1012
|
+
};
|
|
921
1013
|
/** This function uses a probe one time, in a timeout of milliseconds. It does not throw. */
|
|
922
1014
|
const probeOnce = async (probe, timeout, ports) => {
|
|
923
1015
|
try {
|
|
924
1016
|
if (probe.kind === "http") {
|
|
925
1017
|
const want = probe.status ?? 200;
|
|
1018
|
+
if (probe.fresh !== void 0) {
|
|
1019
|
+
if (ports.net.httpText === void 0) return {
|
|
1020
|
+
ok: false,
|
|
1021
|
+
why: "the net port cannot read an answer, thus it cannot examine freshness"
|
|
1022
|
+
};
|
|
1023
|
+
const answer = await ports.net.httpText(probe.url, timeout, PROBE_BODY_LIMIT);
|
|
1024
|
+
if (answer === null) return {
|
|
1025
|
+
ok: false,
|
|
1026
|
+
why: `${probe.url} gave no answer in ${timeout} ms`
|
|
1027
|
+
};
|
|
1028
|
+
if (answer.status !== want) return {
|
|
1029
|
+
ok: false,
|
|
1030
|
+
why: `${probe.url} gave ${answer.status}, not ${want}`
|
|
1031
|
+
};
|
|
1032
|
+
if (!answer.complete) return {
|
|
1033
|
+
ok: false,
|
|
1034
|
+
why: `the answer of ${probe.url} is above ${PROBE_BODY_LIMIT} bytes`
|
|
1035
|
+
};
|
|
1036
|
+
return freshness(probe.url, answer.body, probe.fresh, probe.now, ports.wall());
|
|
1037
|
+
}
|
|
926
1038
|
const status = await ports.net.httpStatus(probe.url, timeout);
|
|
927
1039
|
if (status === want) return { ok: true };
|
|
928
1040
|
return {
|
|
@@ -953,6 +1065,163 @@ const probeOnce = async (probe, timeout, ports) => {
|
|
|
953
1065
|
};
|
|
954
1066
|
}
|
|
955
1067
|
};
|
|
1068
|
+
// src/host/watch.ts
|
|
1069
|
+
/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */
|
|
1070
|
+
const DEFAULT_VERDICT = {
|
|
1071
|
+
type: "debounce",
|
|
1072
|
+
failAfter: 3,
|
|
1073
|
+
recoverAfter: 2
|
|
1074
|
+
};
|
|
1075
|
+
const DEFAULT_JITTER = .1;
|
|
1076
|
+
const ms$1 = (amount) => valueIn(amount, "ms");
|
|
1077
|
+
const isTimeAtLeast$1 = (value, floor, strict) => isTime(value) && (strict ? ms$1(value) > floor : ms$1(value) >= floor);
|
|
1078
|
+
const whole = (value) => Number.isInteger(value) && value >= 1;
|
|
1079
|
+
/** This function gives the problems of a watch spec: each value that the watcher cannot use. */
|
|
1080
|
+
const watchProblems = (spec) => {
|
|
1081
|
+
const problems = [];
|
|
1082
|
+
if (spec.targets.length === 0) problems.push("the spec has no target");
|
|
1083
|
+
const names = /* @__PURE__ */ new Set();
|
|
1084
|
+
for (const target of spec.targets) {
|
|
1085
|
+
const of = `the target ${JSON.stringify(target.name)}`;
|
|
1086
|
+
if (target.name === "") problems.push("a target name is empty");
|
|
1087
|
+
if (names.has(target.name)) problems.push(`${of} is in the spec two times`);
|
|
1088
|
+
names.add(target.name);
|
|
1089
|
+
problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));
|
|
1090
|
+
if (!isTimeAtLeast$1(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);
|
|
1091
|
+
if (!isTimeAtLeast$1(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);
|
|
1092
|
+
else if (isTimeAtLeast$1(target.interval, 0, true) && ms$1(target.timeout) > ms$1(target.interval)) problems.push(`${of}: the timeout is above the interval`);
|
|
1093
|
+
const jitter = target.jitter ?? DEFAULT_JITTER;
|
|
1094
|
+
if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);
|
|
1095
|
+
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
1096
|
+
if (verdict.type === "debounce") {
|
|
1097
|
+
if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);
|
|
1098
|
+
if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);
|
|
1099
|
+
} else if (verdict.type === "window") {
|
|
1100
|
+
if (!isTimeAtLeast$1(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);
|
|
1101
|
+
if (verdict.recoverAfter !== void 0 && !isTimeAtLeast$1(verdict.recoverAfter, 0, false)) problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);
|
|
1102
|
+
} else problems.push(`${of}: the verdict type ${JSON.stringify(verdict.type)} is not debounce or window`);
|
|
1103
|
+
}
|
|
1104
|
+
return problems;
|
|
1105
|
+
};
|
|
1106
|
+
const timingOf = (target) => {
|
|
1107
|
+
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
1108
|
+
return verdict.type === "debounce" ? {
|
|
1109
|
+
type: "debounce",
|
|
1110
|
+
interval: target.interval,
|
|
1111
|
+
failAfter: verdict.failAfter,
|
|
1112
|
+
recoverAfter: verdict.recoverAfter
|
|
1113
|
+
} : {
|
|
1114
|
+
type: "window",
|
|
1115
|
+
failAfter: verdict.failAfter,
|
|
1116
|
+
recoverAfter: verdict.recoverAfter
|
|
1117
|
+
};
|
|
1118
|
+
};
|
|
1119
|
+
/**
|
|
1120
|
+
* This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the
|
|
1121
|
+
* clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a
|
|
1122
|
+
* window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change
|
|
1123
|
+
* goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a
|
|
1124
|
+
* problem.
|
|
1125
|
+
*/
|
|
1126
|
+
const watchTargets = (spec, ports, options) => {
|
|
1127
|
+
const problems = watchProblems(spec);
|
|
1128
|
+
if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join("; ")}`);
|
|
1129
|
+
const random = options.random ?? Math.random;
|
|
1130
|
+
let stopped = false;
|
|
1131
|
+
const emit = (unit, to) => {
|
|
1132
|
+
if (unit.health === to) return;
|
|
1133
|
+
const change = {
|
|
1134
|
+
target: unit.target.name,
|
|
1135
|
+
from: unit.health,
|
|
1136
|
+
to,
|
|
1137
|
+
at: ports.wall(),
|
|
1138
|
+
why: to === "down" ? unit.why : null
|
|
1139
|
+
};
|
|
1140
|
+
unit.health = to;
|
|
1141
|
+
unit.since = change.at;
|
|
1142
|
+
if (stopped) return;
|
|
1143
|
+
try {
|
|
1144
|
+
options.onChange(change);
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
ports.logger?.log("warn", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
const watched = spec.targets.map((target) => {
|
|
1150
|
+
const unit = {
|
|
1151
|
+
target,
|
|
1152
|
+
health: "unknown",
|
|
1153
|
+
since: ports.wall(),
|
|
1154
|
+
last: null,
|
|
1155
|
+
lastAt: null,
|
|
1156
|
+
failures: 0,
|
|
1157
|
+
why: null
|
|
1158
|
+
};
|
|
1159
|
+
const trace = options.trace === void 0 ? void 0 : (from, to, on) => options.trace?.(target.name, from, to, on);
|
|
1160
|
+
const timeout = ms$1(target.timeout);
|
|
1161
|
+
let probed = null;
|
|
1162
|
+
const gate = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? "down" : "up"), trace);
|
|
1163
|
+
const record = (result) => {
|
|
1164
|
+
const own = probed;
|
|
1165
|
+
probed = null;
|
|
1166
|
+
const seen = result.outcome === "ok" ? { ok: true } : {
|
|
1167
|
+
ok: false,
|
|
1168
|
+
why: !result.timedOut && own !== null && !own.ok ? own.why : result.cause ?? "the poll failed"
|
|
1169
|
+
};
|
|
1170
|
+
unit.last = seen;
|
|
1171
|
+
unit.lastAt = ports.wall();
|
|
1172
|
+
unit.failures = seen.ok ? 0 : unit.failures + 1;
|
|
1173
|
+
if (!seen.ok) unit.why = seen.why;
|
|
1174
|
+
gate.record(result);
|
|
1175
|
+
if (seen.ok && unit.health === "unknown" && !gate.tripped) emit(unit, "up");
|
|
1176
|
+
};
|
|
1177
|
+
return {
|
|
1178
|
+
unit,
|
|
1179
|
+
gate,
|
|
1180
|
+
loop: poller({
|
|
1181
|
+
name: target.name,
|
|
1182
|
+
poll: {
|
|
1183
|
+
interval: target.interval,
|
|
1184
|
+
jitter: target.jitter ?? DEFAULT_JITTER,
|
|
1185
|
+
timeout: target.timeout
|
|
1186
|
+
},
|
|
1187
|
+
run: async () => {
|
|
1188
|
+
const result = await probeOnce(target.probe, timeout, ports);
|
|
1189
|
+
probed = result;
|
|
1190
|
+
return result.ok ? "ok" : "error";
|
|
1191
|
+
},
|
|
1192
|
+
clock: ports.clock,
|
|
1193
|
+
random,
|
|
1194
|
+
forced: () => false,
|
|
1195
|
+
record,
|
|
1196
|
+
trace
|
|
1197
|
+
})
|
|
1198
|
+
};
|
|
1199
|
+
});
|
|
1200
|
+
const states = () => watched.map(({ unit }) => ({
|
|
1201
|
+
name: unit.target.name,
|
|
1202
|
+
health: unit.health,
|
|
1203
|
+
since: unit.since,
|
|
1204
|
+
last: unit.last,
|
|
1205
|
+
lastAt: unit.lastAt,
|
|
1206
|
+
failures: unit.failures
|
|
1207
|
+
}));
|
|
1208
|
+
for (const { loop } of watched) loop.start(0);
|
|
1209
|
+
return {
|
|
1210
|
+
states,
|
|
1211
|
+
async pollNow() {
|
|
1212
|
+
await Promise.all(watched.map(({ loop }) => loop.pollNow()));
|
|
1213
|
+
return states();
|
|
1214
|
+
},
|
|
1215
|
+
stop() {
|
|
1216
|
+
if (stopped) return;
|
|
1217
|
+
stopped = true;
|
|
1218
|
+
for (const { gate, loop } of watched) {
|
|
1219
|
+
loop.stop();
|
|
1220
|
+
gate.stop();
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
};
|
|
956
1225
|
// src/host/env.ts
|
|
957
1226
|
const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
958
1227
|
/** This function reads a value in double quotes: `\n`, `\t`, `\"` and `\\` are escapes. */
|
|
@@ -1123,6 +1392,11 @@ const groupProblems = (spec) => {
|
|
|
1123
1392
|
"within"
|
|
1124
1393
|
]) if (!isTimeAtLeast(program.ready[field], 0, true)) problems.push(`${of}: the ${field} of the probe is not a time above zero`);
|
|
1125
1394
|
}
|
|
1395
|
+
if (program.alive !== void 0) {
|
|
1396
|
+
problems.push(...probeProblems(program.alive.probe).map((problem) => `${of}: the liveness probe: ${problem}`));
|
|
1397
|
+
for (const field of ["interval", "timeout"]) if (!isTimeAtLeast(program.alive[field], 0, true)) problems.push(`${of}: the ${field} of the liveness probe is not a time above zero`);
|
|
1398
|
+
if (!(Number.isInteger(program.alive.failures) && program.alive.failures >= 1)) problems.push(`${of}: the failures of the liveness probe is not a whole number of 1 or more`);
|
|
1399
|
+
}
|
|
1126
1400
|
if (program.restart !== void 0 && program.restart !== null) {
|
|
1127
1401
|
problems.push(...backoffProblems(program.restart.backoff).map((problem) => `${of}: ${problem}`));
|
|
1128
1402
|
if (!isTimeAtLeast(program.restart.resetAfter, 0, false)) problems.push(`${of}: the resetAfter is not a time of zero or more`);
|
|
@@ -1195,6 +1469,7 @@ const superviseGroup = (spec, ports, options = {}) => {
|
|
|
1195
1469
|
child: null,
|
|
1196
1470
|
lock: null,
|
|
1197
1471
|
timers: [],
|
|
1472
|
+
watch: null,
|
|
1198
1473
|
restarts: 0,
|
|
1199
1474
|
detail: null,
|
|
1200
1475
|
reason: null,
|
|
@@ -1204,6 +1479,8 @@ const superviseGroup = (spec, ports, options = {}) => {
|
|
|
1204
1479
|
const unitOf = (name) => units.get(name);
|
|
1205
1480
|
const clearTimers = (unit) => {
|
|
1206
1481
|
for (const cancel of unit.timers.splice(0)) cancel();
|
|
1482
|
+
unit.watch?.();
|
|
1483
|
+
unit.watch = null;
|
|
1207
1484
|
};
|
|
1208
1485
|
const environment = async (unit) => {
|
|
1209
1486
|
const env = {};
|
|
@@ -1276,8 +1553,56 @@ const superviseGroup = (spec, ports, options = {}) => {
|
|
|
1276
1553
|
if (unit.retry !== null && restart !== null) unit.timers.push(ports.clock.after(ms(restart.resetAfter), () => {
|
|
1277
1554
|
if (unit.child === child && unit.phase === "ready") unit.retry?.reset();
|
|
1278
1555
|
}));
|
|
1556
|
+
if (unit.spec.alive !== void 0) watch(unit, child, unit.spec.alive);
|
|
1279
1557
|
considerAll();
|
|
1280
1558
|
};
|
|
1559
|
+
/** This function uses the liveness probe of a ready program each interval, and stops the program after `failures` failures in sequence. */
|
|
1560
|
+
const watch = (unit, child, alive) => {
|
|
1561
|
+
let failures = 0;
|
|
1562
|
+
const current = () => unit.child === child && unit.phase === "ready" && !stopping;
|
|
1563
|
+
const next = () => {
|
|
1564
|
+
unit.watch = ports.clock.after(ms(alive.interval), () => {
|
|
1565
|
+
unit.watch = null;
|
|
1566
|
+
check();
|
|
1567
|
+
});
|
|
1568
|
+
};
|
|
1569
|
+
const check = async () => {
|
|
1570
|
+
if (!current()) return;
|
|
1571
|
+
const result = await probeOnce(alive.probe, ms(alive.timeout), ports);
|
|
1572
|
+
if (!current()) return;
|
|
1573
|
+
if (result.ok) {
|
|
1574
|
+
if (failures > 0) say("info", `${unit.spec.name} is alive again`, {
|
|
1575
|
+
program: unit.spec.name,
|
|
1576
|
+
pid: child.pid,
|
|
1577
|
+
failures
|
|
1578
|
+
});
|
|
1579
|
+
failures = 0;
|
|
1580
|
+
unit.detail = null;
|
|
1581
|
+
next();
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
failures += 1;
|
|
1585
|
+
unit.detail = `the liveness probe failed ${failures} of ${alive.failures} times in sequence (${result.why})`;
|
|
1586
|
+
if (failures < alive.failures) {
|
|
1587
|
+
say("warn", `${unit.spec.name}: ${unit.detail}`, {
|
|
1588
|
+
program: unit.spec.name,
|
|
1589
|
+
pid: child.pid,
|
|
1590
|
+
why: result.why
|
|
1591
|
+
});
|
|
1592
|
+
next();
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
unit.reason = `its liveness probe failed ${failures} times in sequence (${result.why})`;
|
|
1596
|
+
unit.detail = unit.reason;
|
|
1597
|
+
say("warn", `${unit.spec.name} is not alive, thus it stops`, {
|
|
1598
|
+
program: unit.spec.name,
|
|
1599
|
+
pid: child.pid,
|
|
1600
|
+
why: result.why
|
|
1601
|
+
});
|
|
1602
|
+
stagedStop(unit, child);
|
|
1603
|
+
};
|
|
1604
|
+
next();
|
|
1605
|
+
};
|
|
1281
1606
|
const probe = (unit, child, ready) => {
|
|
1282
1607
|
const deadline = ports.clock.now() + ms(ready.within);
|
|
1283
1608
|
const attempt = async () => {
|
|
@@ -1695,19 +2020,66 @@ const nodeProcesses = {
|
|
|
1695
2020
|
signalGroup: (pid, signal) => process.platform !== "win32" && sendSignal(-pid, signal),
|
|
1696
2021
|
spawn: nodeSpawn
|
|
1697
2022
|
};
|
|
2023
|
+
/**
|
|
2024
|
+
* This function sends a GET request that does not follow a redirect. The timeout also stops the
|
|
2025
|
+
* read of the body. The status read and the text read use it, thus they have one timeout.
|
|
2026
|
+
*/
|
|
2027
|
+
const get = (url, timeout) => fetch(url, {
|
|
2028
|
+
signal: AbortSignal.timeout(timeout),
|
|
2029
|
+
redirect: "manual"
|
|
2030
|
+
});
|
|
2031
|
+
/**
|
|
2032
|
+
* This function reads the body of an answer up to `limit` bytes, and gives the status and the text.
|
|
2033
|
+
* At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a
|
|
2034
|
+
* character that two parts of the body split. The unit tests give it answers with no network.
|
|
2035
|
+
*/
|
|
2036
|
+
const answerText = async (response, limit) => {
|
|
2037
|
+
const reader = response.body?.getReader();
|
|
2038
|
+
if (reader === void 0) return {
|
|
2039
|
+
status: response.status,
|
|
2040
|
+
body: "",
|
|
2041
|
+
complete: true
|
|
2042
|
+
};
|
|
2043
|
+
const decoder = new TextDecoder();
|
|
2044
|
+
let body = "";
|
|
2045
|
+
let size = 0;
|
|
2046
|
+
for (;;) {
|
|
2047
|
+
const read = await reader.read();
|
|
2048
|
+
if (read.done) return {
|
|
2049
|
+
status: response.status,
|
|
2050
|
+
body: body + decoder.decode(),
|
|
2051
|
+
complete: true
|
|
2052
|
+
};
|
|
2053
|
+
if (size + read.value.byteLength > limit) {
|
|
2054
|
+
body += decoder.decode(read.value.subarray(0, limit - size));
|
|
2055
|
+
await reader.cancel();
|
|
2056
|
+
return {
|
|
2057
|
+
status: response.status,
|
|
2058
|
+
body,
|
|
2059
|
+
complete: false
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
body += decoder.decode(read.value, { stream: true });
|
|
2063
|
+
size += read.value.byteLength;
|
|
2064
|
+
}
|
|
2065
|
+
};
|
|
1698
2066
|
const nodeNet = {
|
|
1699
2067
|
async httpStatus(url, timeout) {
|
|
1700
2068
|
try {
|
|
1701
|
-
const response = await
|
|
1702
|
-
signal: AbortSignal.timeout(timeout),
|
|
1703
|
-
redirect: "manual"
|
|
1704
|
-
});
|
|
2069
|
+
const response = await get(url, timeout);
|
|
1705
2070
|
await response.body?.cancel();
|
|
1706
2071
|
return response.status;
|
|
1707
2072
|
} catch {
|
|
1708
2073
|
return null;
|
|
1709
2074
|
}
|
|
1710
2075
|
},
|
|
2076
|
+
async httpText(url, timeout, limit) {
|
|
2077
|
+
try {
|
|
2078
|
+
return await answerText(await get(url, timeout), limit);
|
|
2079
|
+
} catch {
|
|
2080
|
+
return null;
|
|
2081
|
+
}
|
|
2082
|
+
},
|
|
1711
2083
|
tcpConnect: (host, port, timeout) => new Promise((resolve) => {
|
|
1712
2084
|
const socket = connect({
|
|
1713
2085
|
host,
|
|
@@ -1750,6 +2122,6 @@ const nodeHostPorts = (options = {}) => {
|
|
|
1750
2122
|
...options.logger === void 0 ? {} : { logger: options.logger }
|
|
1751
2123
|
};
|
|
1752
2124
|
};
|
|
1753
|
-
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 };
|
|
2125
|
+
export { DEFAULT_RESTART, DEFAULT_VERDICT, PROBE_BODY_LIMIT, 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, watchProblems, watchTargets, windowsArg, writeDiscovery };
|
|
1754
2126
|
|
|
1755
2127
|
//# sourceMappingURL=host.js.map
|