@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.
@@ -0,0 +1,660 @@
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, type Result } from "@intellectual-frontiers/core";
66
+ import type { Brand } from "@intellectual-frontiers/core";
67
+ import { el, writeXml, type XmlElement, type XmlNode } from "@intellectual-frontiers/formats/xml";
68
+
69
+ /** The schedulers a job can be planned for: systemd on Linux, launchd on macOS, Task Scheduler on Windows. */
70
+ export type SchedulerOs = "linux" | "darwin" | "windows";
71
+
72
+ /** Why a job cannot be planned: the field at fault (`name`, `argv[2]`, `env.PATH`, `when.minute`...), and whether its value is not valid or cannot be carried safely. */
73
+ export type ScheduleError = {
74
+ readonly kind: "schedule";
75
+ readonly field: string;
76
+ readonly reason: "invalid" | "unsafe";
77
+ readonly message: string;
78
+ };
79
+
80
+ /** A schedule error as one line: `argv[1]: a line feed cannot be carried in a systemd unit`. */
81
+ export function formatScheduleError(e: ScheduleError): string {
82
+ return `${e.field}: ${e.message}`;
83
+ }
84
+
85
+ const invalid = (field: string, message: string): ScheduleError => ({ kind: "schedule", field, reason: "invalid", message });
86
+ const unsafe = (field: string, message: string): ScheduleError => ({ kind: "schedule", field, reason: "unsafe", message });
87
+
88
+ /** A job's name, safe in a file name, a unit name, a plist label and a task name: 1 to 64 lowercase letters, digits and dashes, beginning and ending with a letter or digit. */
89
+ export type JobName = Brand<string, "JobName">;
90
+
91
+ const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
92
+
93
+ /** A job's name, validated. */
94
+ export function jobName(s: string): Result<JobName, ScheduleError> {
95
+ return NAME.test(s)
96
+ ? ok(s as JobName)
97
+ : err(
98
+ invalid(
99
+ "name",
100
+ `${JSON.stringify(s)} is not 1 to 64 lowercase letters, digits and dashes, beginning and ending with a letter or digit`,
101
+ ),
102
+ );
103
+ }
104
+
105
+ /** The day of a weekly schedule. */
106
+ export type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
107
+
108
+ const WEEKDAYS: readonly Weekday[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
109
+
110
+ /** When a job runs, in local time: every N minutes on the clock, every hour at a minute, every day, every week on a day, or every month on a day. */
111
+ export type When =
112
+ | { readonly kind: "minutes"; readonly every: number }
113
+ | { readonly kind: "hourly"; readonly minute: number }
114
+ | { readonly kind: "daily"; readonly hour: number; readonly minute: number }
115
+ | { readonly kind: "weekly"; readonly day: Weekday; readonly hour: number; readonly minute: number }
116
+ | { readonly kind: "monthly"; readonly day: number; readonly hour: number; readonly minute: number };
117
+
118
+ /** A `When` whose numbers are in range, made only by `schedule`. */
119
+ export type Schedule = Brand<When, "Schedule">;
120
+
121
+ /** The intervals `minutes` takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour. */
122
+ export const MINUTE_STEPS: readonly number[] = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30];
123
+
124
+ const inRange = (n: number, lo: number, hi: number): boolean => Number.isInteger(n) && n >= lo && n <= hi;
125
+
126
+ /** 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`. */
127
+ export function schedule(when: When): Result<Schedule, ScheduleError> {
128
+ const hm = (w: { readonly hour: number; readonly minute: number }): ScheduleError | undefined =>
129
+ !inRange(w.hour, 0, 23)
130
+ ? invalid("when.hour", `${w.hour} is not an hour from 0 to 23`)
131
+ : !inRange(w.minute, 0, 59)
132
+ ? invalid("when.minute", `${w.minute} is not a minute from 0 to 59`)
133
+ : undefined;
134
+ let e: ScheduleError | undefined;
135
+ switch (when.kind) {
136
+ case "minutes":
137
+ e = MINUTE_STEPS.includes(when.every)
138
+ ? undefined
139
+ : invalid("when.every", `${when.every} is not one of ${MINUTE_STEPS.join(", ")} (a divisor of 60 below 60)`);
140
+ break;
141
+ case "hourly":
142
+ e = inRange(when.minute, 0, 59) ? undefined : invalid("when.minute", `${when.minute} is not a minute from 0 to 59`);
143
+ break;
144
+ case "daily":
145
+ e = hm(when);
146
+ break;
147
+ case "weekly":
148
+ e = WEEKDAYS.includes(when.day) ? hm(when) : invalid("when.day", `${JSON.stringify(when.day)} is not a weekday (mon to sun)`);
149
+ break;
150
+ case "monthly":
151
+ e = inRange(when.day, 1, 28) ? hm(when) : invalid("when.day", `${when.day} is not a day of the month from 1 to 28`);
152
+ break;
153
+ default:
154
+ return absurd(when);
155
+ }
156
+ return e === undefined ? ok(when as Schedule) : err(e);
157
+ }
158
+
159
+ const two = (n: number): string => String(n).padStart(2, "0");
160
+ const DAY_NAMES: Readonly<Record<Weekday, string>> = {
161
+ mon: "Monday",
162
+ tue: "Tuesday",
163
+ wed: "Wednesday",
164
+ thu: "Thursday",
165
+ fri: "Friday",
166
+ sat: "Saturday",
167
+ sun: "Sunday",
168
+ };
169
+
170
+ /** 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`. */
171
+ export function describeSchedule(s: Schedule): string {
172
+ switch (s.kind) {
173
+ case "minutes":
174
+ return s.every === 1 ? "every minute" : `every ${s.every} minutes`;
175
+ case "hourly":
176
+ return `every hour at minute ${two(s.minute)}`;
177
+ case "daily":
178
+ return `every day at ${two(s.hour)}:${two(s.minute)}`;
179
+ case "weekly":
180
+ return `every ${DAY_NAMES[s.day]} at ${two(s.hour)}:${two(s.minute)}`;
181
+ case "monthly":
182
+ return `on day ${s.day} of every month at ${two(s.hour)}:${two(s.minute)}`;
183
+ default:
184
+ return absurd(s);
185
+ }
186
+ }
187
+
188
+ /** systemd's `OnCalendar=` expression for a schedule (systemd.time(7)). */
189
+ export function onCalendar(s: Schedule): string {
190
+ switch (s.kind) {
191
+ case "minutes":
192
+ return `*-*-* *:00/${s.every}:00`;
193
+ case "hourly":
194
+ return `*-*-* *:${two(s.minute)}:00`;
195
+ case "daily":
196
+ return `*-*-* ${two(s.hour)}:${two(s.minute)}:00`;
197
+ case "weekly":
198
+ return `${DAY_NAMES[s.day].slice(0, 3)} *-*-* ${two(s.hour)}:${two(s.minute)}:00`;
199
+ case "monthly":
200
+ return `*-*-${two(s.day)} ${two(s.hour)}:${two(s.minute)}:00`;
201
+ default:
202
+ return absurd(s);
203
+ }
204
+ }
205
+
206
+ /** One launchd calendar interval: the job runs whenever every key given matches (`Weekday` 0 is Sunday). */
207
+ export type CalendarInterval = { readonly Minute: number; readonly Hour?: number; readonly Day?: number; readonly Weekday?: number };
208
+
209
+ const LAUNCHD_DAY: Readonly<Record<Weekday, number>> = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
210
+
211
+ /** launchd's `StartCalendarInterval` for a schedule: one interval, or one for each minute of the hour the job runs at. */
212
+ export function calendarIntervals(s: Schedule): readonly CalendarInterval[] {
213
+ switch (s.kind) {
214
+ case "minutes":
215
+ return Array.from({ length: 60 / s.every }, (_, i) => ({ Minute: i * s.every }));
216
+ case "hourly":
217
+ return [{ Minute: s.minute }];
218
+ case "daily":
219
+ return [{ Minute: s.minute, Hour: s.hour }];
220
+ case "weekly":
221
+ return [{ Minute: s.minute, Hour: s.hour, Weekday: LAUNCHD_DAY[s.day] }];
222
+ case "monthly":
223
+ return [{ Minute: s.minute, Hour: s.hour, Day: s.day }];
224
+ default:
225
+ return absurd(s);
226
+ }
227
+ }
228
+
229
+ /** The arguments `schtasks /Create` takes for a schedule, from `/SC` on. */
230
+ export function schtasksSchedule(s: Schedule): readonly string[] {
231
+ switch (s.kind) {
232
+ case "minutes":
233
+ return ["/SC", "MINUTE", "/MO", String(s.every), "/ST", "00:00"];
234
+ case "hourly":
235
+ return ["/SC", "HOURLY", "/ST", `00:${two(s.minute)}`];
236
+ case "daily":
237
+ return ["/SC", "DAILY", "/ST", `${two(s.hour)}:${two(s.minute)}`];
238
+ case "weekly":
239
+ return ["/SC", "WEEKLY", "/D", s.day.toUpperCase(), "/ST", `${two(s.hour)}:${two(s.minute)}`];
240
+ case "monthly":
241
+ return ["/SC", "MONTHLY", "/D", String(s.day), "/ST", `${two(s.hour)}:${two(s.minute)}`];
242
+ default:
243
+ return absurd(s);
244
+ }
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------------------------------------------------------- quoting
248
+
249
+ /** The first character in `s` that `bad` refuses, as `U+000A`, or undefined. */
250
+ function refused(s: string, bad: (code: number) => boolean): string | undefined {
251
+ for (let i = 0; i < s.length; i++) {
252
+ const c = s.charCodeAt(i);
253
+ if (bad(c)) return `U+${c.toString(16).toUpperCase().padStart(4, "0")}`;
254
+ }
255
+ return undefined;
256
+ }
257
+
258
+ const isLineOrNul = (c: number): boolean => c === 0 || c === 10 || c === 13;
259
+ const isControlButTab = (c: number): boolean => (c < 32 && c !== 9) || c === 127;
260
+
261
+ const SYSTEMD_PLAIN = /^[A-Za-z0-9_@+=:,./-]+$/;
262
+ const SYSTEMD_PREFIXES = "@-:+!|";
263
+
264
+ /** A value in systemd's double quotes, with C escapes, `%%` for `%` and, where `dollar`, `$$` for `$`. */
265
+ function systemdQuoted(s: string, dollar: boolean): string {
266
+ let out = '"';
267
+ for (const ch of s) {
268
+ const c = ch.charCodeAt(0);
269
+ if (ch === "\\") out += "\\\\";
270
+ else if (ch === '"') out += '\\"';
271
+ else if (ch === "%") out += "%%";
272
+ else if (ch === "$" && dollar) out += "$$";
273
+ else if (c === 9) out += "\\t";
274
+ else if (c < 32 || c === 127) out += `\\x${c.toString(16).padStart(2, "0")}`;
275
+ else out += ch;
276
+ }
277
+ return `${out}"`;
278
+ }
279
+
280
+ /**
281
+ * One argument as a word of systemd's `ExecStart=` (systemd.service(5), "Command lines"): as it is where it is plain, else in double
282
+ * quotes with C escapes, `%%` for a specifier's `%` and `$$` for a variable's `$`. Refused: NUL, a carriage return or a line feed; an
283
+ * argument that is only `;` (a command separator); and, for the program (`first`), an empty one or one that begins with a prefix
284
+ * character (`@-:+!|`).
285
+ */
286
+ export function quoteSystemdArg(arg: string, first = false): Result<string, ScheduleError> {
287
+ const bad = refused(arg, isLineOrNul);
288
+ if (bad !== undefined) return err(unsafe("argument", `${bad} cannot be carried in a systemd unit`));
289
+ if (arg === ";") return err(unsafe("argument", "an argument that is only ; separates commands in ExecStart="));
290
+ if (first && (arg === "" || SYSTEMD_PREFIXES.includes(arg.charAt(0))))
291
+ return err(unsafe("argument", `a program must not be empty or begin with one of ${SYSTEMD_PREFIXES}`));
292
+ return ok(SYSTEMD_PLAIN.test(arg) ? arg : systemdQuoted(arg, true));
293
+ }
294
+
295
+ /** An argument vector as systemd's `ExecStart=` value, each word quoted by `quoteSystemdArg`; the first refusal names its index. */
296
+ export function quoteSystemdArgs(argv: readonly string[]): Result<string, ScheduleError> {
297
+ return quoteAll(argv, quoteSystemdArg);
298
+ }
299
+
300
+ const CMD_PLAIN = /^[A-Za-z0-9_+./\\-][A-Za-z0-9_+.:/\\-]*$/;
301
+
302
+ /**
303
+ * 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
304
+ * cmd.exe takes `&|<>^()` as text; `%%` for `%` (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a
305
+ * quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, `first`,
306
+ * whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character
307
+ * but tab; and, for the program, an empty one. Expects delayed expansion off (the `.cmd` file turns it off), so `!` is plain text.
308
+ */
309
+ export function quoteCmdArg(arg: string, first = false): Result<string, ScheduleError> {
310
+ const bad = refused(arg, isControlButTab);
311
+ if (bad !== undefined) return err(unsafe("argument", `${bad} cannot be carried in a .cmd file`));
312
+ if (arg.includes('"')) return err(unsafe("argument", "a double quote cannot be carried safely in a .cmd file"));
313
+ if (first && arg === "") return err(unsafe("argument", "a program must not be empty"));
314
+ if (CMD_PLAIN.test(arg)) return ok(arg);
315
+ const body = first ? arg : arg.replace(/\\+$/, (b) => b + b);
316
+ return ok(`"${body.replaceAll("%", "%%")}"`);
317
+ }
318
+
319
+ /** An argument vector as a command of a `.cmd` file, each word quoted by `quoteCmdArg`; the first refusal names its index. */
320
+ export function quoteCmdArgs(argv: readonly string[]): Result<string, ScheduleError> {
321
+ return quoteAll(argv, quoteCmdArg);
322
+ }
323
+
324
+ function quoteAll(
325
+ argv: readonly string[],
326
+ quote: (arg: string, first: boolean) => Result<string, ScheduleError>,
327
+ ): Result<string, ScheduleError> {
328
+ if (argv.length === 0) return err(invalid("argv", "nothing to run: the argument vector is empty"));
329
+ const words: string[] = [];
330
+ for (const [i, a] of argv.entries()) {
331
+ const q = quote(a, i === 0);
332
+ if (q.kind === "err") return err({ ...q.error, field: `argv[${i}]` });
333
+ words.push(q.value);
334
+ }
335
+ return ok(words.join(" "));
336
+ }
337
+
338
+ /** A value for a line of a systemd unit that takes it as written but for specifiers (`WorkingDirectory=`, `StandardOutput=append:`). */
339
+ function systemdPath(field: string, s: string): Result<string, ScheduleError> {
340
+ const bad = refused(s, (c) => c < 32 || c === 127);
341
+ if (bad !== undefined) return err(unsafe(field, `${bad} cannot be carried in a systemd unit`));
342
+ if (s.trim() !== s) return err(unsafe(field, "systemd trims the white space at the ends of a value"));
343
+ return ok(s.replaceAll("%", "%%"));
344
+ }
345
+
346
+ /** A value of the `.cmd` file in double quotes (a folder or a log path). */
347
+ function cmdPath(field: string, s: string): Result<string, ScheduleError> {
348
+ const bad = refused(s, isControlButTab);
349
+ if (bad !== undefined) return err(unsafe(field, `${bad} cannot be carried in a .cmd file`));
350
+ if (s.includes('"')) return err(unsafe(field, "a double quote cannot be carried safely in a .cmd file"));
351
+ return ok(`"${s.replaceAll("%", "%%")}"`);
352
+ }
353
+
354
+ /** 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. */
355
+ function xmlText(field: string, s: string): Result<string, ScheduleError> {
356
+ const bad = refused(s, (c) => (c < 32 && c !== 9 && c !== 10) || c === 0xfffe || c === 0xffff);
357
+ if (bad !== undefined) return err(unsafe(field, `${bad} cannot be carried in a property list`));
358
+ if (!s.isWellFormed()) return err(unsafe(field, "a lone surrogate cannot be carried in a property list"));
359
+ return ok(s);
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------------------------------------------------------- the plan
363
+
364
+ /** Who a job belongs to: a reverse-DNS `domain` for the launchd label and the systemd unit, and a Task Scheduler `folder`. */
365
+ export type JobOwner = {
366
+ /** Lowercase labels of letters, digits and dashes, two or more, joined by dots (`org.example.backup`). */
367
+ readonly domain: string;
368
+ /** Letters, digits, dots, dashes and underscores, beginning and ending with a letter or digit (`Example`). */
369
+ readonly folder: string;
370
+ };
371
+
372
+ /** A job to schedule. */
373
+ export type JobSpec = {
374
+ /** Its name, unique under its owner. */
375
+ readonly name: JobName;
376
+ /** Its owner, which makes its label and where its files go. */
377
+ readonly owner: JobOwner;
378
+ /** The program and its arguments, run without a shell (by the scheduler, or by the `.cmd` file on Windows). */
379
+ readonly argv: readonly string[];
380
+ /** The absolute folder it runs in. */
381
+ readonly workdir: string;
382
+ /** Variables added to its environment. */
383
+ readonly env?: Readonly<Record<string, string>>;
384
+ /** When it runs. */
385
+ readonly when: Schedule;
386
+ /** An absolute file its output and errors are appended to (systemd's journal, and nothing on macOS and Windows, without it). */
387
+ readonly log?: string;
388
+ };
389
+
390
+ /** The computer a job is planned for: its scheduler, the user's home folder in its own form, and on macOS the user's numeric id (launchctl's `gui/<uid>` domain). */
391
+ export type Target = { readonly os: SchedulerOs; readonly home: string; readonly uid?: number };
392
+
393
+ /** A file to write: its path relative to the home folder, parts joined by `/`; its text; and its mode where it matters (POSIX permission bits). */
394
+ export type PlannedFile = { readonly path: string; readonly content: string; readonly mode?: number };
395
+
396
+ /** A command to run, by its argument vector and never through a shell; `mayFail` where a failure is expected and stops nothing (nothing to unload). */
397
+ export type Step = { readonly argv: readonly string[]; readonly mayFail: boolean };
398
+
399
+ /** What scheduling a job takes: the files to write, then `install`; to remove it, `remove`, then the files removed, then `afterRemove`. */
400
+ export type JobPlan = {
401
+ /** The scheduler. */
402
+ readonly os: SchedulerOs;
403
+ /** The job's label: the systemd timer, the launchd label, or the task's name. */
404
+ readonly label: string;
405
+ /** When it runs, in words. */
406
+ readonly description: string;
407
+ /** The files to write before `install`, and to remove after `remove`. */
408
+ readonly files: readonly PlannedFile[];
409
+ /** The commands that load and enable the job. */
410
+ readonly install: readonly Step[];
411
+ /** The commands that disable and unload it, before its files are removed. */
412
+ readonly remove: readonly Step[];
413
+ /** The commands to run once its files are removed (systemd forgets the units). */
414
+ readonly afterRemove: readonly Step[];
415
+ };
416
+
417
+ const DOMAIN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;
418
+ const FOLDER = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62}[A-Za-z0-9])?$/;
419
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
420
+ const UNIT_MODE = 0o644;
421
+
422
+ /** An absolute path on the target, from the home folder and a path relative to it. */
423
+ function onTarget(t: Target, rel: string): string {
424
+ const sep = t.os === "windows" ? "\\" : "/";
425
+ return `${t.home.replace(/[\\/]+$/, "")}${sep}${rel.split("/").join(sep)}`;
426
+ }
427
+
428
+ /** Every check in turn: the first error, or the values. */
429
+ function each<T>(items: readonly T[], f: (item: T) => Result<string, ScheduleError>): Result<readonly string[], ScheduleError> {
430
+ const out: string[] = [];
431
+ for (const item of items) {
432
+ const r = f(item);
433
+ if (r.kind === "err") return r;
434
+ out.push(r.value);
435
+ }
436
+ return ok(out);
437
+ }
438
+
439
+ /** The parts every scheduler checks alike: the owner, the program and the environment's names. */
440
+ function checkCommon(job: JobSpec, t: Target): ScheduleError | undefined {
441
+ if (!DOMAIN.test(job.owner.domain))
442
+ return invalid("owner.domain", `${JSON.stringify(job.owner.domain)} is not a reverse-DNS name (lowercase labels joined by dots)`);
443
+ if (!FOLDER.test(job.owner.folder))
444
+ return invalid("owner.folder", `${JSON.stringify(job.owner.folder)} is not 1 to 64 letters, digits, dots, dashes and underscores`);
445
+ if (job.argv.length === 0) return invalid("argv", "nothing to run: the argument vector is empty");
446
+ for (const k of Object.keys(job.env ?? {}))
447
+ if (!ENV_NAME.test(k)) return invalid(`env.${k}`, `${JSON.stringify(k)} is not a variable name (letters, digits and _)`);
448
+ const homeBad = refused(t.home, (c) => c < 32 || c === 127);
449
+ if (t.home === "" || homeBad !== undefined) return invalid("home", "the home folder must be a path with no control character");
450
+ return undefined;
451
+ }
452
+
453
+ /** Linux: a systemd user service (one shot) and its timer. */
454
+ function planLinux(job: JobSpec): Result<JobPlan, ScheduleError> {
455
+ const label = `${job.owner.domain}.${job.name}`;
456
+ const description = describeSchedule(job.when);
457
+ if (!job.workdir.startsWith("/")) return err(invalid("workdir", "the working folder must be an absolute path"));
458
+ const exec = quoteSystemdArgs(job.argv);
459
+ if (exec.kind === "err") return exec;
460
+ const dir = systemdPath("workdir", job.workdir);
461
+ if (dir.kind === "err") return dir;
462
+ const env = each(Object.entries(job.env ?? {}), ([k, v]) => {
463
+ const bad = refused(v, isLineOrNul);
464
+ return bad === undefined
465
+ ? ok(`Environment=${systemdQuoted(`${k}=${v}`, false)}`)
466
+ : err(unsafe(`env.${k}`, `${bad} cannot be carried in a systemd unit`));
467
+ });
468
+ if (env.kind === "err") return env;
469
+ let log: readonly string[] = [];
470
+ if (job.log !== undefined) {
471
+ if (!job.log.startsWith("/")) return err(invalid("log", "the log must be an absolute path"));
472
+ const l = systemdPath("log", job.log);
473
+ if (l.kind === "err") return l;
474
+ log = [`StandardOutput=append:${l.value}`, `StandardError=append:${l.value}`];
475
+ }
476
+ const service = [
477
+ `# The scheduled job ${label}, written by a program: it is replaced when the job is scheduled again.`,
478
+ "[Unit]",
479
+ `Description=${label}`,
480
+ "",
481
+ "[Service]",
482
+ "Type=oneshot",
483
+ `WorkingDirectory=${dir.value}`,
484
+ ...env.value,
485
+ `ExecStart=${exec.value}`,
486
+ ...log,
487
+ "",
488
+ ].join("\n");
489
+ const timer = [
490
+ `# The timer of the scheduled job ${label}, written by a program: it is replaced when the job is scheduled again.`,
491
+ "[Unit]",
492
+ `Description=${label}, ${description}`,
493
+ "",
494
+ "[Timer]",
495
+ `OnCalendar=${onCalendar(job.when)}`,
496
+ "Persistent=true",
497
+ "",
498
+ "[Install]",
499
+ "WantedBy=timers.target",
500
+ "",
501
+ ].join("\n");
502
+ const units = ".config/systemd/user";
503
+ const reload: Step = { argv: ["systemctl", "--user", "daemon-reload"], mayFail: false };
504
+ return ok({
505
+ os: "linux",
506
+ label: `${label}.timer`,
507
+ description,
508
+ files: [
509
+ { path: `${units}/${label}.service`, content: service, mode: UNIT_MODE },
510
+ { path: `${units}/${label}.timer`, content: timer, mode: UNIT_MODE },
511
+ ],
512
+ install: [reload, { argv: ["systemctl", "--user", "enable", "--now", `${label}.timer`], mayFail: false }],
513
+ remove: [{ argv: ["systemctl", "--user", "disable", "--now", `${label}.timer`], mayFail: true }],
514
+ afterRemove: [{ ...reload, mayFail: true }],
515
+ });
516
+ }
517
+
518
+ /** An element's children indented by two spaces for each level, where it holds only elements. */
519
+ function indented(e: XmlElement, depth = 0): XmlElement {
520
+ const elements = e.children.filter((c): c is XmlElement => c.kind === "element");
521
+ if (elements.length === 0 || elements.length !== e.children.length) return e;
522
+ const pad = (d: number): XmlNode => ({ kind: "text", text: `\n${" ".repeat(d)}` });
523
+ return { ...e, children: [...elements.flatMap((c) => [pad(depth + 1), indented(c, depth + 1)]), pad(depth)] };
524
+ }
525
+
526
+ const PLIST_DOCTYPE = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">';
527
+
528
+ /** A plist dictionary of keys and values, in order. */
529
+ const dict = (entries: readonly (readonly [string, XmlElement])[]): XmlElement =>
530
+ el(
531
+ "dict",
532
+ entries.flatMap(([k, v]) => [el("key", [k]), v]),
533
+ );
534
+ const intervalDict = (c: CalendarInterval): XmlElement =>
535
+ dict(
536
+ (["Minute", "Hour", "Day", "Weekday"] as const).flatMap((k) => {
537
+ const v = c[k];
538
+ return v === undefined ? [] : [[k, el("integer", [v])] as const];
539
+ }),
540
+ );
541
+
542
+ /** macOS: a LaunchAgent property list, loaded into the user's GUI domain. */
543
+ function planDarwin(job: JobSpec, t: Target): Result<JobPlan, ScheduleError> {
544
+ const label = `${job.owner.domain}.${job.name}`;
545
+ if (t.uid === undefined || !Number.isInteger(t.uid) || t.uid < 0)
546
+ return err(invalid("uid", "a macOS job needs the user's numeric id (launchctl's gui/<uid> domain)"));
547
+ if (!job.workdir.startsWith("/")) return err(invalid("workdir", "the working folder must be an absolute path"));
548
+ const args = each([...job.argv.entries()], ([i, a]) => xmlText(`argv[${i}]`, a));
549
+ if (args.kind === "err") return args;
550
+ if (job.argv[0] === "") return err(unsafe("argv[0]", "a program must not be empty"));
551
+ const dir = xmlText("workdir", job.workdir);
552
+ if (dir.kind === "err") return dir;
553
+ const envEntries = Object.entries(job.env ?? {});
554
+ const env = each(envEntries, ([k, v]) => xmlText(`env.${k}`, v));
555
+ if (env.kind === "err") return env;
556
+ if (job.log !== undefined) {
557
+ if (!job.log.startsWith("/")) return err(invalid("log", "the log must be an absolute path"));
558
+ const l = xmlText("log", job.log);
559
+ if (l.kind === "err") return l;
560
+ }
561
+ const intervals = calendarIntervals(job.when).map(intervalDict);
562
+ const str = (s: string): XmlElement => el("string", [s]);
563
+ const entries: (readonly [string, XmlElement])[] = [
564
+ ["Label", str(label)],
565
+ ["ProgramArguments", el("array", job.argv.map(str))],
566
+ ["WorkingDirectory", str(job.workdir)],
567
+ ...(envEntries.length === 0 ? [] : [["EnvironmentVariables", dict(envEntries.map(([k, v]) => [k, str(v)] as const))] as const]),
568
+ ["StartCalendarInterval", intervals.length === 1 && intervals[0] !== undefined ? intervals[0] : el("array", intervals)],
569
+ ...(job.log === undefined
570
+ ? []
571
+ : ([
572
+ ["StandardOutPath", str(job.log)],
573
+ ["StandardErrorPath", str(job.log)],
574
+ ] as const)),
575
+ ["ProcessType", str("Background")],
576
+ ];
577
+ const root = indented(el("plist", [dict(entries)], [["version", "1.0"]]));
578
+ const content = `${writeXml(root).replace("\n", `\n${PLIST_DOCTYPE}\n`)}\n`;
579
+ const rel = `Library/LaunchAgents/${label}.plist`;
580
+ const domain = `gui/${t.uid}`;
581
+ const bootout: Step = { argv: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true };
582
+ return ok({
583
+ os: "darwin",
584
+ label,
585
+ description: describeSchedule(job.when),
586
+ files: [{ path: rel, content, mode: UNIT_MODE }],
587
+ install: [bootout, { argv: ["launchctl", "bootstrap", domain, onTarget(t, rel)], mayFail: false }],
588
+ remove: [bootout],
589
+ afterRemove: [],
590
+ });
591
+ }
592
+
593
+ const WINDOWS_ABSOLUTE = /^(?:[A-Za-z]:[\\/]|\\\\)/;
594
+
595
+ /** Windows: a `.cmd` file (working folder, environment, log) and a Task Scheduler task that runs it as the signed-in user. */
596
+ function planWindows(job: JobSpec, t: Target): Result<JobPlan, ScheduleError> {
597
+ const task = `${job.owner.folder}\\${job.name}`;
598
+ if (t.home.includes('"') || t.home.includes("%"))
599
+ return err(unsafe("home", "a double quote or a % in the home folder cannot be carried in a task's command"));
600
+ if (!WINDOWS_ABSOLUTE.test(job.workdir))
601
+ return err(invalid("workdir", "the working folder must be an absolute path (C:\\... or \\\\server\\...)"));
602
+ const exec = quoteCmdArgs(job.argv);
603
+ if (exec.kind === "err") return exec;
604
+ const dir = cmdPath("workdir", job.workdir);
605
+ if (dir.kind === "err") return dir;
606
+ const env = each(Object.entries(job.env ?? {}), ([k, v]) => {
607
+ const q = cmdPath(`env.${k}`, `${k}=${v}`);
608
+ return q.kind === "err" ? q : ok(`set ${q.value}`);
609
+ });
610
+ if (env.kind === "err") return env;
611
+ let redirect = "";
612
+ if (job.log !== undefined) {
613
+ if (!WINDOWS_ABSOLUTE.test(job.log)) return err(invalid("log", "the log must be an absolute path"));
614
+ const l = cmdPath("log", job.log);
615
+ if (l.kind === "err") return l;
616
+ redirect = ` >> ${l.value} 2>&1`;
617
+ }
618
+ const content = [
619
+ "@echo off",
620
+ `rem The scheduled job ${task}, written by a program: it is replaced when the job is scheduled again.`,
621
+ "setlocal DisableDelayedExpansion",
622
+ "chcp 65001 >nul",
623
+ `cd /d ${dir.value} || exit /b 1`,
624
+ ...env.value,
625
+ `${exec.value}${redirect}`,
626
+ "exit /b %ERRORLEVEL%",
627
+ "",
628
+ ].join("\r\n");
629
+ const rel = `AppData/Local/${job.owner.folder}/${job.name}.cmd`;
630
+ return ok({
631
+ os: "windows",
632
+ label: task,
633
+ description: describeSchedule(job.when),
634
+ files: [{ path: rel, content }],
635
+ install: [
636
+ { argv: ["schtasks", "/Create", "/F", "/TN", task, "/TR", `"${onTarget(t, rel)}"`, ...schtasksSchedule(job.when)], mayFail: false },
637
+ ],
638
+ remove: [{ argv: ["schtasks", "/Delete", "/F", "/TN", task], mayFail: true }],
639
+ afterRemove: [],
640
+ });
641
+ }
642
+
643
+ /**
644
+ * What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run
645
+ * by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.
646
+ */
647
+ export function planJob(job: JobSpec, target: Target): Result<JobPlan, ScheduleError> {
648
+ const common = checkCommon(job, target);
649
+ if (common !== undefined) return err(common);
650
+ switch (target.os) {
651
+ case "linux":
652
+ return planLinux(job);
653
+ case "darwin":
654
+ return planDarwin(job, target);
655
+ case "windows":
656
+ return planWindows(job, target);
657
+ default:
658
+ return absurd(target.os);
659
+ }
660
+ }