@intellectual-frontiers/system 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/compile.d.ts +94 -0
- package/dist/compile.js +130 -0
- package/dist/dirs.d.ts +19 -0
- package/dist/dirs.js +64 -0
- package/dist/discover.d.ts +43 -0
- package/dist/discover.js +118 -0
- package/dist/errors.d.ts +130 -0
- package/dist/errors.js +189 -0
- package/dist/fs.d.ts +263 -0
- package/dist/fs.js +826 -0
- package/dist/git.d.ts +63 -0
- package/dist/git.js +144 -0
- package/dist/job-plan.d.ts +207 -0
- package/dist/job-plan.js +563 -0
- package/dist/lock.d.ts +41 -0
- package/dist/lock.js +130 -0
- package/dist/mod.d.ts +28 -0
- package/dist/mod.js +29 -0
- package/dist/path.d.ts +47 -0
- package/dist/path.js +55 -0
- package/dist/proc.d.ts +257 -0
- package/dist/proc.js +589 -0
- package/dist/schedule.d.ts +99 -0
- package/dist/schedule.js +131 -0
- package/dist/stdio.d.ts +31 -0
- package/dist/stdio.js +170 -0
- package/dist/tty.d.ts +34 -0
- package/dist/tty.js +71 -0
- package/dist/watch.d.ts +42 -0
- package/dist/watch.js +342 -0
- package/package.json +113 -4
- package/src/compile.ts +178 -0
- package/src/dirs.ts +87 -0
- package/src/discover.ts +144 -0
- package/src/errors.ts +176 -0
- package/src/fs.ts +967 -0
- package/src/git.ts +163 -0
- package/src/job-plan.ts +660 -0
- package/src/lock.ts +149 -0
- package/src/mod.ts +29 -0
- package/src/path.ts +59 -0
- package/src/proc.ts +786 -0
- package/src/schedule.ts +173 -0
- package/src/stdio.ts +204 -0
- package/src/tty.ts +94 -0
- package/src/watch.ts +338 -0
package/dist/job-plan.js
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
// Spec: 0001-system FR-017
|
|
2
|
+
/**
|
|
3
|
+
* The operating system's own scheduled job, planned without touching it (commons 0005-typescript-runtime FR-046): from a job's name, the
|
|
4
|
+
* argument vector it runs, its working folder, its environment and when it runs, `planJob` gives the files to write and the commands that
|
|
5
|
+
* load and unload the job, for one of three schedulers, and writes or runs nothing itself (`runtime/schedule.ts` does).
|
|
6
|
+
*
|
|
7
|
+
* | OS | what is planned | loaded by |
|
|
8
|
+
* | ------- | ---------------------------------------------------------------------------- | ------------------------------------------------ |
|
|
9
|
+
* | Linux | a systemd user service (one shot) and its timer in `~/.config/systemd/user/` | `systemctl --user enable --now <label>.timer` |
|
|
10
|
+
* | macOS | a LaunchAgent, `~/Library/LaunchAgents/<label>.plist` | `launchctl bootstrap gui/<uid> <plist>` |
|
|
11
|
+
* | Windows | a `.cmd` file in `~\AppData\Local\<folder>\` and a Task Scheduler task | `schtasks /Create /F /TN <folder>\<name> /TR ...` |
|
|
12
|
+
*
|
|
13
|
+
* The caller names its jobs with an owner: a reverse-DNS `domain` (`org.example.backup`), which makes the launchd label and the systemd
|
|
14
|
+
* unit `<domain>.<name>`, and a Task Scheduler `folder` (`Example`), which makes the task `<folder>\<name>` and the folder of its `.cmd`
|
|
15
|
+
* file. Paths in `files` are relative to the user's home folder, with `/` between their parts, so the caller writes them on any host; the
|
|
16
|
+
* absolute paths the commands need (the plist for `launchctl`, the `.cmd` file for `schtasks`) are built from the given home folder with
|
|
17
|
+
* the target's own separator.
|
|
18
|
+
*
|
|
19
|
+
* When a job runs is one of five kinds, each expressed on every scheduler at the same minutes of local time:
|
|
20
|
+
*
|
|
21
|
+
* | kind | systemd `OnCalendar=` | launchd `StartCalendarInterval` | `schtasks` |
|
|
22
|
+
* | --------- | ---------------------- | ---------------------------------------- | ------------------------------------ |
|
|
23
|
+
* | `minutes` | `*-*-* *:00/N:00` | one `Minute` dict for each of 0, N, 2N.. | `/SC MINUTE /MO N /ST 00:00` |
|
|
24
|
+
* | `hourly` | `*-*-* *:MM:00` | `Minute` | `/SC HOURLY /ST 00:MM` |
|
|
25
|
+
* | `daily` | `*-*-* HH:MM:00` | `Hour`, `Minute` | `/SC DAILY /ST HH:MM` |
|
|
26
|
+
* | `weekly` | `Fri *-*-* HH:MM:00` | `Weekday` (0 is Sunday), `Hour`, `Minute` | `/SC WEEKLY /D FRI /ST HH:MM` |
|
|
27
|
+
* | `monthly` | `*-*-DD HH:MM:00` | `Day`, `Hour`, `Minute` | `/SC MONTHLY /D DD /ST HH:MM` |
|
|
28
|
+
*
|
|
29
|
+
* `minutes` takes a divisor of 60 below 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30), so that all three run at the same minutes of every
|
|
30
|
+
* hour; `monthly` takes a day from 1 to 28, which every month has.
|
|
31
|
+
*
|
|
32
|
+
* Every argument is quoted for the file that carries it, and what cannot be carried safely is refused with a `ScheduleError`, never
|
|
33
|
+
* altered. systemd's `ExecStart=` and `Environment=` get double quotes with C escapes (`\\`, `\"`, `\t`, `\xHH`), `%%` for `%` and, in
|
|
34
|
+
* `ExecStart=`, `$$` for `$`; a carriage return, a line feed or NUL is refused, and so is an argument that is only `;` and a program that
|
|
35
|
+
* begins with one of systemd's prefixes (`@-:+!|`). The `.cmd` file gets double quotes around any argument that is not plain, `%%` for `%`
|
|
36
|
+
* (a batch file's own escape, inside quotes or not), the trailing backslashes of a quoted argument doubled (the C runtime's rule), delayed
|
|
37
|
+
* expansion turned off (so `!` is plain) and the UTF-8 code page; a double quote (cmd.exe's quoting cannot hold one safely) and any
|
|
38
|
+
* control character but tab are refused. The plist is written with the kernel's XML writer, which escapes the markup; a character XML
|
|
39
|
+
* cannot carry (a control character but tab and line feed, a carriage return, which XML reads as a line feed, or a lone surrogate) is
|
|
40
|
+
* refused.
|
|
41
|
+
*
|
|
42
|
+
* Taken from Stolos's `src/archon/export/schedule.ts` (spec 092), which built the jobs of `stolos export schedule` from an export job and
|
|
43
|
+
* a fleet. What changed: the job is generic (an argument vector, a working folder, an environment, an optional log) and named by the
|
|
44
|
+
* caller's owner instead of Stolos's; the schedule is a discriminated union, with every N minutes added; the files are relative to the
|
|
45
|
+
* home folder; the plist is built as an XML tree; quoting follows each format's rules in full and refuses what it cannot hold, where Stolos
|
|
46
|
+
* quoted a few characters; and errors are values.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* import { jobName, planJob, schedule } from "./job-plan.ts";
|
|
51
|
+
* const name = jobName("backup");
|
|
52
|
+
* const when = schedule({ kind: "daily", hour: 6, minute: 10 });
|
|
53
|
+
* if (name.kind === "ok" && when.kind === "ok") {
|
|
54
|
+
* const plan = planJob(
|
|
55
|
+
* { name: name.value, owner: { domain: "org.example", folder: "Example" }, argv: ["/usr/bin/backup", "--all"], workdir: "/srv", when: when.value },
|
|
56
|
+
* { os: "linux", home: "/home/ada" },
|
|
57
|
+
* );
|
|
58
|
+
* // plan.value.files: .config/systemd/user/org.example.backup.service and .timer, with OnCalendar=*-*-* 06:10:00
|
|
59
|
+
* // plan.value.install: systemctl --user daemon-reload, then systemctl --user enable --now org.example.backup.timer
|
|
60
|
+
* }
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @module
|
|
64
|
+
*/
|
|
65
|
+
import { absurd, err, ok } from "@intellectual-frontiers/core";
|
|
66
|
+
import { el, writeXml } from "@intellectual-frontiers/formats/xml";
|
|
67
|
+
/** A schedule error as one line: `argv[1]: a line feed cannot be carried in a systemd unit`. */
|
|
68
|
+
export function formatScheduleError(e) {
|
|
69
|
+
return `${e.field}: ${e.message}`;
|
|
70
|
+
}
|
|
71
|
+
const invalid = (field, message) => ({ kind: "schedule", field, reason: "invalid", message });
|
|
72
|
+
const unsafe = (field, message) => ({ kind: "schedule", field, reason: "unsafe", message });
|
|
73
|
+
const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
74
|
+
/** A job's name, validated. */
|
|
75
|
+
export function jobName(s) {
|
|
76
|
+
return NAME.test(s)
|
|
77
|
+
? ok(s)
|
|
78
|
+
: err(invalid("name", `${JSON.stringify(s)} is not 1 to 64 lowercase letters, digits and dashes, beginning and ending with a letter or digit`));
|
|
79
|
+
}
|
|
80
|
+
const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
|
|
81
|
+
/** The intervals `minutes` takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour. */
|
|
82
|
+
export const MINUTE_STEPS = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30];
|
|
83
|
+
const inRange = (n, lo, hi) => Number.isInteger(n) && n >= lo && n <= hi;
|
|
84
|
+
/** A schedule, validated: hours 0 to 23, minutes 0 to 59, a day of the month 1 to 28, a weekday by its three letters, a step of `MINUTE_STEPS`. */
|
|
85
|
+
export function schedule(when) {
|
|
86
|
+
const hm = (w) => !inRange(w.hour, 0, 23)
|
|
87
|
+
? invalid("when.hour", `${w.hour} is not an hour from 0 to 23`)
|
|
88
|
+
: !inRange(w.minute, 0, 59)
|
|
89
|
+
? invalid("when.minute", `${w.minute} is not a minute from 0 to 59`)
|
|
90
|
+
: undefined;
|
|
91
|
+
let e;
|
|
92
|
+
switch (when.kind) {
|
|
93
|
+
case "minutes":
|
|
94
|
+
e = MINUTE_STEPS.includes(when.every)
|
|
95
|
+
? undefined
|
|
96
|
+
: invalid("when.every", `${when.every} is not one of ${MINUTE_STEPS.join(", ")} (a divisor of 60 below 60)`);
|
|
97
|
+
break;
|
|
98
|
+
case "hourly":
|
|
99
|
+
e = inRange(when.minute, 0, 59) ? undefined : invalid("when.minute", `${when.minute} is not a minute from 0 to 59`);
|
|
100
|
+
break;
|
|
101
|
+
case "daily":
|
|
102
|
+
e = hm(when);
|
|
103
|
+
break;
|
|
104
|
+
case "weekly":
|
|
105
|
+
e = WEEKDAYS.includes(when.day) ? hm(when) : invalid("when.day", `${JSON.stringify(when.day)} is not a weekday (mon to sun)`);
|
|
106
|
+
break;
|
|
107
|
+
case "monthly":
|
|
108
|
+
e = inRange(when.day, 1, 28) ? hm(when) : invalid("when.day", `${when.day} is not a day of the month from 1 to 28`);
|
|
109
|
+
break;
|
|
110
|
+
default:
|
|
111
|
+
return absurd(when);
|
|
112
|
+
}
|
|
113
|
+
return e === undefined ? ok(when) : err(e);
|
|
114
|
+
}
|
|
115
|
+
const two = (n) => String(n).padStart(2, "0");
|
|
116
|
+
const DAY_NAMES = {
|
|
117
|
+
mon: "Monday",
|
|
118
|
+
tue: "Tuesday",
|
|
119
|
+
wed: "Wednesday",
|
|
120
|
+
thu: "Thursday",
|
|
121
|
+
fri: "Friday",
|
|
122
|
+
sat: "Saturday",
|
|
123
|
+
sun: "Sunday",
|
|
124
|
+
};
|
|
125
|
+
/** When a schedule runs, as a sentence's end: `every 15 minutes`, `every hour at minute 05`, `every day at 06:10`, `every Friday at 08:00`, `on day 3 of every month at 05:00`. */
|
|
126
|
+
export function describeSchedule(s) {
|
|
127
|
+
switch (s.kind) {
|
|
128
|
+
case "minutes":
|
|
129
|
+
return s.every === 1 ? "every minute" : `every ${s.every} minutes`;
|
|
130
|
+
case "hourly":
|
|
131
|
+
return `every hour at minute ${two(s.minute)}`;
|
|
132
|
+
case "daily":
|
|
133
|
+
return `every day at ${two(s.hour)}:${two(s.minute)}`;
|
|
134
|
+
case "weekly":
|
|
135
|
+
return `every ${DAY_NAMES[s.day]} at ${two(s.hour)}:${two(s.minute)}`;
|
|
136
|
+
case "monthly":
|
|
137
|
+
return `on day ${s.day} of every month at ${two(s.hour)}:${two(s.minute)}`;
|
|
138
|
+
default:
|
|
139
|
+
return absurd(s);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** systemd's `OnCalendar=` expression for a schedule (systemd.time(7)). */
|
|
143
|
+
export function onCalendar(s) {
|
|
144
|
+
switch (s.kind) {
|
|
145
|
+
case "minutes":
|
|
146
|
+
return `*-*-* *:00/${s.every}:00`;
|
|
147
|
+
case "hourly":
|
|
148
|
+
return `*-*-* *:${two(s.minute)}:00`;
|
|
149
|
+
case "daily":
|
|
150
|
+
return `*-*-* ${two(s.hour)}:${two(s.minute)}:00`;
|
|
151
|
+
case "weekly":
|
|
152
|
+
return `${DAY_NAMES[s.day].slice(0, 3)} *-*-* ${two(s.hour)}:${two(s.minute)}:00`;
|
|
153
|
+
case "monthly":
|
|
154
|
+
return `*-*-${two(s.day)} ${two(s.hour)}:${two(s.minute)}:00`;
|
|
155
|
+
default:
|
|
156
|
+
return absurd(s);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const LAUNCHD_DAY = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
|
|
160
|
+
/** launchd's `StartCalendarInterval` for a schedule: one interval, or one for each minute of the hour the job runs at. */
|
|
161
|
+
export function calendarIntervals(s) {
|
|
162
|
+
switch (s.kind) {
|
|
163
|
+
case "minutes":
|
|
164
|
+
return Array.from({ length: 60 / s.every }, (_, i) => ({ Minute: i * s.every }));
|
|
165
|
+
case "hourly":
|
|
166
|
+
return [{ Minute: s.minute }];
|
|
167
|
+
case "daily":
|
|
168
|
+
return [{ Minute: s.minute, Hour: s.hour }];
|
|
169
|
+
case "weekly":
|
|
170
|
+
return [{ Minute: s.minute, Hour: s.hour, Weekday: LAUNCHD_DAY[s.day] }];
|
|
171
|
+
case "monthly":
|
|
172
|
+
return [{ Minute: s.minute, Hour: s.hour, Day: s.day }];
|
|
173
|
+
default:
|
|
174
|
+
return absurd(s);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** The arguments `schtasks /Create` takes for a schedule, from `/SC` on. */
|
|
178
|
+
export function schtasksSchedule(s) {
|
|
179
|
+
switch (s.kind) {
|
|
180
|
+
case "minutes":
|
|
181
|
+
return ["/SC", "MINUTE", "/MO", String(s.every), "/ST", "00:00"];
|
|
182
|
+
case "hourly":
|
|
183
|
+
return ["/SC", "HOURLY", "/ST", `00:${two(s.minute)}`];
|
|
184
|
+
case "daily":
|
|
185
|
+
return ["/SC", "DAILY", "/ST", `${two(s.hour)}:${two(s.minute)}`];
|
|
186
|
+
case "weekly":
|
|
187
|
+
return ["/SC", "WEEKLY", "/D", s.day.toUpperCase(), "/ST", `${two(s.hour)}:${two(s.minute)}`];
|
|
188
|
+
case "monthly":
|
|
189
|
+
return ["/SC", "MONTHLY", "/D", String(s.day), "/ST", `${two(s.hour)}:${two(s.minute)}`];
|
|
190
|
+
default:
|
|
191
|
+
return absurd(s);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// ---------------------------------------------------------------------------------------------------------------------------- quoting
|
|
195
|
+
/** The first character in `s` that `bad` refuses, as `U+000A`, or undefined. */
|
|
196
|
+
function refused(s, bad) {
|
|
197
|
+
for (let i = 0; i < s.length; i++) {
|
|
198
|
+
const c = s.charCodeAt(i);
|
|
199
|
+
if (bad(c))
|
|
200
|
+
return `U+${c.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
const isLineOrNul = (c) => c === 0 || c === 10 || c === 13;
|
|
205
|
+
const isControlButTab = (c) => (c < 32 && c !== 9) || c === 127;
|
|
206
|
+
const SYSTEMD_PLAIN = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
207
|
+
const SYSTEMD_PREFIXES = "@-:+!|";
|
|
208
|
+
/** A value in systemd's double quotes, with C escapes, `%%` for `%` and, where `dollar`, `$$` for `$`. */
|
|
209
|
+
function systemdQuoted(s, dollar) {
|
|
210
|
+
let out = '"';
|
|
211
|
+
for (const ch of s) {
|
|
212
|
+
const c = ch.charCodeAt(0);
|
|
213
|
+
if (ch === "\\")
|
|
214
|
+
out += "\\\\";
|
|
215
|
+
else if (ch === '"')
|
|
216
|
+
out += '\\"';
|
|
217
|
+
else if (ch === "%")
|
|
218
|
+
out += "%%";
|
|
219
|
+
else if (ch === "$" && dollar)
|
|
220
|
+
out += "$$";
|
|
221
|
+
else if (c === 9)
|
|
222
|
+
out += "\\t";
|
|
223
|
+
else if (c < 32 || c === 127)
|
|
224
|
+
out += `\\x${c.toString(16).padStart(2, "0")}`;
|
|
225
|
+
else
|
|
226
|
+
out += ch;
|
|
227
|
+
}
|
|
228
|
+
return `${out}"`;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* One argument as a word of systemd's `ExecStart=` (systemd.service(5), "Command lines"): as it is where it is plain, else in double
|
|
232
|
+
* quotes with C escapes, `%%` for a specifier's `%` and `$$` for a variable's `$`. Refused: NUL, a carriage return or a line feed; an
|
|
233
|
+
* argument that is only `;` (a command separator); and, for the program (`first`), an empty one or one that begins with a prefix
|
|
234
|
+
* character (`@-:+!|`).
|
|
235
|
+
*/
|
|
236
|
+
export function quoteSystemdArg(arg, first = false) {
|
|
237
|
+
const bad = refused(arg, isLineOrNul);
|
|
238
|
+
if (bad !== undefined)
|
|
239
|
+
return err(unsafe("argument", `${bad} cannot be carried in a systemd unit`));
|
|
240
|
+
if (arg === ";")
|
|
241
|
+
return err(unsafe("argument", "an argument that is only ; separates commands in ExecStart="));
|
|
242
|
+
if (first && (arg === "" || SYSTEMD_PREFIXES.includes(arg.charAt(0))))
|
|
243
|
+
return err(unsafe("argument", `a program must not be empty or begin with one of ${SYSTEMD_PREFIXES}`));
|
|
244
|
+
return ok(SYSTEMD_PLAIN.test(arg) ? arg : systemdQuoted(arg, true));
|
|
245
|
+
}
|
|
246
|
+
/** An argument vector as systemd's `ExecStart=` value, each word quoted by `quoteSystemdArg`; the first refusal names its index. */
|
|
247
|
+
export function quoteSystemdArgs(argv) {
|
|
248
|
+
return quoteAll(argv, quoteSystemdArg);
|
|
249
|
+
}
|
|
250
|
+
const CMD_PLAIN = /^[A-Za-z0-9_+./\\-][A-Za-z0-9_+.:/\\-]*$/;
|
|
251
|
+
/**
|
|
252
|
+
* One argument as a word of a line of a `.cmd` file that runs a program: as it is where it is plain, else in double quotes, inside which
|
|
253
|
+
* cmd.exe takes `&|<>^()` as text; `%%` for `%` (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a
|
|
254
|
+
* quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, `first`,
|
|
255
|
+
* whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character
|
|
256
|
+
* but tab; and, for the program, an empty one. Expects delayed expansion off (the `.cmd` file turns it off), so `!` is plain text.
|
|
257
|
+
*/
|
|
258
|
+
export function quoteCmdArg(arg, first = false) {
|
|
259
|
+
const bad = refused(arg, isControlButTab);
|
|
260
|
+
if (bad !== undefined)
|
|
261
|
+
return err(unsafe("argument", `${bad} cannot be carried in a .cmd file`));
|
|
262
|
+
if (arg.includes('"'))
|
|
263
|
+
return err(unsafe("argument", "a double quote cannot be carried safely in a .cmd file"));
|
|
264
|
+
if (first && arg === "")
|
|
265
|
+
return err(unsafe("argument", "a program must not be empty"));
|
|
266
|
+
if (CMD_PLAIN.test(arg))
|
|
267
|
+
return ok(arg);
|
|
268
|
+
const body = first ? arg : arg.replace(/\\+$/, (b) => b + b);
|
|
269
|
+
return ok(`"${body.replaceAll("%", "%%")}"`);
|
|
270
|
+
}
|
|
271
|
+
/** An argument vector as a command of a `.cmd` file, each word quoted by `quoteCmdArg`; the first refusal names its index. */
|
|
272
|
+
export function quoteCmdArgs(argv) {
|
|
273
|
+
return quoteAll(argv, quoteCmdArg);
|
|
274
|
+
}
|
|
275
|
+
function quoteAll(argv, quote) {
|
|
276
|
+
if (argv.length === 0)
|
|
277
|
+
return err(invalid("argv", "nothing to run: the argument vector is empty"));
|
|
278
|
+
const words = [];
|
|
279
|
+
for (const [i, a] of argv.entries()) {
|
|
280
|
+
const q = quote(a, i === 0);
|
|
281
|
+
if (q.kind === "err")
|
|
282
|
+
return err({ ...q.error, field: `argv[${i}]` });
|
|
283
|
+
words.push(q.value);
|
|
284
|
+
}
|
|
285
|
+
return ok(words.join(" "));
|
|
286
|
+
}
|
|
287
|
+
/** A value for a line of a systemd unit that takes it as written but for specifiers (`WorkingDirectory=`, `StandardOutput=append:`). */
|
|
288
|
+
function systemdPath(field, s) {
|
|
289
|
+
const bad = refused(s, (c) => c < 32 || c === 127);
|
|
290
|
+
if (bad !== undefined)
|
|
291
|
+
return err(unsafe(field, `${bad} cannot be carried in a systemd unit`));
|
|
292
|
+
if (s.trim() !== s)
|
|
293
|
+
return err(unsafe(field, "systemd trims the white space at the ends of a value"));
|
|
294
|
+
return ok(s.replaceAll("%", "%%"));
|
|
295
|
+
}
|
|
296
|
+
/** A value of the `.cmd` file in double quotes (a folder or a log path). */
|
|
297
|
+
function cmdPath(field, s) {
|
|
298
|
+
const bad = refused(s, isControlButTab);
|
|
299
|
+
if (bad !== undefined)
|
|
300
|
+
return err(unsafe(field, `${bad} cannot be carried in a .cmd file`));
|
|
301
|
+
if (s.includes('"'))
|
|
302
|
+
return err(unsafe(field, "a double quote cannot be carried safely in a .cmd file"));
|
|
303
|
+
return ok(`"${s.replaceAll("%", "%%")}"`);
|
|
304
|
+
}
|
|
305
|
+
/** Text XML 1.0 carries unchanged: no control character but tab and line feed (a carriage return is read back as a line feed), no lone surrogate, no U+FFFE or U+FFFF. */
|
|
306
|
+
function xmlText(field, s) {
|
|
307
|
+
const bad = refused(s, (c) => (c < 32 && c !== 9 && c !== 10) || c === 0xfffe || c === 0xffff);
|
|
308
|
+
if (bad !== undefined)
|
|
309
|
+
return err(unsafe(field, `${bad} cannot be carried in a property list`));
|
|
310
|
+
if (!s.isWellFormed())
|
|
311
|
+
return err(unsafe(field, "a lone surrogate cannot be carried in a property list"));
|
|
312
|
+
return ok(s);
|
|
313
|
+
}
|
|
314
|
+
const DOMAIN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;
|
|
315
|
+
const FOLDER = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62}[A-Za-z0-9])?$/;
|
|
316
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
317
|
+
const UNIT_MODE = 0o644;
|
|
318
|
+
/** An absolute path on the target, from the home folder and a path relative to it. */
|
|
319
|
+
function onTarget(t, rel) {
|
|
320
|
+
const sep = t.os === "windows" ? "\\" : "/";
|
|
321
|
+
return `${t.home.replace(/[\\/]+$/, "")}${sep}${rel.split("/").join(sep)}`;
|
|
322
|
+
}
|
|
323
|
+
/** Every check in turn: the first error, or the values. */
|
|
324
|
+
function each(items, f) {
|
|
325
|
+
const out = [];
|
|
326
|
+
for (const item of items) {
|
|
327
|
+
const r = f(item);
|
|
328
|
+
if (r.kind === "err")
|
|
329
|
+
return r;
|
|
330
|
+
out.push(r.value);
|
|
331
|
+
}
|
|
332
|
+
return ok(out);
|
|
333
|
+
}
|
|
334
|
+
/** The parts every scheduler checks alike: the owner, the program and the environment's names. */
|
|
335
|
+
function checkCommon(job, t) {
|
|
336
|
+
if (!DOMAIN.test(job.owner.domain))
|
|
337
|
+
return invalid("owner.domain", `${JSON.stringify(job.owner.domain)} is not a reverse-DNS name (lowercase labels joined by dots)`);
|
|
338
|
+
if (!FOLDER.test(job.owner.folder))
|
|
339
|
+
return invalid("owner.folder", `${JSON.stringify(job.owner.folder)} is not 1 to 64 letters, digits, dots, dashes and underscores`);
|
|
340
|
+
if (job.argv.length === 0)
|
|
341
|
+
return invalid("argv", "nothing to run: the argument vector is empty");
|
|
342
|
+
for (const k of Object.keys(job.env ?? {}))
|
|
343
|
+
if (!ENV_NAME.test(k))
|
|
344
|
+
return invalid(`env.${k}`, `${JSON.stringify(k)} is not a variable name (letters, digits and _)`);
|
|
345
|
+
const homeBad = refused(t.home, (c) => c < 32 || c === 127);
|
|
346
|
+
if (t.home === "" || homeBad !== undefined)
|
|
347
|
+
return invalid("home", "the home folder must be a path with no control character");
|
|
348
|
+
return undefined;
|
|
349
|
+
}
|
|
350
|
+
/** Linux: a systemd user service (one shot) and its timer. */
|
|
351
|
+
function planLinux(job) {
|
|
352
|
+
const label = `${job.owner.domain}.${job.name}`;
|
|
353
|
+
const description = describeSchedule(job.when);
|
|
354
|
+
if (!job.workdir.startsWith("/"))
|
|
355
|
+
return err(invalid("workdir", "the working folder must be an absolute path"));
|
|
356
|
+
const exec = quoteSystemdArgs(job.argv);
|
|
357
|
+
if (exec.kind === "err")
|
|
358
|
+
return exec;
|
|
359
|
+
const dir = systemdPath("workdir", job.workdir);
|
|
360
|
+
if (dir.kind === "err")
|
|
361
|
+
return dir;
|
|
362
|
+
const env = each(Object.entries(job.env ?? {}), ([k, v]) => {
|
|
363
|
+
const bad = refused(v, isLineOrNul);
|
|
364
|
+
return bad === undefined
|
|
365
|
+
? ok(`Environment=${systemdQuoted(`${k}=${v}`, false)}`)
|
|
366
|
+
: err(unsafe(`env.${k}`, `${bad} cannot be carried in a systemd unit`));
|
|
367
|
+
});
|
|
368
|
+
if (env.kind === "err")
|
|
369
|
+
return env;
|
|
370
|
+
let log = [];
|
|
371
|
+
if (job.log !== undefined) {
|
|
372
|
+
if (!job.log.startsWith("/"))
|
|
373
|
+
return err(invalid("log", "the log must be an absolute path"));
|
|
374
|
+
const l = systemdPath("log", job.log);
|
|
375
|
+
if (l.kind === "err")
|
|
376
|
+
return l;
|
|
377
|
+
log = [`StandardOutput=append:${l.value}`, `StandardError=append:${l.value}`];
|
|
378
|
+
}
|
|
379
|
+
const service = [
|
|
380
|
+
`# The scheduled job ${label}, written by a program: it is replaced when the job is scheduled again.`,
|
|
381
|
+
"[Unit]",
|
|
382
|
+
`Description=${label}`,
|
|
383
|
+
"",
|
|
384
|
+
"[Service]",
|
|
385
|
+
"Type=oneshot",
|
|
386
|
+
`WorkingDirectory=${dir.value}`,
|
|
387
|
+
...env.value,
|
|
388
|
+
`ExecStart=${exec.value}`,
|
|
389
|
+
...log,
|
|
390
|
+
"",
|
|
391
|
+
].join("\n");
|
|
392
|
+
const timer = [
|
|
393
|
+
`# The timer of the scheduled job ${label}, written by a program: it is replaced when the job is scheduled again.`,
|
|
394
|
+
"[Unit]",
|
|
395
|
+
`Description=${label}, ${description}`,
|
|
396
|
+
"",
|
|
397
|
+
"[Timer]",
|
|
398
|
+
`OnCalendar=${onCalendar(job.when)}`,
|
|
399
|
+
"Persistent=true",
|
|
400
|
+
"",
|
|
401
|
+
"[Install]",
|
|
402
|
+
"WantedBy=timers.target",
|
|
403
|
+
"",
|
|
404
|
+
].join("\n");
|
|
405
|
+
const units = ".config/systemd/user";
|
|
406
|
+
const reload = { argv: ["systemctl", "--user", "daemon-reload"], mayFail: false };
|
|
407
|
+
return ok({
|
|
408
|
+
os: "linux",
|
|
409
|
+
label: `${label}.timer`,
|
|
410
|
+
description,
|
|
411
|
+
files: [
|
|
412
|
+
{ path: `${units}/${label}.service`, content: service, mode: UNIT_MODE },
|
|
413
|
+
{ path: `${units}/${label}.timer`, content: timer, mode: UNIT_MODE },
|
|
414
|
+
],
|
|
415
|
+
install: [reload, { argv: ["systemctl", "--user", "enable", "--now", `${label}.timer`], mayFail: false }],
|
|
416
|
+
remove: [{ argv: ["systemctl", "--user", "disable", "--now", `${label}.timer`], mayFail: true }],
|
|
417
|
+
afterRemove: [{ ...reload, mayFail: true }],
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/** An element's children indented by two spaces for each level, where it holds only elements. */
|
|
421
|
+
function indented(e, depth = 0) {
|
|
422
|
+
const elements = e.children.filter((c) => c.kind === "element");
|
|
423
|
+
if (elements.length === 0 || elements.length !== e.children.length)
|
|
424
|
+
return e;
|
|
425
|
+
const pad = (d) => ({ kind: "text", text: `\n${" ".repeat(d)}` });
|
|
426
|
+
return { ...e, children: [...elements.flatMap((c) => [pad(depth + 1), indented(c, depth + 1)]), pad(depth)] };
|
|
427
|
+
}
|
|
428
|
+
const PLIST_DOCTYPE = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">';
|
|
429
|
+
/** A plist dictionary of keys and values, in order. */
|
|
430
|
+
const dict = (entries) => el("dict", entries.flatMap(([k, v]) => [el("key", [k]), v]));
|
|
431
|
+
const intervalDict = (c) => dict(["Minute", "Hour", "Day", "Weekday"].flatMap((k) => {
|
|
432
|
+
const v = c[k];
|
|
433
|
+
return v === undefined ? [] : [[k, el("integer", [v])]];
|
|
434
|
+
}));
|
|
435
|
+
/** macOS: a LaunchAgent property list, loaded into the user's GUI domain. */
|
|
436
|
+
function planDarwin(job, t) {
|
|
437
|
+
const label = `${job.owner.domain}.${job.name}`;
|
|
438
|
+
if (t.uid === undefined || !Number.isInteger(t.uid) || t.uid < 0)
|
|
439
|
+
return err(invalid("uid", "a macOS job needs the user's numeric id (launchctl's gui/<uid> domain)"));
|
|
440
|
+
if (!job.workdir.startsWith("/"))
|
|
441
|
+
return err(invalid("workdir", "the working folder must be an absolute path"));
|
|
442
|
+
const args = each([...job.argv.entries()], ([i, a]) => xmlText(`argv[${i}]`, a));
|
|
443
|
+
if (args.kind === "err")
|
|
444
|
+
return args;
|
|
445
|
+
if (job.argv[0] === "")
|
|
446
|
+
return err(unsafe("argv[0]", "a program must not be empty"));
|
|
447
|
+
const dir = xmlText("workdir", job.workdir);
|
|
448
|
+
if (dir.kind === "err")
|
|
449
|
+
return dir;
|
|
450
|
+
const envEntries = Object.entries(job.env ?? {});
|
|
451
|
+
const env = each(envEntries, ([k, v]) => xmlText(`env.${k}`, v));
|
|
452
|
+
if (env.kind === "err")
|
|
453
|
+
return env;
|
|
454
|
+
if (job.log !== undefined) {
|
|
455
|
+
if (!job.log.startsWith("/"))
|
|
456
|
+
return err(invalid("log", "the log must be an absolute path"));
|
|
457
|
+
const l = xmlText("log", job.log);
|
|
458
|
+
if (l.kind === "err")
|
|
459
|
+
return l;
|
|
460
|
+
}
|
|
461
|
+
const intervals = calendarIntervals(job.when).map(intervalDict);
|
|
462
|
+
const str = (s) => el("string", [s]);
|
|
463
|
+
const entries = [
|
|
464
|
+
["Label", str(label)],
|
|
465
|
+
["ProgramArguments", el("array", job.argv.map(str))],
|
|
466
|
+
["WorkingDirectory", str(job.workdir)],
|
|
467
|
+
...(envEntries.length === 0 ? [] : [["EnvironmentVariables", dict(envEntries.map(([k, v]) => [k, str(v)]))]]),
|
|
468
|
+
["StartCalendarInterval", intervals.length === 1 && intervals[0] !== undefined ? intervals[0] : el("array", intervals)],
|
|
469
|
+
...(job.log === undefined
|
|
470
|
+
? []
|
|
471
|
+
: [
|
|
472
|
+
["StandardOutPath", str(job.log)],
|
|
473
|
+
["StandardErrorPath", str(job.log)],
|
|
474
|
+
]),
|
|
475
|
+
["ProcessType", str("Background")],
|
|
476
|
+
];
|
|
477
|
+
const root = indented(el("plist", [dict(entries)], [["version", "1.0"]]));
|
|
478
|
+
const content = `${writeXml(root).replace("\n", `\n${PLIST_DOCTYPE}\n`)}\n`;
|
|
479
|
+
const rel = `Library/LaunchAgents/${label}.plist`;
|
|
480
|
+
const domain = `gui/${t.uid}`;
|
|
481
|
+
const bootout = { argv: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true };
|
|
482
|
+
return ok({
|
|
483
|
+
os: "darwin",
|
|
484
|
+
label,
|
|
485
|
+
description: describeSchedule(job.when),
|
|
486
|
+
files: [{ path: rel, content, mode: UNIT_MODE }],
|
|
487
|
+
install: [bootout, { argv: ["launchctl", "bootstrap", domain, onTarget(t, rel)], mayFail: false }],
|
|
488
|
+
remove: [bootout],
|
|
489
|
+
afterRemove: [],
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const WINDOWS_ABSOLUTE = /^(?:[A-Za-z]:[\\/]|\\\\)/;
|
|
493
|
+
/** Windows: a `.cmd` file (working folder, environment, log) and a Task Scheduler task that runs it as the signed-in user. */
|
|
494
|
+
function planWindows(job, t) {
|
|
495
|
+
const task = `${job.owner.folder}\\${job.name}`;
|
|
496
|
+
if (t.home.includes('"') || t.home.includes("%"))
|
|
497
|
+
return err(unsafe("home", "a double quote or a % in the home folder cannot be carried in a task's command"));
|
|
498
|
+
if (!WINDOWS_ABSOLUTE.test(job.workdir))
|
|
499
|
+
return err(invalid("workdir", "the working folder must be an absolute path (C:\\... or \\\\server\\...)"));
|
|
500
|
+
const exec = quoteCmdArgs(job.argv);
|
|
501
|
+
if (exec.kind === "err")
|
|
502
|
+
return exec;
|
|
503
|
+
const dir = cmdPath("workdir", job.workdir);
|
|
504
|
+
if (dir.kind === "err")
|
|
505
|
+
return dir;
|
|
506
|
+
const env = each(Object.entries(job.env ?? {}), ([k, v]) => {
|
|
507
|
+
const q = cmdPath(`env.${k}`, `${k}=${v}`);
|
|
508
|
+
return q.kind === "err" ? q : ok(`set ${q.value}`);
|
|
509
|
+
});
|
|
510
|
+
if (env.kind === "err")
|
|
511
|
+
return env;
|
|
512
|
+
let redirect = "";
|
|
513
|
+
if (job.log !== undefined) {
|
|
514
|
+
if (!WINDOWS_ABSOLUTE.test(job.log))
|
|
515
|
+
return err(invalid("log", "the log must be an absolute path"));
|
|
516
|
+
const l = cmdPath("log", job.log);
|
|
517
|
+
if (l.kind === "err")
|
|
518
|
+
return l;
|
|
519
|
+
redirect = ` >> ${l.value} 2>&1`;
|
|
520
|
+
}
|
|
521
|
+
const content = [
|
|
522
|
+
"@echo off",
|
|
523
|
+
`rem The scheduled job ${task}, written by a program: it is replaced when the job is scheduled again.`,
|
|
524
|
+
"setlocal DisableDelayedExpansion",
|
|
525
|
+
"chcp 65001 >nul",
|
|
526
|
+
`cd /d ${dir.value} || exit /b 1`,
|
|
527
|
+
...env.value,
|
|
528
|
+
`${exec.value}${redirect}`,
|
|
529
|
+
"exit /b %ERRORLEVEL%",
|
|
530
|
+
"",
|
|
531
|
+
].join("\r\n");
|
|
532
|
+
const rel = `AppData/Local/${job.owner.folder}/${job.name}.cmd`;
|
|
533
|
+
return ok({
|
|
534
|
+
os: "windows",
|
|
535
|
+
label: task,
|
|
536
|
+
description: describeSchedule(job.when),
|
|
537
|
+
files: [{ path: rel, content }],
|
|
538
|
+
install: [
|
|
539
|
+
{ argv: ["schtasks", "/Create", "/F", "/TN", task, "/TR", `"${onTarget(t, rel)}"`, ...schtasksSchedule(job.when)], mayFail: false },
|
|
540
|
+
],
|
|
541
|
+
remove: [{ argv: ["schtasks", "/Delete", "/F", "/TN", task], mayFail: true }],
|
|
542
|
+
afterRemove: [],
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run
|
|
547
|
+
* by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.
|
|
548
|
+
*/
|
|
549
|
+
export function planJob(job, target) {
|
|
550
|
+
const common = checkCommon(job, target);
|
|
551
|
+
if (common !== undefined)
|
|
552
|
+
return err(common);
|
|
553
|
+
switch (target.os) {
|
|
554
|
+
case "linux":
|
|
555
|
+
return planLinux(job);
|
|
556
|
+
case "darwin":
|
|
557
|
+
return planDarwin(job, target);
|
|
558
|
+
case "windows":
|
|
559
|
+
return planWindows(job, target);
|
|
560
|
+
default:
|
|
561
|
+
return absurd(target.os);
|
|
562
|
+
}
|
|
563
|
+
}
|
package/dist/lock.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Who holds a lock. */
|
|
2
|
+
export type Holder = {
|
|
3
|
+
readonly pid: number;
|
|
4
|
+
readonly command: string;
|
|
5
|
+
readonly since: string;
|
|
6
|
+
readonly token: string;
|
|
7
|
+
};
|
|
8
|
+
/** How to take a lock. */
|
|
9
|
+
export type LockOptions = {
|
|
10
|
+
/** Wait until it is free (polling), or give up at once. */
|
|
11
|
+
readonly wait: boolean;
|
|
12
|
+
/** What the holder runs, said to whoever waits. */
|
|
13
|
+
readonly command?: string;
|
|
14
|
+
/** Called once, with the holder where it can be read, when the lock is not free. */
|
|
15
|
+
readonly onWait?: (holder: Holder | undefined) => void;
|
|
16
|
+
/** How often a waiting run looks again (250 ms by default). */
|
|
17
|
+
readonly pollMs?: number;
|
|
18
|
+
/** The variable that says a parent already holds the lock (no variable by default); it is set while the lock is held. */
|
|
19
|
+
readonly inheritEnv?: string;
|
|
20
|
+
/** How long a waiting run waits before it gives up and returns nothing (no limit by default). */
|
|
21
|
+
readonly timeoutMs?: number;
|
|
22
|
+
};
|
|
23
|
+
/** A lock taken. */
|
|
24
|
+
export type Held = {
|
|
25
|
+
/** Who holds it: this process. */
|
|
26
|
+
readonly holder: Holder;
|
|
27
|
+
/** The lock given back (the file removed where it is still this holder's); safe to call twice. */
|
|
28
|
+
release(): void;
|
|
29
|
+
};
|
|
30
|
+
/** Whether a process runs: a signal of 0 checks without sending one. A process of another account counts as running. */
|
|
31
|
+
export declare function processRuns(pid: number): boolean;
|
|
32
|
+
/** Who holds the lock at `path`, where its file can be read; whether that process still runs is not checked here. */
|
|
33
|
+
export declare function readHolder(path: string): Promise<Holder | undefined>;
|
|
34
|
+
/** A holder as a person reads it: `update (pid 4242, for 3m 12s)`. */
|
|
35
|
+
export declare function describeHolder(h: Holder, now?: number): string;
|
|
36
|
+
/**
|
|
37
|
+
* The lock at `path` taken, or undefined where it is held by a running process and `wait` is false (or `timeoutMs` passed). A lock whose
|
|
38
|
+
* holder no longer runs, or whose file cannot be read, is taken over. Where `inheritEnv` is set in the environment, a parent holds it,
|
|
39
|
+
* and it is given at once (its release does nothing).
|
|
40
|
+
*/
|
|
41
|
+
export declare function acquireLock(path: string, options: LockOptions): Promise<Held | undefined>;
|