IF Commons GitHub

job-plan

Written to: 1 requirement: 1 proved, 0 partly, 0 failing, 0 with no test recorded. 0001-system FR-017

The operating system's own scheduled job, planned without touching it (commons 0001-system FR-017): from a job's name, the argument vector it runs, its working folder, its environment and when it runs, planJob gives the files to write and the commands that load and unload the job, for one of three schedulers, and writes or runs nothing itself (runtime/schedule.ts does).

OSwhat is plannedloaded by
Linuxa systemd user service (one shot) and its timer in ~/.config/systemd/user/systemctl --user enable --now <label>.timer
macOSa LaunchAgent, ~/Library/LaunchAgents/<label>.plistlaunchctl bootstrap gui/<uid> <plist>
Windowsa .cmd file in ~\AppData\Local\<folder>\ and a Task Scheduler taskschtasks /Create /F /TN <folder>\<name> /TR ...

The caller names its jobs with an owner: a reverse-DNS domain (org.example.backup), which makes the launchd label and the systemd unit <domain>.<name>, and a Task Scheduler folder (Example), which makes the task <folder>\<name> and the folder of its .cmd 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 absolute paths the commands need (the plist for launchctl, the .cmd file for schtasks) are built from the given home folder with the target's own separator.

When a job runs is one of five kinds, each expressed on every scheduler at the same minutes of local time:

kindsystemd OnCalendar=launchd StartCalendarIntervalschtasks
minutes*-*-* *:00/N:00one Minute dict for each of 0, N, 2N../SC MINUTE /MO N /ST 00:00
hourly*-*-* *:MM:00Minute/SC HOURLY /ST 00:MM
daily*-*-* HH:MM:00Hour, Minute/SC DAILY /ST HH:MM
weeklyFri *-*-* HH:MM:00Weekday (0 is Sunday), Hour, Minute/SC WEEKLY /D FRI /ST HH:MM
monthly*-*-DD HH:MM:00Day, Hour, Minute/SC MONTHLY /D DD /ST HH:MM

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 hour; monthly takes a day from 1 to 28, which every month has.

Every argument is quoted for the file that carries it, and what cannot be carried safely is refused with a ScheduleError, never altered. systemd's ExecStart= and Environment= get double quotes with C escapes (\\, \", \t, \xHH), %% for % and, in ExecStart=, $$ for $; a carriage return, a line feed or NUL is refused, and so is an argument that is only ; and a program that begins with one of systemd's prefixes (@-:+!|). The .cmd file gets double quotes around any argument that is not plain, %% for % (a batch file's own escape, inside quotes or not), the trailing backslashes of a quoted argument doubled (the C runtime's rule), delayed 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 control character but tab are refused. The plist is written with the kernel's XML writer, which escapes the markup; a character XML 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 refused.

Taken from Stolos's src/archon/export/schedule.ts (spec 092), which built the jobs of stolos export schedule from an export job and a fleet. What changed: the job is generic (an argument vector, a working folder, an environment, an optional log) and named by the caller's owner instead of Stolos's; the schedule is a discriminated union, with every N minutes added; the files are relative to the 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 quoted a few characters; and errors are values.

import { jobName, planJob, schedule } from "./job-plan.ts";
const name = jobName("backup");
const when = schedule({ kind: "daily", hour: 6, minute: 10 });
if (name.kind === "ok" && when.kind === "ok") {
  const plan = planJob(
    { name: name.value, owner: { domain: "org.example", folder: "Example" }, argv: ["/usr/bin/backup", "--all"], workdir: "/srv", when: when.value },
    { os: "linux", home: "/home/ada" },
  );
  // plan.value.files: .config/systemd/user/org.example.backup.service and .timer, with OnCalendar=*-*-* 06:10:00
  // plan.value.install: systemctl --user daemon-reload, then systemctl --user enable --now org.example.backup.timer
}

Source: commons/system/src/job-plan.ts

19 of 51 exports are imported by a test of the run. A test that imports an export may not call it or check what it returns.

jobPlannamespace
namespace jobPlan
jobPlan.SchedulerOstypeno test imports it
type SchedulerOs = "linux" | "darwin" | "windows";

The schedulers a job can be planned for: systemd on Linux, launchd on macOS, Task Scheduler on Windows.

jobPlan.ScheduleErrortypeno test imports it
type ScheduleError = {
  readonly kind: "schedule";
  readonly field: string;
  readonly reason: "invalid" | "unsafe";
  readonly message: string;
};

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.

jobPlan.formatScheduleErrorfunctionno test imports it
function formatScheduleError(e: ScheduleError): string

A schedule error as one line: argv[1]: a line feed cannot be carried in a systemd unit.

jobPlan.JobNametypeno test imports it
type JobName = Brand<string, "JobName">;

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.

jobPlan.jobNamefunctionno test imports it
function jobName(s: string): Result<JobName, ScheduleError>

A job's name, validated.

jobPlan.Weekdaytypeno test imports it
type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";

The day of a weekly schedule.

jobPlan.Whentypeno test imports it
type When = | { readonly kind: "minutes"; readonly every: number } | { readonly kind: "hourly"; readonly minute: num… (411 characters)
type When =
  | { readonly kind: "minutes"; readonly every: number }
  | { readonly kind: "hourly"; readonly minute: number }
  | { readonly kind: "daily"; readonly hour: number; readonly minute: number }
  | { readonly kind: "weekly"; readonly day: Weekday; readonly hour: number; readonly minute: number }
  | { readonly kind: "monthly"; readonly day: number; readonly hour: number; readonly minute: number };

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.

jobPlan.Scheduletypeno test imports it
type Schedule = Brand<When, "Schedule">;

A When whose numbers are in range, made only by schedule.

jobPlan.MINUTE_STEPSconstno test imports it
const MINUTE_STEPS: readonly number[]

The intervals minutes takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour.

jobPlan.schedulefunctionno test imports it
function schedule(when: When): Result<Schedule, ScheduleError>

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.

jobPlan.describeSchedulefunctionno test imports it
function describeSchedule(s: Schedule): string

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.

jobPlan.onCalendarfunctionno test imports it
function onCalendar(s: Schedule): string

systemd's OnCalendar= expression for a schedule (systemd.time(7)).

jobPlan.CalendarIntervaltypeno test imports it
type CalendarInterval = { readonly Minute: number; readonly Hour?: number; readonly Day?: number; readonly Weekday?: number };

One launchd calendar interval: the job runs whenever every key given matches (Weekday 0 is Sunday).

jobPlan.calendarIntervalsfunctionno test imports it
function calendarIntervals(s: Schedule): readonly CalendarInterval[]

launchd's StartCalendarInterval for a schedule: one interval, or one for each minute of the hour the job runs at.

jobPlan.schtasksSchedulefunctionno test imports it
function schtasksSchedule(s: Schedule): readonly string[]

The arguments schtasks /Create takes for a schedule, from /SC on.

jobPlan.quoteSystemdArgfunctionno test imports it
function quoteSystemdArg(arg: string, first?: boolean): Result<string, ScheduleError>

One argument as a word of systemd's ExecStart= (systemd.service(5), "Command lines"): as it is where it is plain, else in double quotes with C escapes, %% for a specifier's % and $$ for a variable's $. Refused: NUL, a carriage return or a line feed; an argument that is only ; (a command separator); and, for the program (first), an empty one or one that begins with a prefix character (@-:+!|).

jobPlan.quoteSystemdArgsfunctionno test imports it
function quoteSystemdArgs(argv: readonly string[]): Result<string, ScheduleError>

An argument vector as systemd's ExecStart= value, each word quoted by quoteSystemdArg; the first refusal names its index.

jobPlan.quoteCmdArgfunctionno test imports it
function quoteCmdArg(arg: string, first?: boolean): Result<string, ScheduleError>

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 cmd.exe takes &|<>^() as text; %% for % (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, first, whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character but tab; and, for the program, an empty one. Expects delayed expansion off (the .cmd file turns it off), so ! is plain text.

jobPlan.quoteCmdArgsfunctionno test imports it
function quoteCmdArgs(argv: readonly string[]): Result<string, ScheduleError>

An argument vector as a command of a .cmd file, each word quoted by quoteCmdArg; the first refusal names its index.

jobPlan.JobOwnertypeno test imports it
type JobOwner = {
  /** Lowercase labels of letters, digits and dashes, two or more, joined by dots (`org.example.backup`). */
  readonly domain: string;
  /** Letters, digits, dots, dashes and underscores, beginning and ending with a letter or digit (`Example`). */
  readonly folder: string;
};

Who a job belongs to: a reverse-DNS domain for the launchd label and the systemd unit, and a Task Scheduler folder.

jobPlan.JobSpectypeno test imports it
type JobSpec = { /** Its name, unique under its owner. */ readonly name: JobName; /** Its owner, which makes its l… (703 characters)
type JobSpec = {
  /** Its name, unique under its owner. */
  readonly name: JobName;
  /** Its owner, which makes its label and where its files go. */
  readonly owner: JobOwner;
  /** The program and its arguments, run without a shell (by the scheduler, or by the `.cmd` file on Windows). */
  readonly argv: readonly string[];
  /** The absolute folder it runs in. */
  readonly workdir: string;
  /** Variables added to its environment. */
  readonly env?: Readonly<Record<string, string>>;
  /** When it runs. */
  readonly when: Schedule;
  /** An absolute file its output and errors are appended to (systemd's journal, and nothing on macOS and Windows, without it). */
  readonly log?: string;
};

A job to schedule.

jobPlan.Targettypeno test imports it
type Target = { readonly os: SchedulerOs; readonly home: string; readonly uid?: number };

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).

jobPlan.PlannedFiletypeno test imports it
type PlannedFile = { readonly path: string; readonly content: string; readonly mode?: number };

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).

jobPlan.Steptypeno test imports it
type Step = { readonly argv: readonly string[]; readonly mayFail: boolean };

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).

jobPlan.JobPlantypeno test imports it
type JobPlan = { /** The scheduler. */ readonly os: SchedulerOs; /** The job's label: the systemd timer, the launc… (695 characters)
type JobPlan = {
  /** The scheduler. */
  readonly os: SchedulerOs;
  /** The job's label: the systemd timer, the launchd label, or the task's name. */
  readonly label: string;
  /** When it runs, in words. */
  readonly description: string;
  /** The files to write before `install`, and to remove after `remove`. */
  readonly files: readonly PlannedFile[];
  /** The commands that load and enable the job. */
  readonly install: readonly Step[];
  /** The commands that disable and unload it, before its files are removed. */
  readonly remove: readonly Step[];
  /** The commands to run once its files are removed (systemd forgets the units). */
  readonly afterRemove: readonly Step[];
};

What scheduling a job takes: the files to write, then install; to remove it, remove, then the files removed, then afterRemove.

jobPlan.planJobfunctionno test imports it
function planJob(job: JobSpec, target: Target): Result<JobPlan, ScheduleError>

What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.

SchedulerOstype
type SchedulerOs = "linux" | "darwin" | "windows";

The schedulers a job can be planned for: systemd on Linux, launchd on macOS, Task Scheduler on Windows.

Imported by 6 tests of the run (6 passed, 0 failed): the library's results

ScheduleErrortype
type ScheduleError = {
  readonly kind: "schedule";
  readonly field: string;
  readonly reason: "invalid" | "unsafe";
  readonly message: string;
};

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.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

formatScheduleErrorfunction
function formatScheduleError(e: ScheduleError): string

A schedule error as one line: argv[1]: a line feed cannot be carried in a systemd unit.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

JobNametype
type JobName = Brand<string, "JobName">;

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.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

jobNamefunction
function jobName(s: string): Result<JobName, ScheduleError>

A job's name, validated.

Imported by 18 tests of the run (18 passed, 0 failed): the library's results

Weekdaytype
type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";

The day of a weekly schedule.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

Whentype
type When = | { readonly kind: "minutes"; readonly every: number } | { readonly kind: "hourly"; readonly minute: num… (411 characters)
type When =
  | { readonly kind: "minutes"; readonly every: number }
  | { readonly kind: "hourly"; readonly minute: number }
  | { readonly kind: "daily"; readonly hour: number; readonly minute: number }
  | { readonly kind: "weekly"; readonly day: Weekday; readonly hour: number; readonly minute: number }
  | { readonly kind: "monthly"; readonly day: number; readonly hour: number; readonly minute: number };

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.

Imported by 18 tests of the run (18 passed, 0 failed): the library's results

Scheduletype
type Schedule = Brand<When, "Schedule">;

A When whose numbers are in range, made only by schedule.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

MINUTE_STEPSconst
const MINUTE_STEPS: readonly number[]

The intervals minutes takes: the divisors of 60 below 60, so every scheduler runs the job at the same minutes of every hour.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

schedulefunction
function schedule(when: When): Result<Schedule, ScheduleError>

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.

Imported by 18 tests of the run (18 passed, 0 failed): the library's results

describeSchedulefunction
function describeSchedule(s: Schedule): string

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.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

onCalendarfunction
function onCalendar(s: Schedule): string

systemd's OnCalendar= expression for a schedule (systemd.time(7)).

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

CalendarIntervaltypeno test imports it
type CalendarInterval = { readonly Minute: number; readonly Hour?: number; readonly Day?: number; readonly Weekday?: number };

One launchd calendar interval: the job runs whenever every key given matches (Weekday 0 is Sunday).

calendarIntervalsfunction
function calendarIntervals(s: Schedule): readonly CalendarInterval[]

launchd's StartCalendarInterval for a schedule: one interval, or one for each minute of the hour the job runs at.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

schtasksSchedulefunction
function schtasksSchedule(s: Schedule): readonly string[]

The arguments schtasks /Create takes for a schedule, from /SC on.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

quoteSystemdArgfunctionno test imports it
function quoteSystemdArg(arg: string, first?: boolean): Result<string, ScheduleError>

One argument as a word of systemd's ExecStart= (systemd.service(5), "Command lines"): as it is where it is plain, else in double quotes with C escapes, %% for a specifier's % and $$ for a variable's $. Refused: NUL, a carriage return or a line feed; an argument that is only ; (a command separator); and, for the program (first), an empty one or one that begins with a prefix character (@-:+!|).

quoteSystemdArgsfunction
function quoteSystemdArgs(argv: readonly string[]): Result<string, ScheduleError>

An argument vector as systemd's ExecStart= value, each word quoted by quoteSystemdArg; the first refusal names its index.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

quoteCmdArgfunctionno test imports it
function quoteCmdArg(arg: string, first?: boolean): Result<string, ScheduleError>

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 cmd.exe takes &|<>^() as text; %% for % (a batch file's escape, which holds inside quotes too); and the trailing backslashes of a quoted argument doubled, so the C runtime's parser does not read the closing quote as an escaped one (not for the program, first, whose name the parser takes as written). Refused: a double quote, which cmd.exe's quoting cannot hold safely, and any control character but tab; and, for the program, an empty one. Expects delayed expansion off (the .cmd file turns it off), so ! is plain text.

quoteCmdArgsfunction
function quoteCmdArgs(argv: readonly string[]): Result<string, ScheduleError>

An argument vector as a command of a .cmd file, each word quoted by quoteCmdArg; the first refusal names its index.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

JobOwnertypeno test imports it
type JobOwner = {
  /** Lowercase labels of letters, digits and dashes, two or more, joined by dots (`org.example.backup`). */
  readonly domain: string;
  /** Letters, digits, dots, dashes and underscores, beginning and ending with a letter or digit (`Example`). */
  readonly folder: string;
};

Who a job belongs to: a reverse-DNS domain for the launchd label and the systemd unit, and a Task Scheduler folder.

JobSpectype
type JobSpec = { /** Its name, unique under its owner. */ readonly name: JobName; /** Its owner, which makes its l… (703 characters)
type JobSpec = {
  /** Its name, unique under its owner. */
  readonly name: JobName;
  /** Its owner, which makes its label and where its files go. */
  readonly owner: JobOwner;
  /** The program and its arguments, run without a shell (by the scheduler, or by the `.cmd` file on Windows). */
  readonly argv: readonly string[];
  /** The absolute folder it runs in. */
  readonly workdir: string;
  /** Variables added to its environment. */
  readonly env?: Readonly<Record<string, string>>;
  /** When it runs. */
  readonly when: Schedule;
  /** An absolute file its output and errors are appended to (systemd's journal, and nothing on macOS and Windows, without it). */
  readonly log?: string;
};

A job to schedule.

Imported by 18 tests of the run (18 passed, 0 failed): the library's results

PlannedFiletypeno test imports it
type PlannedFile = { readonly path: string; readonly content: string; readonly mode?: number };

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).

Steptypeno test imports it
type Step = { readonly argv: readonly string[]; readonly mayFail: boolean };

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).

JobPlantype
type JobPlan = { /** The scheduler. */ readonly os: SchedulerOs; /** The job's label: the systemd timer, the launc… (695 characters)
type JobPlan = {
  /** The scheduler. */
  readonly os: SchedulerOs;
  /** The job's label: the systemd timer, the launchd label, or the task's name. */
  readonly label: string;
  /** When it runs, in words. */
  readonly description: string;
  /** The files to write before `install`, and to remove after `remove`. */
  readonly files: readonly PlannedFile[];
  /** The commands that load and enable the job. */
  readonly install: readonly Step[];
  /** The commands that disable and unload it, before its files are removed. */
  readonly remove: readonly Step[];
  /** The commands to run once its files are removed (systemd forgets the units). */
  readonly afterRemove: readonly Step[];
};

What scheduling a job takes: the files to write, then install; to remove it, remove, then the files removed, then afterRemove.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

planJobfunction
function planJob(job: JobSpec, target: Target): Result<JobPlan, ScheduleError>

What scheduling a job on a computer takes: the files (relative to the home folder) and the commands, built and checked, written and run by nothing here. A value that is not valid, or that a file cannot carry safely, is an error naming the field.

Imported by 18 tests of the run (18 passed, 0 failed): the library's results

Titles, headings, exports, tables, columns and requirements. Esc closes.