@mark1russell7/service 0.8.18 → 0.8.20
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 +19 -0
- package/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +470 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +223 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +517 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +517 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +24 -3277
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
- package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +152 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +34 -0
- package/build/watchdog.js +53 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +4 -3
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-Bgy6Gmvl.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { convertible, isQuantity, valueIn } from "@mark1russell7/quantity";
|
|
2
|
+
import { escapeAttribute } from "@mark1russell7/text";
|
|
3
|
+
// src/host/render.ts
|
|
4
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
5
|
+
const DAILY = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
|
6
|
+
/** 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. */
|
|
7
|
+
const hasControl = (text) => {
|
|
8
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
9
|
+
const code = text.charCodeAt(at);
|
|
10
|
+
if (code < 32 || code === 127) return true;
|
|
11
|
+
}
|
|
12
|
+
return false;
|
|
13
|
+
};
|
|
14
|
+
/** This function gives the time of a daily start, or null when the text is not `HH:MM`. */
|
|
15
|
+
const dailyTime = (text) => {
|
|
16
|
+
const found = DAILY.exec(text);
|
|
17
|
+
return found === null ? null : {
|
|
18
|
+
hour: found[1],
|
|
19
|
+
minute: found[2]
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */
|
|
23
|
+
const runsUntilStop = (start) => start === "logon" || start === "boot";
|
|
24
|
+
/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */
|
|
25
|
+
const inBackground = (spec) => spec.background ?? spec.start === "boot";
|
|
26
|
+
/** This function tells if a value is a time: a quantity in a unit of time. */
|
|
27
|
+
const isTime = (value) => isQuantity(value) && convertible(value.unit, "ms");
|
|
28
|
+
/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */
|
|
29
|
+
const serviceProblems = (spec) => {
|
|
30
|
+
const problems = [];
|
|
31
|
+
if (!NAME.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, ".", "_" and "-"`);
|
|
32
|
+
const fields = [
|
|
33
|
+
["description", spec.description],
|
|
34
|
+
["program", spec.program],
|
|
35
|
+
["stateDir", spec.stateDir],
|
|
36
|
+
...spec.args.map((arg, at) => [`argument ${at}`, arg]),
|
|
37
|
+
...spec.cwd === void 0 ? [] : [["cwd", spec.cwd]]
|
|
38
|
+
];
|
|
39
|
+
for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);
|
|
40
|
+
if (spec.program === "") problems.push("the program is empty");
|
|
41
|
+
if (spec.stateDir === "") problems.push("the stateDir is empty");
|
|
42
|
+
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`);
|
|
43
|
+
if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push("a daily job has no restart: give null");
|
|
44
|
+
if (spec.background !== void 0 && typeof spec.background !== "boolean") problems.push("the background is not true or false");
|
|
45
|
+
if (spec.start === "boot" && spec.background === false) problems.push("a boot start runs before a logon: give background true, or leave it out");
|
|
46
|
+
if (inBackground(spec) && spec.console === "visible") problems.push("a program in the background has no desktop: give the console hidden, or leave it out");
|
|
47
|
+
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");
|
|
48
|
+
if (spec.timeLimit !== void 0 && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, "ms") > 0)) problems.push("the time limit is not a time above zero");
|
|
49
|
+
if (spec.console !== void 0 && spec.console !== "hidden" && spec.console !== "visible") problems.push(`the console ${JSON.stringify(spec.console)} is not "hidden" or "visible"`);
|
|
50
|
+
return problems;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.
|
|
54
|
+
* It doubles each backslash before a quote and at the end. One pass keeps the time linear.
|
|
55
|
+
*/
|
|
56
|
+
const windowsArg = (arg) => {
|
|
57
|
+
if (arg !== "" && !/[\s"]/.test(arg)) return arg;
|
|
58
|
+
let quoted = "\"";
|
|
59
|
+
let slashes = 0;
|
|
60
|
+
for (const char of arg) {
|
|
61
|
+
if (char === "\\") {
|
|
62
|
+
slashes += 1;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
quoted += char === "\"" ? `${"\\".repeat(slashes * 2 + 1)}"` : `${"\\".repeat(slashes)}${char}`;
|
|
66
|
+
slashes = 0;
|
|
67
|
+
}
|
|
68
|
+
return `${quoted}${"\\".repeat(slashes * 2)}"`;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as
|
|
72
|
+
* `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,
|
|
73
|
+
* a quote, a backslash or a `;` goes in double quotes.
|
|
74
|
+
*/
|
|
75
|
+
const systemdArg = (arg) => {
|
|
76
|
+
const escaped = arg.replace(/%/g, () => "%%").replace(/\$/g, () => "$$");
|
|
77
|
+
if (escaped !== "" && !/[\s"'\\;]/.test(escaped)) return escaped;
|
|
78
|
+
return `"${escaped.replace(/\\/g, () => "\\\\").replace(/"/g, () => "\\\"")}"`;
|
|
79
|
+
};
|
|
80
|
+
/** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */
|
|
81
|
+
const isoSeconds = (time) => `PT${Math.max(1, Math.ceil(valueIn(time, "s")))}S`;
|
|
82
|
+
/** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */
|
|
83
|
+
const repeatMinutes = (time) => Math.max(1, Math.ceil(valueIn(time, "min")));
|
|
84
|
+
/** This function gives the seconds of a restart wait for systemd, a whole number. */
|
|
85
|
+
const restartSeconds = (time) => Math.max(0, Math.ceil(valueIn(time, "s")));
|
|
86
|
+
const refuse = (spec) => {
|
|
87
|
+
const problems = serviceProblems(spec);
|
|
88
|
+
if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join("; ")}`);
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* This function gives the task file of Windows for a spec, as text. It is a pure function: the same
|
|
92
|
+
* spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.
|
|
93
|
+
* - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger
|
|
94
|
+
* also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).
|
|
95
|
+
* - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).
|
|
96
|
+
* - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.
|
|
97
|
+
* Otherwise the task runs only in the session of the user (`InteractiveToken`).
|
|
98
|
+
* Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.
|
|
99
|
+
*/
|
|
100
|
+
const renderTaskXml = (spec, context) => {
|
|
101
|
+
refuse(spec);
|
|
102
|
+
const user = escapeAttribute(context.user);
|
|
103
|
+
const hidden = (spec.console ?? "hidden") === "hidden";
|
|
104
|
+
const command = hidden ? context.conhost : spec.program;
|
|
105
|
+
const args = (hidden ? [
|
|
106
|
+
"--headless",
|
|
107
|
+
spec.program,
|
|
108
|
+
...spec.args
|
|
109
|
+
] : [...spec.args]).map(windowsArg).join(" ");
|
|
110
|
+
const triggers = [];
|
|
111
|
+
if (runsUntilStop(spec.start)) {
|
|
112
|
+
triggers.push(spec.start === "logon" ? ` <LogonTrigger>
|
|
113
|
+
<Enabled>true</Enabled>
|
|
114
|
+
<UserId>${user}</UserId>
|
|
115
|
+
</LogonTrigger>` : ` <BootTrigger>
|
|
116
|
+
<Enabled>true</Enabled>
|
|
117
|
+
</BootTrigger>`);
|
|
118
|
+
if (spec.restart !== null) triggers.push(` <TimeTrigger>
|
|
119
|
+
<Enabled>true</Enabled>
|
|
120
|
+
<StartBoundary>2000-01-01T00:00:00</StartBoundary>
|
|
121
|
+
<Repetition>
|
|
122
|
+
<Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>
|
|
123
|
+
<StopAtDurationEnd>false</StopAtDurationEnd>
|
|
124
|
+
</Repetition>
|
|
125
|
+
</TimeTrigger>`);
|
|
126
|
+
} else {
|
|
127
|
+
const time = dailyTime(spec.start.daily);
|
|
128
|
+
triggers.push(` <CalendarTrigger>
|
|
129
|
+
<Enabled>true</Enabled>
|
|
130
|
+
<StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>
|
|
131
|
+
<ScheduleByDay>
|
|
132
|
+
<DaysInterval>1</DaysInterval>
|
|
133
|
+
</ScheduleByDay>
|
|
134
|
+
</CalendarTrigger>`);
|
|
135
|
+
}
|
|
136
|
+
const cwd = spec.cwd === void 0 ? "" : `\n <WorkingDirectory>${escapeAttribute(spec.cwd)}</WorkingDirectory>`;
|
|
137
|
+
const limit = spec.timeLimit === void 0 ? "PT0S" : isoSeconds(spec.timeLimit);
|
|
138
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
139
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
140
|
+
<RegistrationInfo>
|
|
141
|
+
<Description>${escapeAttribute(spec.description)}</Description>
|
|
142
|
+
<URI>\\${escapeAttribute(spec.name)}</URI>
|
|
143
|
+
</RegistrationInfo>
|
|
144
|
+
<Triggers>
|
|
145
|
+
${triggers.join("\n")}
|
|
146
|
+
</Triggers>
|
|
147
|
+
<Principals>
|
|
148
|
+
<Principal id="Author">
|
|
149
|
+
<UserId>${user}</UserId>
|
|
150
|
+
<LogonType>${inBackground(spec) ? "S4U" : "InteractiveToken"}</LogonType>
|
|
151
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
152
|
+
</Principal>
|
|
153
|
+
</Principals>
|
|
154
|
+
<Settings>
|
|
155
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
156
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
157
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
158
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
159
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
160
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
161
|
+
<IdleSettings>
|
|
162
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
163
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
164
|
+
</IdleSettings>
|
|
165
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
166
|
+
<Enabled>true</Enabled>
|
|
167
|
+
<Hidden>false</Hidden>
|
|
168
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
169
|
+
<WakeToRun>false</WakeToRun>
|
|
170
|
+
<ExecutionTimeLimit>${limit}</ExecutionTimeLimit>
|
|
171
|
+
<Priority>5</Priority>
|
|
172
|
+
</Settings>
|
|
173
|
+
<Actions Context="Author">
|
|
174
|
+
<Exec>
|
|
175
|
+
<Command>${escapeAttribute(windowsArg(command))}</Command>
|
|
176
|
+
<Arguments>${escapeAttribute(args)}</Arguments>${cwd}
|
|
177
|
+
</Exec>
|
|
178
|
+
</Actions>
|
|
179
|
+
</Task>
|
|
180
|
+
`;
|
|
181
|
+
};
|
|
182
|
+
/** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */
|
|
183
|
+
const utf16le = (text) => {
|
|
184
|
+
const bytes = new Uint8Array(2 + text.length * 2);
|
|
185
|
+
bytes[0] = 255;
|
|
186
|
+
bytes[1] = 254;
|
|
187
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
188
|
+
const unit = text.charCodeAt(at);
|
|
189
|
+
bytes[2 + at * 2] = unit & 255;
|
|
190
|
+
bytes[3 + at * 2] = unit >> 8;
|
|
191
|
+
}
|
|
192
|
+
return bytes;
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.
|
|
196
|
+
* - 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`.
|
|
197
|
+
* The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.
|
|
198
|
+
* - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.
|
|
199
|
+
*/
|
|
200
|
+
const renderSystemdUnit = (spec) => {
|
|
201
|
+
refuse(spec);
|
|
202
|
+
const lines = [
|
|
203
|
+
"[Unit]",
|
|
204
|
+
`Description=${spec.description.replace(/%/g, "%%")}`,
|
|
205
|
+
"",
|
|
206
|
+
"[Service]"
|
|
207
|
+
];
|
|
208
|
+
lines.push(runsUntilStop(spec.start) ? "Type=simple" : "Type=oneshot");
|
|
209
|
+
lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(" ")}`);
|
|
210
|
+
if (spec.cwd !== void 0) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, "%%")}`);
|
|
211
|
+
if (spec.restart !== null) lines.push("Restart=on-failure", `RestartSec=${restartSeconds(spec.restart.after)}`);
|
|
212
|
+
if (spec.timeLimit !== void 0) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, "s")))}`);
|
|
213
|
+
if (runsUntilStop(spec.start)) lines.push("", "[Install]", "WantedBy=default.target");
|
|
214
|
+
return `${lines.join("\n")}\n`;
|
|
215
|
+
};
|
|
216
|
+
/** 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. */
|
|
217
|
+
const renderSystemdTimer = (spec) => {
|
|
218
|
+
refuse(spec);
|
|
219
|
+
if (runsUntilStop(spec.start)) return null;
|
|
220
|
+
const time = dailyTime(spec.start.daily);
|
|
221
|
+
return `${[
|
|
222
|
+
"[Unit]",
|
|
223
|
+
`Description=${spec.description.replace(/%/g, "%%")}`,
|
|
224
|
+
"",
|
|
225
|
+
"[Timer]",
|
|
226
|
+
`OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,
|
|
227
|
+
"Persistent=true",
|
|
228
|
+
"",
|
|
229
|
+
"[Install]",
|
|
230
|
+
"WantedBy=timers.target"
|
|
231
|
+
].join("\n")}\n`;
|
|
232
|
+
};
|
|
233
|
+
export { dailyTime, inBackground, isTime, renderSystemdTimer, renderSystemdUnit, renderTaskXml, runsUntilStop, serviceProblems, systemdArg, utf16le, windowsArg };
|
|
234
|
+
|
|
235
|
+
//# sourceMappingURL=render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render.js","names":["xmlText"],"sources":["../../src/host/render.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, isQuantity, valueIn } from \"@mark1russell7/quantity\";\nimport { escapeAttribute as xmlText } from \"@mark1russell7/text\";\n\n/**\n * A service start tells when the system starts the program.\n * - `logon`: at the logon of the user. The program runs until it stops.\n * - `boot`: at the start of the computer, before a logon. The program runs until it stops. It runs in the background.\n * - `{ daily: \"HH:MM\" }`: each day at that local time, as a job that runs to its end.\n */\nexport type ServiceStart = \"logon\" | \"boot\" | { readonly daily: string };\n\n/** A restart policy tells how long the system waits before it starts a program again after it stops. */\nexport interface RestartPolicy {\n /** This time is the wait before the next start. On Windows, the task starts again at whole minutes, 1 minute or more. */\n readonly after: Quantity;\n}\n\n/** A service spec tells which program the system runs as a user service, and when. */\nexport interface ServiceSpec {\n /** This name is the name of the Windows task and of the systemd unit: letters, digits, `.`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /** This path is the full path of the program, for example the path of Node. */\n readonly program: string;\n readonly args: readonly string[];\n /** This folder is the working folder of the program. */\n readonly cwd?: string | undefined;\n readonly start: ServiceStart;\n /** This policy starts a program at logon or at boot again after it stops. Null starts it only at its start. A daily job has no restart. */\n readonly restart: RestartPolicy | null;\n /**\n * True runs the program when the user is not logged on. On Windows, the task gets an S4U logon, and Task Scheduler\n * then refuses the task from a shell that is not elevated. On Linux, the install sets the linger of the user\n * (`loginctl enable-linger`), thus the user manager of systemd starts at boot and stays after the logout.\n * The default is true for a boot start, and false for the other starts.\n */\n readonly background?: boolean | undefined;\n /** This folder keeps the files of the host, for example the task file of Windows. */\n readonly stateDir: string;\n /** On Windows, `hidden` starts the program through `conhost --headless`, thus no window opens. The default is `hidden`. */\n readonly console?: \"hidden\" | \"visible\" | undefined;\n /** This time is the most that one run can take. The default is no limit. */\n readonly timeLimit?: Quantity | undefined;\n}\n\n/** These are the parts of the task of Windows that come from the system, not from the spec. */\nexport interface TaskContext {\n /** This text is the user of the task, for example `HOST\\name`. */\n readonly user: string;\n /** This path is the path of `conhost.exe`, for a hidden console. */\n readonly conhost: string;\n}\n\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst DAILY = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n/** 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. */\nconst hasControl = (text: string): boolean => {\n for (let at = 0; at < text.length; at += 1) {\n const code = text.charCodeAt(at);\n if (code < 0x20 || code === 0x7f) return true;\n }\n return false;\n};\n\n/** This function gives the time of a daily start, or null when the text is not `HH:MM`. */\nexport const dailyTime = (text: string): { readonly hour: string; readonly minute: string } | null => {\n const found = DAILY.exec(text);\n return found === null ? null : { hour: found[1]!, minute: found[2]! };\n};\n\n/** This function tells if the program of a spec runs until it stops: a start at logon or at boot, not a daily job. */\nexport const runsUntilStop = (start: ServiceStart): start is \"logon\" | \"boot\" => start === \"logon\" || start === \"boot\";\n\n/** This function tells if a spec runs when the user is not logged on: its `background`, or true for a boot start. */\nexport const inBackground = (spec: ServiceSpec): boolean => spec.background ?? spec.start === \"boot\";\n\n/** This function tells if a value is a time: a quantity in a unit of time. */\nexport const isTime = (value: unknown): value is Quantity => isQuantity(value) && convertible(value.unit, \"ms\");\n\n/** This function gives the problems of a service spec: each value that the task or the unit cannot use. */\nexport const serviceProblems = (spec: ServiceSpec): string[] => {\n const problems: string[] = [];\n if (!NAME.test(spec.name)) problems.push(`the name ${JSON.stringify(spec.name)} is not letters, digits, \".\", \"_\" and \"-\"`);\n const fields: Array<[string, string]> = [\n [\"description\", spec.description],\n [\"program\", spec.program],\n [\"stateDir\", spec.stateDir],\n ...spec.args.map((arg, at): [string, string] => [`argument ${at}`, arg]),\n ...(spec.cwd === undefined ? [] : [[\"cwd\", spec.cwd] as [string, string]]),\n ];\n for (const [field, value] of fields) if (hasControl(value)) problems.push(`the ${field} has a control character`);\n if (spec.program === \"\") problems.push(\"the program is empty\");\n if (spec.stateDir === \"\") problems.push(\"the stateDir is empty\");\n if (!runsUntilStop(spec.start) && dailyTime(spec.start.daily) === null)\n problems.push(`the daily start ${JSON.stringify(spec.start.daily)} is not a time HH:MM`);\n if (!runsUntilStop(spec.start) && spec.restart !== null) problems.push(\"a daily job has no restart: give null\");\n if (spec.background !== undefined && typeof spec.background !== \"boolean\") problems.push(\"the background is not true or false\");\n if (spec.start === \"boot\" && spec.background === false) problems.push(\"a boot start runs before a logon: give background true, or leave it out\");\n if (inBackground(spec) && spec.console === \"visible\") problems.push(\"a program in the background has no desktop: give the console hidden, or leave it out\");\n if (spec.restart !== null && !(isTime(spec.restart.after) && valueIn(spec.restart.after, \"ms\") >= 0))\n problems.push(\"the restart wait is not a time of zero or more\");\n if (spec.timeLimit !== undefined && !(isTime(spec.timeLimit) && valueIn(spec.timeLimit, \"ms\") > 0))\n problems.push(\"the time limit is not a time above zero\");\n if (spec.console !== undefined && spec.console !== \"hidden\" && spec.console !== \"visible\")\n problems.push(`the console ${JSON.stringify(spec.console)} is not \"hidden\" or \"visible\"`);\n return problems;\n};\n\n/**\n * This function quotes one argument for a command line of Windows, by the rules of `CommandLineToArgvW`.\n * It doubles each backslash before a quote and at the end. One pass keeps the time linear.\n */\nexport const windowsArg = (arg: string): string => {\n if (arg !== \"\" && !/[\\s\"]/.test(arg)) return arg;\n let quoted = '\"';\n let slashes = 0;\n for (const char of arg) {\n if (char === \"\\\\\") {\n slashes += 1;\n continue;\n }\n quoted += char === '\"' ? `${\"\\\\\".repeat(slashes * 2 + 1)}\"` : `${\"\\\\\".repeat(slashes)}${char}`;\n slashes = 0;\n }\n return `${quoted}${\"\\\\\".repeat(slashes * 2)}\"`;\n};\n\n/**\n * This function quotes one argument for the `ExecStart` line of a systemd unit. It writes `%` as\n * `%%` and `$` as `$$`, thus systemd expands no specifier and no variable. An argument with a space,\n * a quote, a backslash or a `;` goes in double quotes.\n */\nexport const systemdArg = (arg: string): string => {\n const escaped = arg.replace(/%/g, () => \"%%\").replace(/\\$/g, () => \"$$\");\n if (escaped !== \"\" && !/[\\s\"'\\\\;]/.test(escaped)) return escaped;\n return `\"${escaped.replace(/\\\\/g, () => \"\\\\\\\\\").replace(/\"/g, () => '\\\\\"')}\"`;\n};\n\n/** This function gives a time as an ISO 8601 duration of Task Scheduler in whole seconds, for example `PT90S`. */\nconst isoSeconds = (time: Quantity): string => `PT${Math.max(1, Math.ceil(valueIn(time, \"s\")))}S`;\n\n/** This function gives the interval of the repeat trigger of a task: whole minutes, 1 minute or more. */\nconst repeatMinutes = (time: Quantity): number => Math.max(1, Math.ceil(valueIn(time, \"min\")));\n\n/** This function gives the seconds of a restart wait for systemd, a whole number. */\nconst restartSeconds = (time: Quantity): number => Math.max(0, Math.ceil(valueIn(time, \"s\")));\n\nconst refuse = (spec: ServiceSpec): void => {\n const problems = serviceProblems(spec);\n if (problems.length > 0) throw new Error(`the service spec has problems: ${problems.join(\"; \")}`);\n};\n\n/**\n * This function gives the task file of Windows for a spec, as text. It is a pure function: the same\n * spec and context give the same text. Each start boundary is in the past, thus the task does not wait for a date.\n * - A start at logon gets a logon trigger, and a start at boot gets a boot trigger. With a restart, a time trigger\n * also starts the task each few minutes. The task ignores a start while its program runs (`IgnoreNew`).\n * - A daily start gets a calendar trigger at its time. A start that the computer missed occurs when it can (`StartWhenAvailable`).\n * - A spec in the background gets an S4U logon: the task runs when the user is not logged on, and Windows keeps no password.\n * Otherwise the task runs only in the session of the user (`InteractiveToken`).\n * Task Scheduler reads the file as UTF-16 with a byte order mark: give the text to `utf16le`.\n */\nexport const renderTaskXml = (spec: ServiceSpec, context: TaskContext): string => {\n refuse(spec);\n const user = xmlText(context.user);\n const hidden = (spec.console ?? \"hidden\") === \"hidden\";\n const command = hidden ? context.conhost : spec.program;\n const args = (hidden ? [\"--headless\", spec.program, ...spec.args] : [...spec.args]).map(windowsArg).join(\" \");\n const triggers: string[] = [];\n if (runsUntilStop(spec.start)) {\n triggers.push(\n spec.start === \"logon\"\n ? ` <LogonTrigger>\n <Enabled>true</Enabled>\n <UserId>${user}</UserId>\n </LogonTrigger>`\n : ` <BootTrigger>\n <Enabled>true</Enabled>\n </BootTrigger>`,\n );\n if (spec.restart !== null)\n triggers.push(` <TimeTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T00:00:00</StartBoundary>\n <Repetition>\n <Interval>PT${repeatMinutes(spec.restart.after)}M</Interval>\n <StopAtDurationEnd>false</StopAtDurationEnd>\n </Repetition>\n </TimeTrigger>`);\n } else {\n const time = dailyTime(spec.start.daily)!;\n triggers.push(` <CalendarTrigger>\n <Enabled>true</Enabled>\n <StartBoundary>2000-01-01T${time.hour}:${time.minute}:00</StartBoundary>\n <ScheduleByDay>\n <DaysInterval>1</DaysInterval>\n </ScheduleByDay>\n </CalendarTrigger>`);\n }\n const cwd = spec.cwd === undefined ? \"\" : `\\n <WorkingDirectory>${xmlText(spec.cwd)}</WorkingDirectory>`;\n const limit = spec.timeLimit === undefined ? \"PT0S\" : isoSeconds(spec.timeLimit);\n return `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>${xmlText(spec.description)}</Description>\n <URI>\\\\${xmlText(spec.name)}</URI>\n </RegistrationInfo>\n <Triggers>\n${triggers.join(\"\\n\")}\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${user}</UserId>\n <LogonType>${inBackground(spec) ? \"S4U\" : \"InteractiveToken\"}</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>true</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>${limit}</ExecutionTimeLimit>\n <Priority>5</Priority>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${xmlText(windowsArg(command))}</Command>\n <Arguments>${xmlText(args)}</Arguments>${cwd}\n </Exec>\n </Actions>\n</Task>\n`;\n};\n\n/** This function encodes a text as UTF-16, little-endian, with a byte order mark: the encoding that Task Scheduler reads. */\nexport const utf16le = (text: string): Uint8Array => {\n const bytes = new Uint8Array(2 + text.length * 2);\n bytes[0] = 0xff;\n bytes[1] = 0xfe;\n for (let at = 0; at < text.length; at += 1) {\n const unit = text.charCodeAt(at);\n bytes[2 + at * 2] = unit & 0xff;\n bytes[3 + at * 2] = unit >> 8;\n }\n return bytes;\n};\n\n/**\n * This function gives the systemd user unit of a spec (`<name>.service`), as text. It is a pure function.\n * - 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`.\n * The unit is the same for the two starts: the linger of the user (`installService`) starts the user manager at boot.\n * - A daily start is a service of the type `oneshot` with no `[Install]` section. Its timer (`renderSystemdTimer`) starts it.\n */\nexport const renderSystemdUnit = (spec: ServiceSpec): string => {\n refuse(spec);\n const lines = [\"[Unit]\", `Description=${spec.description.replace(/%/g, \"%%\")}`, \"\", \"[Service]\"];\n lines.push(runsUntilStop(spec.start) ? \"Type=simple\" : \"Type=oneshot\");\n lines.push(`ExecStart=${[spec.program, ...spec.args].map(systemdArg).join(\" \")}`);\n if (spec.cwd !== undefined) lines.push(`WorkingDirectory=${spec.cwd.replace(/%/g, \"%%\")}`);\n if (spec.restart !== null) lines.push(\"Restart=on-failure\", `RestartSec=${restartSeconds(spec.restart.after)}`);\n if (spec.timeLimit !== undefined) lines.push(`RuntimeMaxSec=${Math.max(1, Math.ceil(valueIn(spec.timeLimit, \"s\")))}`);\n if (runsUntilStop(spec.start)) lines.push(\"\", \"[Install]\", \"WantedBy=default.target\");\n return `${lines.join(\"\\n\")}\\n`;\n};\n\n/** 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. */\nexport const renderSystemdTimer = (spec: ServiceSpec): string | null => {\n refuse(spec);\n if (runsUntilStop(spec.start)) return null;\n const time = dailyTime(spec.start.daily)!;\n return `${[\n \"[Unit]\",\n `Description=${spec.description.replace(/%/g, \"%%\")}`,\n \"\",\n \"[Timer]\",\n `OnCalendar=*-*-* ${time.hour}:${time.minute}:00`,\n \"Persistent=true\",\n \"\",\n \"[Install]\",\n \"WantedBy=timers.target\",\n ].join(\"\\n\")}\\n`;\n};\n"],"mappings":";;;AAsDA,MAAM,OAAO;AACb,MAAM,QAAQ;;AAEd,MAAM,cAAc,SAA0B;CAC5C,KAAK,IAAI,KAAK,GAAG,KAAK,KAAK,QAAQ,MAAM,GAAG;EAC1C,MAAM,OAAO,KAAK,WAAW,EAAE;EAC/B,IAAI,OAAO,MAAQ,SAAS,KAAM,OAAO;CAC3C;CACA,OAAO;AACT;;AAGA,MAAa,aAAa,SAA4E;CACpG,MAAM,QAAQ,MAAM,KAAK,IAAI;CAC7B,OAAO,UAAU,OAAO,OAAO;EAAE,MAAM,MAAM;EAAK,QAAQ,MAAM;CAAI;AACtE;;AAGA,MAAa,iBAAiB,UAAmD,UAAU,WAAW,UAAU;;AAGhH,MAAa,gBAAgB,SAA+B,KAAK,cAAc,KAAK,UAAU;;AAG9F,MAAa,UAAU,UAAsC,WAAW,KAAK,KAAK,YAAY,MAAM,MAAM,IAAI;;AAG9G,MAAa,mBAAmB,SAAgC;CAC9D,MAAM,WAAqB,CAAC;CAC5B,IAAI,CAAC,KAAK,KAAK,KAAK,IAAI,GAAG,SAAS,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI,EAAE,0CAA0C;CACzH,MAAM,SAAkC;EACtC,CAAC,eAAe,KAAK,WAAW;EAChC,CAAC,WAAW,KAAK,OAAO;EACxB,CAAC,YAAY,KAAK,QAAQ;EAC1B,GAAG,KAAK,KAAK,KAAK,KAAK,OAAyB,CAAC,YAAY,MAAM,GAAG,CAAC;EACvE,GAAI,KAAK,QAAQ,KAAA,IAAY,CAAC,IAAI,CAAC,CAAC,OAAO,KAAK,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AK,YAAY,QAAQ,MAAM,IAAI;EAAK;EAAI;CAAW;CAC/F,MAAM,KAAK,cAAc,KAAK,KAAK,IAAI,gBAAgB,cAAc;CACrE,MAAM,KAAK,aAAa,CAAC,KAAK,SAAS,GAAG,KAAK,IAAI,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,GAAG;CAChF,IAAI,KAAK,QAAQ,KAAA,GAAW,MAAM,KAAK,oBAAoB,KAAK,IAAI,QAAQ,MAAM,IAAI,GAAG;CACzF,IAAI,KAAK,YAAY,MAAM,MAAM,KAAK,sBAAsB,cAAc,eAAe,KAAK,QAAQ,KAAK,GAAG;CAC9G,IAAI,KAAK,cAAc,KAAA,GAAW,MAAM,KAAK,iBAAiB,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,KAAK,WAAW,GAAG,CAAC,CAAC,GAAG;CACpH,IAAI,cAAc,KAAK,KAAK,GAAG,MAAM,KAAK,IAAI,aAAa,yBAAyB;CACpF,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC7B;;AAGA,MAAa,sBAAsB,SAAqC;CACtE,OAAO,IAAI;CACX,IAAI,cAAc,KAAK,KAAK,GAAG,OAAO;CACtC,MAAM,OAAO,UAAU,KAAK,MAAM,KAAK;CACvC,OAAO,GAAG;EACR;EACA,eAAe,KAAK,YAAY,QAAQ,MAAM,IAAI;EAClD;EACA;EACA,oBAAoB,KAAK,KAAK,GAAG,KAAK,OAAO;EAC7C;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI,EAAE;AACf"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { HostPorts } from "./ports.js";
|
|
2
|
+
import { ProbeResult, ReadyProbe } from "./probes.js";
|
|
3
|
+
import { Quantity } from "@mark1russell7/quantity";
|
|
4
|
+
/**
|
|
5
|
+
* A verdict tells when a target goes down and when it comes up again.
|
|
6
|
+
* - `debounce`: `failAfter` failed polls in sequence make it down, and `recoverAfter` passed polls in sequence make it up.
|
|
7
|
+
* - `window`: failures for the time `failAfter` make it down. Passes for the time `recoverAfter` make it up. Without
|
|
8
|
+
* `recoverAfter`, the first pass makes it up.
|
|
9
|
+
*/
|
|
10
|
+
export type TargetVerdict = {
|
|
11
|
+
readonly type: "debounce";
|
|
12
|
+
readonly failAfter: number;
|
|
13
|
+
readonly recoverAfter: number;
|
|
14
|
+
} | {
|
|
15
|
+
readonly type: "window";
|
|
16
|
+
readonly failAfter: Quantity;
|
|
17
|
+
readonly recoverAfter?: Quantity | undefined;
|
|
18
|
+
};
|
|
19
|
+
/** A watch target is one thing that a watcher probes on its own loop. */
|
|
20
|
+
export interface WatchTarget {
|
|
21
|
+
/** This name is unique in the spec. A change names its target with it. */
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly probe: ReadyProbe;
|
|
24
|
+
/** This time is between the starts of two polls. */
|
|
25
|
+
readonly interval: Quantity;
|
|
26
|
+
/** This time is the most that one poll waits. It is not above the interval. */
|
|
27
|
+
readonly timeout: Quantity;
|
|
28
|
+
/** This fraction moves each interval by up to ± its part, thus two watchers do not poll in step. The default is 0.1. */
|
|
29
|
+
readonly jitter?: number | undefined;
|
|
30
|
+
/** The default is a debounce: 3 failures make it down, and 2 passes make it up. */
|
|
31
|
+
readonly verdict?: TargetVerdict | undefined;
|
|
32
|
+
}
|
|
33
|
+
/** A watch spec lists the targets of one watcher. */
|
|
34
|
+
export interface WatchSpec {
|
|
35
|
+
readonly targets: readonly WatchTarget[];
|
|
36
|
+
}
|
|
37
|
+
/** The health of a target is `unknown` until its first verdict. */
|
|
38
|
+
export type TargetHealth = "unknown" | "up" | "down";
|
|
39
|
+
/** A target change is one transition of the health of a target. */
|
|
40
|
+
export interface TargetChange {
|
|
41
|
+
readonly target: string;
|
|
42
|
+
readonly from: TargetHealth;
|
|
43
|
+
readonly to: "up" | "down";
|
|
44
|
+
/** This time is the wall time of the change, in milliseconds after the epoch. */
|
|
45
|
+
readonly at: number;
|
|
46
|
+
/** This text tells why the latest poll failed, for a change to down. It is null for a change to up. */
|
|
47
|
+
readonly why: string | null;
|
|
48
|
+
}
|
|
49
|
+
/** A target state is what a watcher knows of one target at this time. */
|
|
50
|
+
export interface TargetState {
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly health: TargetHealth;
|
|
53
|
+
/** This time is the wall time of the latest change of the health, or of the start. */
|
|
54
|
+
readonly since: number;
|
|
55
|
+
/** This result is the latest poll, or null before the first poll. */
|
|
56
|
+
readonly last: ProbeResult | null;
|
|
57
|
+
/** This time is the wall time of the latest poll, or null. */
|
|
58
|
+
readonly lastAt: number | null;
|
|
59
|
+
/** This count is the failed polls in sequence. */
|
|
60
|
+
readonly failures: number;
|
|
61
|
+
}
|
|
62
|
+
export interface WatchOptions {
|
|
63
|
+
/** This function gets each change of the health of a target. A throw in it does not stop the watcher. */
|
|
64
|
+
readonly onChange: (change: TargetChange) => void;
|
|
65
|
+
/** This function gives a number in [0, 1) for the jitter. The default is `Math.random`. */
|
|
66
|
+
readonly random?: (() => number) | undefined;
|
|
67
|
+
/** This function gets each transition of the poller and the latch of each target, with the name of the target. */
|
|
68
|
+
readonly trace?: ((target: string, from: string, to: string, on: string) => void) | undefined;
|
|
69
|
+
}
|
|
70
|
+
/** A target watch is a running watcher. */
|
|
71
|
+
export interface TargetWatch {
|
|
72
|
+
/** This method gives the state of each target, in the sequence of the spec. */
|
|
73
|
+
states(): TargetState[];
|
|
74
|
+
/** This method polls each target one time at once, outside its loop, and gives the states after the polls. */
|
|
75
|
+
pollNow(): Promise<TargetState[]>;
|
|
76
|
+
/** This method stops each loop. A stopped watcher gives no change. */
|
|
77
|
+
stop(): void;
|
|
78
|
+
}
|
|
79
|
+
/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */
|
|
80
|
+
export declare const DEFAULT_VERDICT: TargetVerdict;
|
|
81
|
+
/** This function gives the problems of a watch spec: each value that the watcher cannot use. */
|
|
82
|
+
export declare const watchProblems: (spec: WatchSpec) => string[];
|
|
83
|
+
/**
|
|
84
|
+
* This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the
|
|
85
|
+
* clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a
|
|
86
|
+
* window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change
|
|
87
|
+
* goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a
|
|
88
|
+
* problem.
|
|
89
|
+
*/
|
|
90
|
+
export declare const watchTargets: (spec: WatchSpec, ports: HostPorts, options: WatchOptions) => TargetWatch;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { latch } from "../latch.js";
|
|
2
|
+
import { poller } from "../poller.js";
|
|
3
|
+
import { probeOnce, probeProblems } from "./probes.js";
|
|
4
|
+
import { isTime } from "./render.js";
|
|
5
|
+
import { valueIn } from "@mark1russell7/quantity";
|
|
6
|
+
// src/host/watch.ts
|
|
7
|
+
/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */
|
|
8
|
+
const DEFAULT_VERDICT = {
|
|
9
|
+
type: "debounce",
|
|
10
|
+
failAfter: 3,
|
|
11
|
+
recoverAfter: 2
|
|
12
|
+
};
|
|
13
|
+
const DEFAULT_JITTER = .1;
|
|
14
|
+
const ms = (amount) => valueIn(amount, "ms");
|
|
15
|
+
const isTimeAtLeast = (value, floor, strict) => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);
|
|
16
|
+
const whole = (value) => Number.isInteger(value) && value >= 1;
|
|
17
|
+
/** This function gives the problems of a watch spec: each value that the watcher cannot use. */
|
|
18
|
+
const watchProblems = (spec) => {
|
|
19
|
+
const problems = [];
|
|
20
|
+
if (spec.targets.length === 0) problems.push("the spec has no target");
|
|
21
|
+
const names = /* @__PURE__ */ new Set();
|
|
22
|
+
for (const target of spec.targets) {
|
|
23
|
+
const of = `the target ${JSON.stringify(target.name)}`;
|
|
24
|
+
if (target.name === "") problems.push("a target name is empty");
|
|
25
|
+
if (names.has(target.name)) problems.push(`${of} is in the spec two times`);
|
|
26
|
+
names.add(target.name);
|
|
27
|
+
problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));
|
|
28
|
+
if (!isTimeAtLeast(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);
|
|
29
|
+
if (!isTimeAtLeast(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);
|
|
30
|
+
else if (isTimeAtLeast(target.interval, 0, true) && ms(target.timeout) > ms(target.interval)) problems.push(`${of}: the timeout is above the interval`);
|
|
31
|
+
const jitter = target.jitter ?? DEFAULT_JITTER;
|
|
32
|
+
if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);
|
|
33
|
+
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
34
|
+
if (verdict.type === "debounce") {
|
|
35
|
+
if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);
|
|
36
|
+
if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);
|
|
37
|
+
} else if (verdict.type === "window") {
|
|
38
|
+
if (!isTimeAtLeast(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);
|
|
39
|
+
if (verdict.recoverAfter !== void 0 && !isTimeAtLeast(verdict.recoverAfter, 0, false)) problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);
|
|
40
|
+
} else problems.push(`${of}: the verdict type ${JSON.stringify(verdict.type)} is not debounce or window`);
|
|
41
|
+
}
|
|
42
|
+
return problems;
|
|
43
|
+
};
|
|
44
|
+
const timingOf = (target) => {
|
|
45
|
+
const verdict = target.verdict ?? DEFAULT_VERDICT;
|
|
46
|
+
return verdict.type === "debounce" ? {
|
|
47
|
+
type: "debounce",
|
|
48
|
+
interval: target.interval,
|
|
49
|
+
failAfter: verdict.failAfter,
|
|
50
|
+
recoverAfter: verdict.recoverAfter
|
|
51
|
+
} : {
|
|
52
|
+
type: "window",
|
|
53
|
+
failAfter: verdict.failAfter,
|
|
54
|
+
recoverAfter: verdict.recoverAfter
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the
|
|
59
|
+
* clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a
|
|
60
|
+
* window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change
|
|
61
|
+
* goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a
|
|
62
|
+
* problem.
|
|
63
|
+
*/
|
|
64
|
+
const watchTargets = (spec, ports, options) => {
|
|
65
|
+
const problems = watchProblems(spec);
|
|
66
|
+
if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join("; ")}`);
|
|
67
|
+
const random = options.random ?? Math.random;
|
|
68
|
+
let stopped = false;
|
|
69
|
+
const emit = (unit, to) => {
|
|
70
|
+
if (unit.health === to) return;
|
|
71
|
+
const change = {
|
|
72
|
+
target: unit.target.name,
|
|
73
|
+
from: unit.health,
|
|
74
|
+
to,
|
|
75
|
+
at: ports.wall(),
|
|
76
|
+
why: to === "down" ? unit.why : null
|
|
77
|
+
};
|
|
78
|
+
unit.health = to;
|
|
79
|
+
unit.since = change.at;
|
|
80
|
+
if (stopped) return;
|
|
81
|
+
try {
|
|
82
|
+
options.onChange(change);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
ports.logger?.log("warn", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const watched = spec.targets.map((target) => {
|
|
88
|
+
const unit = {
|
|
89
|
+
target,
|
|
90
|
+
health: "unknown",
|
|
91
|
+
since: ports.wall(),
|
|
92
|
+
last: null,
|
|
93
|
+
lastAt: null,
|
|
94
|
+
failures: 0,
|
|
95
|
+
why: null
|
|
96
|
+
};
|
|
97
|
+
const trace = options.trace === void 0 ? void 0 : (from, to, on) => options.trace?.(target.name, from, to, on);
|
|
98
|
+
const timeout = ms(target.timeout);
|
|
99
|
+
let probed = null;
|
|
100
|
+
const gate = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? "down" : "up"), trace);
|
|
101
|
+
const record = (result) => {
|
|
102
|
+
const own = probed;
|
|
103
|
+
probed = null;
|
|
104
|
+
const seen = result.outcome === "ok" ? { ok: true } : {
|
|
105
|
+
ok: false,
|
|
106
|
+
why: !result.timedOut && own !== null && !own.ok ? own.why : result.cause ?? "the poll failed"
|
|
107
|
+
};
|
|
108
|
+
unit.last = seen;
|
|
109
|
+
unit.lastAt = ports.wall();
|
|
110
|
+
unit.failures = seen.ok ? 0 : unit.failures + 1;
|
|
111
|
+
if (!seen.ok) unit.why = seen.why;
|
|
112
|
+
gate.record(result);
|
|
113
|
+
if (seen.ok && unit.health === "unknown" && !gate.tripped) emit(unit, "up");
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
unit,
|
|
117
|
+
gate,
|
|
118
|
+
loop: poller({
|
|
119
|
+
name: target.name,
|
|
120
|
+
poll: {
|
|
121
|
+
interval: target.interval,
|
|
122
|
+
jitter: target.jitter ?? DEFAULT_JITTER,
|
|
123
|
+
timeout: target.timeout
|
|
124
|
+
},
|
|
125
|
+
run: async () => {
|
|
126
|
+
const result = await probeOnce(target.probe, timeout, ports);
|
|
127
|
+
probed = result;
|
|
128
|
+
return result.ok ? "ok" : "error";
|
|
129
|
+
},
|
|
130
|
+
clock: ports.clock,
|
|
131
|
+
random,
|
|
132
|
+
forced: () => false,
|
|
133
|
+
record,
|
|
134
|
+
trace
|
|
135
|
+
})
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
const states = () => watched.map(({ unit }) => ({
|
|
139
|
+
name: unit.target.name,
|
|
140
|
+
health: unit.health,
|
|
141
|
+
since: unit.since,
|
|
142
|
+
last: unit.last,
|
|
143
|
+
lastAt: unit.lastAt,
|
|
144
|
+
failures: unit.failures
|
|
145
|
+
}));
|
|
146
|
+
for (const { loop } of watched) loop.start(0);
|
|
147
|
+
return {
|
|
148
|
+
states,
|
|
149
|
+
async pollNow() {
|
|
150
|
+
await Promise.all(watched.map(({ loop }) => loop.pollNow()));
|
|
151
|
+
return states();
|
|
152
|
+
},
|
|
153
|
+
stop() {
|
|
154
|
+
if (stopped) return;
|
|
155
|
+
stopped = true;
|
|
156
|
+
for (const { gate, loop } of watched) {
|
|
157
|
+
loop.stop();
|
|
158
|
+
gate.stop();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
export { DEFAULT_VERDICT, watchProblems, watchTargets };
|
|
164
|
+
|
|
165
|
+
//# sourceMappingURL=watch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watch.js","names":[],"sources":["../../src/host/watch.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Latch, Result, Trace } from \"../latch.ts\";\nimport { latch } from \"../latch.ts\";\nimport type { Poller } from \"../poller.ts\";\nimport { poller } from \"../poller.ts\";\nimport type { Timing } from \"../timing.ts\";\nimport type { HostPorts } from \"./ports.ts\";\nimport type { ProbeResult, ReadyProbe } from \"./probes.ts\";\nimport { probeOnce, probeProblems } from \"./probes.ts\";\nimport { isTime } from \"./render.ts\";\n\n/**\n * A verdict tells when a target goes down and when it comes up again.\n * - `debounce`: `failAfter` failed polls in sequence make it down, and `recoverAfter` passed polls in sequence make it up.\n * - `window`: failures for the time `failAfter` make it down. Passes for the time `recoverAfter` make it up. Without\n * `recoverAfter`, the first pass makes it up.\n */\nexport type TargetVerdict =\n | { readonly type: \"debounce\"; readonly failAfter: number; readonly recoverAfter: number }\n | { readonly type: \"window\"; readonly failAfter: Quantity; readonly recoverAfter?: Quantity | undefined };\n\n/** A watch target is one thing that a watcher probes on its own loop. */\nexport interface WatchTarget {\n /** This name is unique in the spec. A change names its target with it. */\n readonly name: string;\n readonly probe: ReadyProbe;\n /** This time is between the starts of two polls. */\n readonly interval: Quantity;\n /** This time is the most that one poll waits. It is not above the interval. */\n readonly timeout: Quantity;\n /** This fraction moves each interval by up to ± its part, thus two watchers do not poll in step. The default is 0.1. */\n readonly jitter?: number | undefined;\n /** The default is a debounce: 3 failures make it down, and 2 passes make it up. */\n readonly verdict?: TargetVerdict | undefined;\n}\n\n/** A watch spec lists the targets of one watcher. */\nexport interface WatchSpec {\n readonly targets: readonly WatchTarget[];\n}\n\n/** The health of a target is `unknown` until its first verdict. */\nexport type TargetHealth = \"unknown\" | \"up\" | \"down\";\n\n/** A target change is one transition of the health of a target. */\nexport interface TargetChange {\n readonly target: string;\n readonly from: TargetHealth;\n readonly to: \"up\" | \"down\";\n /** This time is the wall time of the change, in milliseconds after the epoch. */\n readonly at: number;\n /** This text tells why the latest poll failed, for a change to down. It is null for a change to up. */\n readonly why: string | null;\n}\n\n/** A target state is what a watcher knows of one target at this time. */\nexport interface TargetState {\n readonly name: string;\n readonly health: TargetHealth;\n /** This time is the wall time of the latest change of the health, or of the start. */\n readonly since: number;\n /** This result is the latest poll, or null before the first poll. */\n readonly last: ProbeResult | null;\n /** This time is the wall time of the latest poll, or null. */\n readonly lastAt: number | null;\n /** This count is the failed polls in sequence. */\n readonly failures: number;\n}\n\nexport interface WatchOptions {\n /** This function gets each change of the health of a target. A throw in it does not stop the watcher. */\n readonly onChange: (change: TargetChange) => void;\n /** This function gives a number in [0, 1) for the jitter. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /** This function gets each transition of the poller and the latch of each target, with the name of the target. */\n readonly trace?: ((target: string, from: string, to: string, on: string) => void) | undefined;\n}\n\n/** A target watch is a running watcher. */\nexport interface TargetWatch {\n /** This method gives the state of each target, in the sequence of the spec. */\n states(): TargetState[];\n /** This method polls each target one time at once, outside its loop, and gives the states after the polls. */\n pollNow(): Promise<TargetState[]>;\n /** This method stops each loop. A stopped watcher gives no change. */\n stop(): void;\n}\n\n/** This verdict is the default: 3 failures in sequence make a target down, and 2 passes make it up. */\nexport const DEFAULT_VERDICT: TargetVerdict = { type: \"debounce\", failAfter: 3, recoverAfter: 2 };\nconst DEFAULT_JITTER = 0.1;\n\nconst ms = (amount: Quantity): number => valueIn(amount, \"ms\");\nconst isTimeAtLeast = (value: unknown, floor: number, strict: boolean): boolean => isTime(value) && (strict ? ms(value) > floor : ms(value) >= floor);\nconst whole = (value: number): boolean => Number.isInteger(value) && value >= 1;\n\n/** This function gives the problems of a watch spec: each value that the watcher cannot use. */\nexport const watchProblems = (spec: WatchSpec): string[] => {\n const problems: string[] = [];\n if (spec.targets.length === 0) problems.push(\"the spec has no target\");\n const names = new Set<string>();\n for (const target of spec.targets) {\n const of = `the target ${JSON.stringify(target.name)}`;\n if (target.name === \"\") problems.push(\"a target name is empty\");\n if (names.has(target.name)) problems.push(`${of} is in the spec two times`);\n names.add(target.name);\n problems.push(...probeProblems(target.probe).map((problem) => `${of}: ${problem}`));\n if (!isTimeAtLeast(target.interval, 0, true)) problems.push(`${of}: the interval is not a time above zero`);\n if (!isTimeAtLeast(target.timeout, 0, true)) problems.push(`${of}: the timeout is not a time above zero`);\n else if (isTimeAtLeast(target.interval, 0, true) && ms(target.timeout) > ms(target.interval)) problems.push(`${of}: the timeout is above the interval`);\n const jitter = target.jitter ?? DEFAULT_JITTER;\n if (!(Number.isFinite(jitter) && jitter >= 0 && jitter < 1)) problems.push(`${of}: the jitter ${jitter} is not a fraction from 0 to below 1`);\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n if (verdict.type === \"debounce\") {\n if (!whole(verdict.failAfter)) problems.push(`${of}: the verdict fails after ${verdict.failAfter} polls, not a whole number above zero`);\n if (!whole(verdict.recoverAfter)) problems.push(`${of}: the verdict recovers after ${verdict.recoverAfter} polls, not a whole number above zero`);\n } else if (verdict.type === \"window\") {\n if (!isTimeAtLeast(verdict.failAfter, 0, false)) problems.push(`${of}: the failAfter of the window is not a time of zero or more`);\n if (verdict.recoverAfter !== undefined && !isTimeAtLeast(verdict.recoverAfter, 0, false))\n problems.push(`${of}: the recoverAfter of the window is not a time of zero or more`);\n } else problems.push(`${of}: the verdict type ${JSON.stringify((verdict as { type: unknown }).type)} is not debounce or window`);\n }\n return problems;\n};\n\nconst timingOf = (target: WatchTarget): Timing => {\n const verdict = target.verdict ?? DEFAULT_VERDICT;\n return verdict.type === \"debounce\"\n ? { type: \"debounce\", interval: target.interval, failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter }\n : { type: \"window\", failAfter: verdict.failAfter, recoverAfter: verdict.recoverAfter };\n};\n\ninterface Unit {\n readonly target: WatchTarget;\n health: TargetHealth;\n since: number;\n last: ProbeResult | null;\n lastAt: number | null;\n failures: number;\n /** This text is the reason of the latest failed poll. */\n why: string | null;\n}\n\n/**\n * This function starts a watcher of targets: an outside prober. Each target has its own loop of polls, on the\n * clock of the ports, with a jitter. A verdict turns the polls into the health of the target: a debounce or a\n * window. A target is `unknown` at the start. Its first pass makes it up, and its verdict makes it down. Each change\n * goes to `onChange`, with the reason of the latest failed poll. The watcher throws at the start when the spec has a\n * problem.\n */\nexport const watchTargets = (spec: WatchSpec, ports: HostPorts, options: WatchOptions): TargetWatch => {\n const problems = watchProblems(spec);\n if (problems.length > 0) throw new Error(`the watch spec has problems: ${problems.join(\"; \")}`);\n const random = options.random ?? Math.random;\n let stopped = false;\n\n const emit = (unit: Unit, to: \"up\" | \"down\"): void => {\n if (unit.health === to) return;\n const change: TargetChange = { target: unit.target.name, from: unit.health, to, at: ports.wall(), why: to === \"down\" ? unit.why : null };\n unit.health = to;\n unit.since = change.at;\n if (stopped) return;\n try {\n options.onChange(change);\n } catch (error) {\n ports.logger?.log(\"warn\", `the change handler of the watch failed: ${error instanceof Error ? error.message : String(error)}`, { target: change.target });\n }\n };\n\n const watched = spec.targets.map((target): { readonly unit: Unit; readonly gate: Latch; readonly loop: Poller } => {\n const unit: Unit = { target, health: \"unknown\", since: ports.wall(), last: null, lastAt: null, failures: 0, why: null };\n const trace: Trace | undefined = options.trace === undefined ? undefined : (from, to, on) => options.trace?.(target.name, from, to, on);\n const timeout = ms(target.timeout);\n // the result of the latest probe: a poller result tells only the outcome\n let probed: ProbeResult | null = null;\n const gate: Latch = latch(timingOf(target), ports.clock, false, () => emit(unit, gate.tripped ? \"down\" : \"up\"), trace);\n const record = (result: Result): void => {\n const own = probed;\n probed = null;\n // a timeout or a pending call has the cause of the poller: the probe gave no result for this poll\n const seen: ProbeResult =\n result.outcome === \"ok\" ? { ok: true } : { ok: false, why: !result.timedOut && own !== null && !own.ok ? own.why : (result.cause ?? \"the poll failed\") };\n unit.last = seen;\n unit.lastAt = ports.wall();\n unit.failures = seen.ok ? 0 : unit.failures + 1;\n if (!seen.ok) unit.why = seen.why;\n gate.record(result);\n if (seen.ok && unit.health === \"unknown\" && !gate.tripped) emit(unit, \"up\");\n };\n const loop = poller({\n name: target.name,\n poll: { interval: target.interval, jitter: target.jitter ?? DEFAULT_JITTER, timeout: target.timeout },\n run: async () => {\n const result = await probeOnce(target.probe, timeout, ports);\n probed = result;\n return result.ok ? \"ok\" : \"error\";\n },\n clock: ports.clock,\n random,\n forced: () => false,\n record,\n trace,\n });\n return { unit, gate, loop };\n });\n\n const states = (): TargetState[] =>\n watched.map(({ unit }) => ({ name: unit.target.name, health: unit.health, since: unit.since, last: unit.last, lastAt: unit.lastAt, failures: unit.failures }));\n\n for (const { loop } of watched) loop.start(0);\n\n return {\n states,\n async pollNow() {\n await Promise.all(watched.map(({ loop }) => loop.pollNow()));\n return states();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const { gate, loop } of watched) {\n loop.stop();\n gate.stop();\n }\n },\n };\n};\n"],"mappings":";;;;;;;AA0FA,MAAa,kBAAiC;CAAE,MAAM;CAAY,WAAW;CAAG,cAAc;AAAE;AAChG,MAAM,iBAAiB;AAEvB,MAAM,MAAM,WAA6B,QAAQ,QAAQ,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