deployontime 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,95 @@
1
+ // Job kinds and command stems. The kind groups similar jobs for the run limit; the stem tells runs of one command
2
+ // apart from runs of another. Both are read from the label and the command line only.
3
+ import { SHELLS, TEST_KIND_RE } from "./commands.mjs";
4
+ import { labelTask } from "./project.mjs";
5
+
6
+ /** The label a job gets when --label is missing. The repeated-failure stop never takes two such jobs for one check. */
7
+ export const UNLABELLED = "unnamed";
8
+
9
+ const DEBUG_WORDS = "debug|repro|bisect|probe";
10
+ export const DEBUG_LABEL_RE = new RegExp(`\\b(${DEBUG_WORDS})\\b|\\?`, "i");
11
+ // In a command the word must not be followed by "=", so setting a DEBUG variable does not make a debug job.
12
+ export const DEBUG_CMD_RE = new RegExp(`\\b(${DEBUG_WORDS})\\b(?!=)`, "i");
13
+
14
+ // Ordered from heaviest to lightest; the first match wins.
15
+ export const KINDS = [
16
+ ["deploy", /\b(deploy|release|publish)\b/i],
17
+ ["test", TEST_KIND_RE],
18
+ ["build", /\b(build|bundle|compile)\b/i],
19
+ ["lint", /\b(lint|typecheck|tsc|format)\b/i],
20
+ ];
21
+ /** A given kind wins. Otherwise the label's task part is read first, then the command, and in each a debug word
22
+ * comes before KINDS; "other" when nothing matches. */
23
+ export function kindOf(label, command, given) {
24
+ if (given) return String(given).toLowerCase();
25
+ for (const [text, debugRe] of [[labelTask(label), DEBUG_LABEL_RE], [String(command ?? ""), DEBUG_CMD_RE]]) {
26
+ if (debugRe.test(text)) return "debug";
27
+ const hit = KINDS.find(([, pattern]) => pattern.test(text));
28
+ if (hit) return hit[0];
29
+ }
30
+ return "other";
31
+ }
32
+
33
+ // Words that make or ship output, matched anywhere inside a word, so prebuild, esbuild, deploy_prod.sh and
34
+ // deployProd all count. Matching too much only means a check runs again; matching too little loses output.
35
+ const MAKES_WITHIN_WORDS = /build|bundle|compile|deploy|release|publish|webpack|rollup|parcel/i;
36
+ // tsc writes its output unless told not to; vercel and netlify ship with --prod.
37
+ const TSC_RE = /(^|[^a-z0-9])tsc([^a-z0-9]|$)/i;
38
+ const NO_EMIT_RE = /--noEmit\b/i;
39
+ const SHIPS_RE = /\b(vercel|netlify)\b[^&|;]*--prod\b/i;
40
+ /** Does the label's task part or the command also name a build or a deploy, whatever kind won? "build and test" is a
41
+ * test job by the order of KINDS, but its build output may still be needed. Besides the build and deploy words, even
42
+ * inside other words, this counts webpack, rollup and parcel, tsc without --noEmit, and vercel or netlify with
43
+ * --prod. When in doubt it answers true. */
44
+ export function alsoBuilds(label, command) {
45
+ return [labelTask(label), String(command ?? "")].some((text) => MAKES_WITHIN_WORDS.test(text)
46
+ || (TSC_RE.test(text) && !NO_EMIT_RE.test(text)) || SHIPS_RE.test(text));
47
+ }
48
+
49
+ // The stem is what stays the same between two runs of one command: the program and the task it is given, without
50
+ // paths, flags or variable assignments. Runs are compared with earlier runs that have the same stem.
51
+
52
+ const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn"]);
53
+ const TOOL_RUNNERS = new Set(["npx", "pnpx", "bunx"]);
54
+ const INTERPRETERS = new Set(["node", "tsx", "ts-node", "vite-node", "bun", "deno", "python", "python3", ...SHELLS]);
55
+ const INLINE_CODE_FLAGS = new Set(["-e", "-c", "--eval"]);
56
+ const baseName = (word) => String(word).split("/").pop();
57
+ const isPlainWord = (word) => /^[a-z][\w:.-]*$/i.test(word);
58
+
59
+ function splitWords(line) {
60
+ const words = String(line ?? "").match(/"(?:[^"\\]|\\.)*"|\S+/g) ?? [];
61
+ return words.map((word) => {
62
+ if (!word.startsWith('"')) return word;
63
+ try { return JSON.parse(word); } catch { return word; }
64
+ });
65
+ }
66
+ function stemOfWords(words) {
67
+ let first = 0;
68
+ while (first < words.length && (words[first] === "env" || /^[A-Za-z_]\w*=/.test(words[first]))) first++;
69
+ const program = baseName(words[first] ?? "");
70
+ if (!program) return null;
71
+ const args = words.slice(first + 1).filter((word) => !word.startsWith("-") || INLINE_CODE_FLAGS.has(word));
72
+ if (SHELLS.has(program) && args[0] === "-c") {
73
+ // sh -c "a && b": stem each chained command, then join.
74
+ const parts = String(args[1] ?? "").split(/&&|\|\||[;|]/).map((part) => stemOfWords(splitWords(part.trim())));
75
+ return parts.filter(Boolean).join(" && ") || null;
76
+ }
77
+ if (INLINE_CODE_FLAGS.has(args[0])) return null;
78
+ if (PACKAGE_MANAGERS.has(program)) {
79
+ const words = args[0] === "run" || args[0] === "exec" ? 2 : 1;
80
+ return [program, ...args.slice(0, words)].join(" ");
81
+ }
82
+ if (TOOL_RUNNERS.has(program)) {
83
+ if (INTERPRETERS.has(args[0])) return [program, args[0], ...args.slice(1, 2).map(baseName)].join(" ");
84
+ return [program, ...args.slice(0, 1), ...args.slice(1, 2).filter(isPlainWord)].join(" ");
85
+ }
86
+ if (INTERPRETERS.has(program)) return [program, ...args.slice(0, 1).map(baseName)].join(" ");
87
+ return [program, ...args.slice(0, 1).filter(isPlainWord)].join(" ");
88
+ }
89
+ const stemCache = new Map();
90
+ /** The stem of a command line as written by cmdString(), or null when it has none (inline code, empty line). */
91
+ export function cmdStem(command) {
92
+ const line = String(command ?? "");
93
+ if (!stemCache.has(line)) stemCache.set(line, stemOfWords(splitWords(line)) || null);
94
+ return stemCache.get(line);
95
+ }
@@ -0,0 +1,79 @@
1
+ // Run limits. A limit is taken from the journal: from earlier runs of the same command when there are enough, else
2
+ // from runs of the same kind, else from a default. An unreadable journal counts as no history and never holds a job
3
+ // back.
4
+ import { lineProject, parseLines } from "./journal.mjs";
5
+ import { cmdStem, kindOf } from "./kinds.mjs";
6
+ import { pctl } from "./stats.mjs";
7
+ import { DAY, oneDecimal } from "./units.mjs";
8
+
9
+ function passedRuns(lines, { project, now, windowDays }) {
10
+ const oldest = now - windowDays * DAY;
11
+ return parseLines(lines).filter((row) => {
12
+ const ended = Date.parse(row.endedAt);
13
+ const inWindow = ended >= oldest && ended <= now;
14
+ return lineProject(row) === project && row.outcome === "ran" && row.exit === 0 && inWindow;
15
+ });
16
+ }
17
+ const runTimes = (rows) => rows.map((row) => row.runMin ?? 0);
18
+ /** Returns { n, p75, p90 } in minutes, over passed runs of one kind in one project. */
19
+ export function kindStats(lines, { project, kind, now = Date.now(), windowDays }) {
20
+ const ofKind = (row) => (row.kind ?? kindOf(row.label, row.cmd)) === kind;
21
+ const times = runTimes(passedRuns(lines, { project, now, windowDays }).filter(ofKind));
22
+ return { n: times.length, p75: pctl(times, 0.75), p90: pctl(times, 0.9) };
23
+ }
24
+ /** Returns { n, p75, p90, max, stem } in minutes, over passed runs with one command stem in one project. */
25
+ export function stemStats(lines, { project, stem, now = Date.now(), windowDays }) {
26
+ if (!stem) return { n: 0, stem: null };
27
+ const times = runTimes(passedRuns(lines, { project, now, windowDays }).filter((row) => cmdStem(row.cmd) === stem));
28
+ const max = times.length ? Math.max(...times) : null;
29
+ return { n: times.length, p75: pctl(times, 0.75), p90: pctl(times, 0.9), max, stem };
30
+ }
31
+
32
+ /** Picks the run limit and the long-run mark for a job. Returns { limitMin, basis, longRunMin, longRunBasis,
33
+ * killMin, notifyLongRun }; killMin is when the job is stopped. */
34
+ export function decideLimit(job, limitSettings) {
35
+ const { maxRun = null, kind, stats = { n: 0 }, stem = null, priority = false } = job;
36
+ const { minSamples, p90Factor, floorMin, longRunFactor, longRunUnmeasuredMin } = limitSettings;
37
+ const ownHistory = (stem?.n ?? 0) >= minSamples;
38
+ const source = ownHistory ? stem : stats;
39
+ const subject = ownHistory ? `command "${stem.stem}"` : `kind ${kind}`;
40
+ const measured = source.n >= minSamples;
41
+ const fixed = maxRun != null || kind === "debug";
42
+ let limitMin;
43
+ let basis;
44
+ if (maxRun != null) {
45
+ limitMin = maxRun;
46
+ basis = "the --max-run flag";
47
+ } else if (kind === "debug") {
48
+ limitMin = limitSettings.debugMin;
49
+ basis = "the debug-job setting";
50
+ } else if (measured) {
51
+ const fromRuns = oneDecimal(source.p90 * p90Factor);
52
+ const lifted = fromRuns < floorMin ? `, lifted to the ${floorMin} min minimum` : "";
53
+ limitMin = Math.max(floorMin, fromRuns);
54
+ basis = `${source.n} passed runs of ${subject} (${p90Factor} times their p90 of ${source.p90} min${lifted})`;
55
+ } else {
56
+ limitMin = limitSettings.defaultMin;
57
+ basis = `the default (${source.n} of the ${minSamples} passed runs needed for ${subject})`;
58
+ }
59
+ const markFrom = (s, what) => `${longRunFactor} times the p75 of ${s.p75} min over ${s.n} passed runs of ${what}`;
60
+ let longRunMin = measured ? Math.max(floorMin, oneDecimal(source.p75 * longRunFactor)) : longRunUnmeasuredMin;
61
+ const unmeasured = `the ${longRunUnmeasuredMin} min setting for jobs without history`;
62
+ let longRunBasis = measured ? markFrom(source, subject) : unmeasured;
63
+ // A command with only a few runs cannot set the limit, but it may raise one that its own runs already exceed.
64
+ if (!ownHistory && stem?.n > 0) {
65
+ const fromLongest = oneDecimal(stem.max * p90Factor);
66
+ const ownMark = oneDecimal(stem.p75 * longRunFactor);
67
+ if (!fixed && fromLongest > limitMin) {
68
+ limitMin = fromLongest;
69
+ basis = `${stem.max} min, the longest passed run of command "${stem.stem}" (${stem.n} on record), `
70
+ + `times ${p90Factor}; that is more than ${basis}`;
71
+ }
72
+ if (ownMark > longRunMin) {
73
+ longRunMin = ownMark;
74
+ longRunBasis = markFrom(stem, `command "${stem.stem}"`);
75
+ }
76
+ }
77
+ const killMin = priority ? limitMin * limitSettings.priorityGrace : limitMin;
78
+ return { limitMin, basis, longRunMin, longRunBasis, killMin, notifyLongRun: longRunMin < killMin };
79
+ }
@@ -0,0 +1,72 @@
1
+ // Readings that Linux keeps in files under /proc and /sys, with the parsing kept apart so it can be tested on sample
2
+ // text. A file that is missing or cannot be read gives empty text, and a reading that cannot be made gives null, the
3
+ // same way a missing tool does on macOS.
4
+ import { readdirSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ /** The text of a file, or empty text when it is missing or cannot be read. */
8
+ export function readText(file) {
9
+ try { return readFileSync(file, "utf8"); } catch { return ""; }
10
+ }
11
+
12
+ /** Parses /proc/meminfo into a Map from field name to its value in kB. */
13
+ export function parseMeminfo(text) {
14
+ const fields = new Map();
15
+ for (const line of String(text ?? "").split("\n")) {
16
+ const found = line.match(/^(\w+):\s+(\d+)(?:\s+kB)?\s*$/);
17
+ if (found) fields.set(found[1], Number(found[2]));
18
+ }
19
+ return fields;
20
+ }
21
+
22
+ /** The share of memory still available to new work, as a whole percent, or null when /proc/meminfo has no
23
+ * MemAvailable and MemTotal line. */
24
+ export function meminfoFreePct(fields) {
25
+ const total = fields.get("MemTotal"), available = fields.get("MemAvailable");
26
+ if (!(total > 0) || !Number.isFinite(available)) return null;
27
+ return Math.round(Math.min(available, total) / total * 100);
28
+ }
29
+
30
+ /** The share of swap in use, in percent: 0 without swap or without the swap lines, as on macOS. */
31
+ export function meminfoSwapPct(fields) {
32
+ const total = fields.get("SwapTotal"), free = fields.get("SwapFree");
33
+ if (!(total > 0) || !Number.isFinite(free)) return 0;
34
+ return Math.max(0, total - free) / total * 100;
35
+ }
36
+
37
+ export const POWER_SUPPLY_DIR = "/sys/class/power_supply";
38
+ const SUPPLY_FILES = ["type", "scope", "online", "capacity", "status"];
39
+
40
+ /** Every power supply in dir, as [{ name, type, scope, online, capacity, status }] with each file's text trimmed
41
+ * ("" when the file is missing). An empty list when the folder cannot be read. */
42
+ export function readPowerSupplies(dir = POWER_SUPPLY_DIR, { list = readdirSync, read = readText } = {}) {
43
+ let names;
44
+ try { names = list(dir).sort(); } catch { return []; }
45
+ return names.map((name) => ({
46
+ name, ...Object.fromEntries(SUPPLY_FILES.map((file) => [file, read(join(dir, name, file)).trim()])),
47
+ }));
48
+ }
49
+
50
+ // A battery or charger of a mouse, keyboard or phone has the scope "Device"; only the computer's own supplies count.
51
+ const own = (supply) => supply.scope !== "Device";
52
+ const CHARGER_STATES = new Set(["Charging", "Full", "Not charging"]);
53
+
54
+ /** The battery reading for the gate from the power supplies: { onBattery, pct, plugged }, or null without a battery
55
+ * of the computer's own (a server or desktop) or when its state is unknown. Several batteries count as one: the
56
+ * mean charge, and on battery while any of them is discharging. A computer that is plugged in and still
57
+ * discharges counts as on battery, as on macOS. */
58
+ export function supplyBattery(supplies) {
59
+ const batteries = supplies.filter((s) => own(s) && s.type === "Battery" && /^\d{1,3}$/.test(s.capacity));
60
+ if (!batteries.length) return null;
61
+ const chargers = supplies.filter((s) => own(s) && s.type !== "Battery" && /^[01]$/.test(s.online));
62
+ const discharging = batteries.some((b) => b.status === "Discharging");
63
+ const charging = batteries.some((b) => CHARGER_STATES.has(b.status));
64
+ const plugged = chargers.length ? chargers.some((c) => c.online === "1") : charging;
65
+ let onBattery = null;
66
+ if (discharging) onBattery = true;
67
+ else if (charging || plugged) onBattery = false;
68
+ else if (chargers.length) onBattery = true;
69
+ if (onBattery == null) return null;
70
+ const pct = Math.round(batteries.reduce((sum, b) => sum + Number(b.capacity), 0) / batteries.length);
71
+ return { onBattery, pct, plugged };
72
+ }
@@ -0,0 +1,83 @@
1
+ // Nested runs: a job started by the queue that itself calls `dotime-queue run`. The queue puts two markers in the job's
2
+ // environment: one that names the slot of the outermost job, as every copy of the queue reads it, and one that names
3
+ // the job's direct parent: that same slot, or for a job of a nested run that run's own note in the nested folder. A
4
+ // run that finds a marker is nested in that job, its parent: it takes no slot, but waits for one of the parent's few
5
+ // places for nested runs. That holds only while the marker is genuine: the slot or note it names is held by a job that
6
+ // has started, and the process holding it is one of the run's own ancestors. Anything else, such as a marker copied
7
+ // into another shell or left over from a job that has ended, is ignored, so the markers cannot be used to skip the
8
+ // line from outside.
9
+ import { basename } from "node:path";
10
+ import { probeProcessTree } from "./probes.mjs";
11
+ import { ancestors } from "./proctree.mjs";
12
+ import { psRows } from "./ps.mjs";
13
+
14
+ /** The environment variable that carries the marker of the outermost job's slot into a job. */
15
+ export const JOB_MARKER = "DOTIME_JOB";
16
+ /** The environment variable that carries the marker of a job's direct parent: a slot, or a nested run's note. */
17
+ export const PARENT_MARKER = "DOTIME_PARENT";
18
+ /** The environment variable that tells the runs nested in a job, at any depth, that the job was started with
19
+ * --no-skip, so they run too. It is set to "1" or left out, and only a nested run heeds it. */
20
+ export const NO_SKIP_MARKER = "DOTIME_NO_SKIP";
21
+
22
+ const SLOT_FORM = /^slot-\d+$/;
23
+ const NESTED_FORM = /^nested-\d+$/;
24
+
25
+ /** The marker of a slot file or a nested note: its name without the folder and the .json ending, such as "slot-0" or
26
+ * "nested-5104". */
27
+ export const markerOf = (file) => basename(file, ".json");
28
+
29
+ /** The key under which the places of a parent job are kept: its marker and start time, so a later job with the same
30
+ * marker never shares them. */
31
+ export const placeKey = (parent) => `${markerOf(parent.file)}.${parent.born}`;
32
+
33
+ // The slot file or note of a job the queue started names the queue process, above pid 1, with its start time and the
34
+ // process group of the job. A file that lacks any of these was not written by a job that runs, and is not trusted:
35
+ // pid 1 in particular is an ancestor of every process. A nested run that still waits for a place has no process
36
+ // group yet, so its marker is not trusted either.
37
+ const realHolder = (h) => Number.isInteger(h.pid) && h.pid > 1 && Number.isFinite(h.born) && Number.isInteger(h.pgid);
38
+
39
+ /** The job a run is nested in, its direct parent, or null. marker: the value of the marker variable; pid: the run's
40
+ * own pid; holders and nested: the slot holders and nested runs from snapshot(), each with its file; rows: process
41
+ * rows ({ pid, ppid }), by default a fresh listing. A marker that is missing or malformed, names a slot or note
42
+ * nobody holds or one whose file lacks the pid, start time or process group of a running job, or names one whose
43
+ * holder is not an ancestor of pid gives null. */
44
+ export function outerJob({ marker, pid, holders, nested = [], rows = null }) {
45
+ if (typeof marker !== "string") return null;
46
+ const pool = SLOT_FORM.test(marker) ? holders : NESTED_FORM.test(marker) ? nested : null;
47
+ if (!pool) return null;
48
+ const holder = pool.find((h) => markerOf(h.file) === marker);
49
+ if (!holder || !realHolder(holder) || holder.waiting) return null;
50
+ if (NESTED_FORM.test(marker) && marker !== `nested-${holder.pid}`) return null;
51
+ const above = ancestors(rows ?? psRows(probeProcessTree()), pid).slice(1);
52
+ return above.some((row) => row.pid === holder.pid) ? holder : null;
53
+ }
54
+
55
+ /** The job a run is nested in, from the markers in env, or null. The direct parent in PARENT_MARKER is tried first;
56
+ * when it is missing or not genuine, the slot in JOB_MARKER is, as a job started by a copy of the queue that sets
57
+ * only that one hands it on. JOB_MARKER is taken only in the form of a slot. pid, holders, nested and rows: as for
58
+ * outerJob(); the process table is read at most once. */
59
+ export function parentJob({ env, pid, holders, nested = [], rows = null }) {
60
+ const parentMarker = env?.[PARENT_MARKER], slotMarker = env?.[JOB_MARKER];
61
+ const asked = [parentMarker, typeof slotMarker === "string" && SLOT_FORM.test(slotMarker) ? slotMarker : undefined];
62
+ let listing = rows;
63
+ const table = () => (listing ??= psRows(probeProcessTree()));
64
+ for (const marker of asked) {
65
+ if (typeof marker !== "string" || !(SLOT_FORM.test(marker) || NESTED_FORM.test(marker))) continue;
66
+ const found = outerJob({ marker, pid, holders, nested, rows: table() });
67
+ if (found) return found;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /** The marker of the slot of the outermost job that parent, the job from outerJob(), runs in: its own slot, or the
73
+ * one its note names. */
74
+ export const slotMarkerOf = (parent) => (SLOT_FORM.test(markerOf(parent.file)) ? markerOf(parent.file) : parent.slot);
75
+
76
+ /** Whether parent, the job from outerJob(), still runs: its slot or note is there with the same pid and start time,
77
+ * and is still that of a running job. holders and nested: from snapshot(). Once the job has ended its file is gone,
78
+ * or belongs to a later job, and this gives false. */
79
+ export function stillRunning(parent, { holders, nested = [] }) {
80
+ const pool = SLOT_FORM.test(markerOf(parent.file)) ? holders : nested;
81
+ return pool.some((h) => h.file === parent.file && h.pid === parent.pid && h.born === parent.born && realHolder(h)
82
+ && !h.waiting);
83
+ }
@@ -0,0 +1,114 @@
1
+ // The long-run and idle-slot notices: their text, the per-slot CPU sampling that finds a quiet job, and the store
2
+ // of notices already sent, a folder in the state folder.
3
+ import { linkSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { clockTime } from "./clock.mjs";
6
+ import { tempName } from "./files.mjs";
7
+ import { sampleKeepMs, slotIdleVerdict } from "./idle.mjs";
8
+ import { probeProcessCpu } from "./probes.mjs";
9
+ import { jobCpu } from "./proctree.mjs";
10
+ import { psRows } from "./ps.mjs";
11
+ import { MINUTE } from "./units.mjs";
12
+
13
+ function heldUpText(waiting, now) {
14
+ if (!waiting.length) return "holding up no other job";
15
+ const waited = (w) => Math.max(0, Math.round((now - w.at) / MINUTE));
16
+ return `holding up ${waiting.map((w) => `"${w.label}" (${waited(w)} min)`).join(" and ")}`;
17
+ }
18
+ /** The notice for a job that passed its long-run mark. Returns { title, message, key, entry }. */
19
+ export function longRunAlert(job) {
20
+ const { label, project, pid, minutes, longRunBasis, limitMin, killMin, startedAt, tz } = job;
21
+ const { waiting = [], now = Date.now() } = job;
22
+ const heldUp = heldUpText(waiting, now);
23
+ const stopAt = clockTime(startedAt + killMin * MINUTE, tz);
24
+ return {
25
+ title: "dotime: job running long",
26
+ message: `long run: "${label}" of project ${project}, pid ${pid}, ${heldUp}, ${minutes} min in its slot, `
27
+ + `long-run mark from ${longRunBasis}, limit ${limitMin} min, hard stop at ${stopAt}`,
28
+ key: `long-run:${pid}:${startedAt}`,
29
+ entry: {
30
+ type: "long-run", project, label, pid, minutes,
31
+ detail: `mark from ${longRunBasis}, limit ${limitMin} min, hard stop at ${stopAt}`,
32
+ waiting: waiting.map((w) => w.label), at: now,
33
+ },
34
+ };
35
+ }
36
+ /** The notice for a job that holds a slot without using CPU. Returns { title, message, key, entry }. */
37
+ export function idleAlert(job) {
38
+ const { label, project, pid, usedS, minutes, startedAt, killMin = null, waiting = [], now = Date.now(), tz } = job;
39
+ const heldUp = heldUpText(waiting, now);
40
+ const use = `${usedS} s of CPU in ${minutes} min`;
41
+ const limit = killMin ? `, limit reached at ${clockTime(startedAt + killMin * MINUTE, tz)}` : "";
42
+ return {
43
+ title: "dotime: slot held by a quiet job",
44
+ message: `idle slot: "${label}" of project ${project}, pid ${pid}, ${heldUp}, ${use}, not stopped${limit}`,
45
+ key: `idle-slot:${pid}:${startedAt}`,
46
+ entry: {
47
+ type: "idle-slot", project, label, pid, minutes, usedS, detail: use,
48
+ waiting: waiting.map((w) => w.label), at: now,
49
+ },
50
+ };
51
+ }
52
+
53
+ /** Takes one CPU sample per slot holder and judges it. ps: text from `ps -S -Ao pid=,ppid=,pgid=,time=`;
54
+ * state: { "<pid>:<startedAt>": { samples, told } } from the previous call.
55
+ * Returns { state, alerts }: state for the holders still present; each job gets at most one alert. */
56
+ export function slotIdleStep({ holders, ps, state = {}, waiting = [], now = Date.now(), idle, tz }) {
57
+ const rows = psRows(ps);
58
+ const next = {};
59
+ const alerts = [];
60
+ const keepMs = sampleKeepMs(idle.slotIdleMin);
61
+ for (const holder of holders) {
62
+ const startedAt = holder.startedAt ?? holder.at;
63
+ const id = `${holder.pid}:${startedAt}`;
64
+ const cpu = jobCpu(holder, rows);
65
+ if (cpu == null) {
66
+ // Not in this process listing: carry the earlier samples forward untouched.
67
+ if (state[id]) next[id] = state[id];
68
+ continue;
69
+ }
70
+ const before = state[id] ?? { samples: [] };
71
+ const samples = [...before.samples, { t: now, cpu }].filter((s) => now - s.t <= keepMs);
72
+ const verdict = before.told ? null : slotIdleVerdict({ startedAt, samples, now }, idle);
73
+ if (verdict?.idle) {
74
+ alerts.push(idleAlert({
75
+ label: holder.label, project: holder.project ?? "unknown", pid: holder.pid, usedS: verdict.usedS,
76
+ minutes: verdict.minutes, startedAt, killMin: holder.killMin, waiting, now, tz,
77
+ }));
78
+ }
79
+ next[id] = { samples, ...(before.told || verdict?.idle ? { told: true } : {}) };
80
+ }
81
+ return { state: next, alerts };
82
+ }
83
+ /** slotIdleStep plus delivery of the new alerts. On a dry run nothing is sent. Returns { state, lines }. */
84
+ export function slotIdleCheck(check) {
85
+ const { holders, notify, record, idle, tz } = check;
86
+ const { waiting = [], state = {}, now = Date.now(), dry = false, ps = probeProcessCpu } = check;
87
+ const step = slotIdleStep({ holders, ps: holders.length ? ps() : "", state, waiting, now, idle, tz });
88
+ if (!dry) for (const alert of step.alerts) { notify(alert.title, alert.message); record(alert.key, alert.entry); }
89
+ const note = dry ? " (dry run, no notice sent)" : "";
90
+ return { state: step.state, lines: step.alerts.map((alert) => `${alert.message}${note}`) };
91
+ }
92
+
93
+ // The store holds one file per notice, named after its key. A notice is written under a temporary name and then
94
+ // linked into place, which fails when the file exists, so two processes that send notices at once never lose one,
95
+ // and the first of two with the same key wins.
96
+ const noticeFile = (dir, key) => join(dir, `${encodeURIComponent(key)}.json`);
97
+
98
+ /** Stores a notice in the notices folder of the state folder under its key. Returns true when it was added, false
99
+ * when the key exists or the file cannot be written. */
100
+ export function addNotice(key, entry, dir) {
101
+ let temp = null;
102
+ try {
103
+ const file = noticeFile(dir, key);
104
+ temp = tempName(file);
105
+ mkdirSync(dir, { recursive: true });
106
+ writeFileSync(temp, JSON.stringify(entry, null, 1));
107
+ linkSync(temp, file);
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ } finally {
112
+ try { if (temp) rmSync(temp, { force: true }); } catch { /* the folder itself could not be made */ }
113
+ }
114
+ }
@@ -0,0 +1,47 @@
1
+ // Sends a notice three ways: a line in $DOTIME_HOME/notify.log (always), a desktop notice, and the command in
2
+ // $DOTIME_NOTIFY_CMD. DOTIME_NOTIFY=log limits it to the log line. Nothing here throws.
3
+ import { homedir } from "node:os";
4
+ import { spawnSync } from "node:child_process";
5
+ import { showDesktopNotice } from "./probes.mjs";
6
+ import { appendLine } from "./files.mjs";
7
+
8
+ // The home folder, but not a longer folder name that starts the same way ("/h/ann" must not turn "/h/anna" into "~a").
9
+ // An empty or "/" home gives null: nothing is shortened, so no text is mangled.
10
+ const homeRe = () => {
11
+ const home = homedir();
12
+ return home.length < 2 ? null : new RegExp(`${home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w.-])`, "g");
13
+ };
14
+
15
+ /** One line of printable text with the home folder shortened to ~, cut to a length. */
16
+ export function cleanText(text, maxLength) {
17
+ const home = homeRe();
18
+ const raw = String(text ?? "");
19
+ const shortened = home ? raw.replace(home, "~") : raw;
20
+ return shortened.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength);
21
+ }
22
+
23
+ /** Runs the notify command in a shell. The texts are handed over as environment variables, not as shell code. */
24
+ export function runNotifyCommand(command, title, message, env = process.env) {
25
+ try {
26
+ const withTexts = { ...env, DOTIME_TITLE: title, DOTIME_MESSAGE: message };
27
+ const ran = spawnSync("/bin/sh", ["-c", command], { env: withTexts, stdio: "ignore", timeout: 15_000 });
28
+ return ran.status === 0;
29
+ } catch { return false; }
30
+ }
31
+
32
+ /** Returns { logged, desktop, command }; command is null when no command is set. env selects the channels; logFile
33
+ * is the notify.log of the state folder. */
34
+ export function notify(title, message, channels) {
35
+ const { env, logFile, desktop = showDesktopNotice, command = runNotifyCommand, now = Date.now() } = channels;
36
+ const head = cleanText(title, 80);
37
+ const body = cleanText(message, 900);
38
+ const sent = { logged: false, desktop: false, command: null };
39
+ // A log line that cannot be written does not stop the other channels.
40
+ sent.logged = appendLine(logFile, `${new Date(now).toISOString()}\t${head}\t${body}\n`);
41
+ if (env.DOTIME_NOTIFY === "log") return sent;
42
+ try { sent.desktop = !!desktop(head, cleanText(body, 240)); } catch { /* stays false */ }
43
+ if (env.DOTIME_NOTIFY_CMD) {
44
+ try { sent.command = !!command(env.DOTIME_NOTIFY_CMD, head, body, env); } catch { sent.command = false; }
45
+ }
46
+ return sent;
47
+ }
@@ -0,0 +1,162 @@
1
+ // Readings from the operating system, one small function per reading, with the text parsing kept apart so it can be
2
+ // tested on sample output. A probe that differs between macOS and Linux takes the platform as an option, so tests
3
+ // can take either branch on any machine. Other platforms take the macOS branch, except that they show no desktop
4
+ // notice. When the operating system gives no answer, a probe answers null or empty text instead of throwing.
5
+ import { spawnSync } from "node:child_process";
6
+ import { statfsSync } from "node:fs";
7
+ import { cpus, loadavg } from "node:os";
8
+ import { parseGroupId } from "./ps.mjs";
9
+ import { meminfoFreePct, meminfoSwapPct, parseMeminfo, readText } from "./linux.mjs";
10
+
11
+ const BIG_OUTPUT = 32 * 1024 * 1024;
12
+
13
+ /** The environment for system tools: decimals with a dot (some locales write a comma, which would not parse) and
14
+ * UTF-8 text, so command lines with non-ASCII letters come through as they are. Linux names the UTF-8 locale
15
+ * C.UTF-8; a bare UTF-8 is not a locale there. */
16
+ export function toolEnv(env = process.env, platform = process.platform) {
17
+ const { LC_ALL, ...rest } = env;
18
+ return { ...rest, LC_NUMERIC: "C", LC_CTYPE: platform === "linux" ? "C.UTF-8" : "UTF-8" };
19
+ }
20
+
21
+ /** The tool's output, or empty text when the tool is missing, is stopped or runs out of time: part of a reading is
22
+ * never passed on as if it were all of it. */
23
+ export function runTool(tool, args, timeout = 5000) {
24
+ try {
25
+ const ran = spawnSync(tool, args, { encoding: "utf8", timeout, maxBuffer: BIG_OUTPUT, env: toolEnv() });
26
+ return ran.error || ran.signal ? "" : ran.stdout || "";
27
+ } catch { return ""; }
28
+ }
29
+
30
+ export const probeLoad = () => ({ load: loadavg()[0], cores: cpus().length });
31
+
32
+ const TIME_NAMES = ["user", "nice", "sys", "idle", "irq"];
33
+
34
+ /** True when list is a list of cores as os.cpus() gives them: each with times.{user,nice,sys,idle,irq} as numbers
35
+ * of 0 or more. Times read back from a file are checked with it before use. */
36
+ export function validCpuTimes(list) {
37
+ if (!Array.isArray(list)) return false;
38
+ return list.every((core) => TIME_NAMES.every((name) => Number.isFinite(core?.times?.[name]) && core.times[name] >= 0));
39
+ }
40
+
41
+ /** The share of CPU time in use across all cores between two os.cpus() snapshots, in percent, or null when no time
42
+ * passed between them, a snapshot is not a valid list of core times, or a counter went backwards. Only cores found
43
+ * in both snapshots count, so a core list that changed size still gives a fair share. */
44
+ export function cpuBusyPct(before, after) {
45
+ if (!validCpuTimes(before) || !validCpuTimes(after)) return null;
46
+ let busy = 0, total = 0;
47
+ for (let i = 0; i < Math.min(before.length, after.length); i++) {
48
+ const spent = Object.fromEntries(TIME_NAMES.map((name) => [name, after[i].times[name] - before[i].times[name]]));
49
+ if (TIME_NAMES.some((name) => spent[name] < 0)) return null;
50
+ const used = spent.user + spent.nice + spent.sys + spent.irq;
51
+ busy += used;
52
+ total += used + spent.idle;
53
+ }
54
+ if (!(total > 0)) return null;
55
+ return (busy / total) * 100;
56
+ }
57
+
58
+ /** The CPU times of each core now, as { at, cpus: [{ times }] }, small enough to keep in a file for a later
59
+ * cpuBusyPct(). */
60
+ export const probeCpuTimes = (now = Date.now) => ({ at: now(), cpus: cpus().map(({ times }) => ({ times })) });
61
+
62
+ /** Blocks for ms milliseconds. */
63
+ export const pause = (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };
64
+
65
+ /** Parses memory_pressure output into free percent, or null. */
66
+ export function parseMemoryPressure(text) {
67
+ const found = String(text ?? "").match(/free percentage:\s*(\d+)%/);
68
+ return found ? Number(found[1]) : null;
69
+ }
70
+ /** Free memory in percent, or null: on Linux the available share from /proc/meminfo, on macOS what
71
+ * memory_pressure reports. */
72
+ export function probeMemoryFreePct({ platform = process.platform, run = runTool, read = readText } = {}) {
73
+ if (platform === "linux") return meminfoFreePct(parseMeminfo(read("/proc/meminfo")));
74
+ return parseMemoryPressure(run("memory_pressure", []));
75
+ }
76
+
77
+ /** Free GB from a file system reading of statfs, counting only the blocks a user who is not root may use, as `df`
78
+ * does; null when the reading has no usable numbers. A full disk is 0, not null. */
79
+ export function statfsFreeGB(reading) {
80
+ const { bavail, bsize } = reading ?? {};
81
+ return Number.isFinite(bavail) && bavail >= 0 && bsize > 0 ? (bavail * bsize) / 1024 ** 3 : null;
82
+ }
83
+ /** Free GB on the disk that holds path, the same way on macOS and Linux, or null when it cannot be read. */
84
+ export function probeDiskFreeGB(path = "/", { statfs = statfsSync } = {}) {
85
+ try { return statfsFreeGB(statfs(path)); } catch { return null; }
86
+ }
87
+
88
+ /** Parses `sysctl vm.swapusage` output into percent of swap in use (0 without swap). */
89
+ export function parseSwap(text) {
90
+ const found = String(text ?? "").match(/total = ([\d.]+)M\s+used = ([\d.]+)M/);
91
+ if (!found) return 0;
92
+ const total = Number(found[1]);
93
+ const used = Number(found[2]);
94
+ return total > 0 ? (used / total) * 100 : 0;
95
+ }
96
+ /** Swap in use, in percent: on Linux from /proc/meminfo, on macOS from sysctl; 0 without swap or a reading. */
97
+ export function probeSwapPct({ platform = process.platform, run = runTool, read = readText } = {}) {
98
+ if (platform === "linux") return meminfoSwapPct(parseMeminfo(read("/proc/meminfo")));
99
+ return parseSwap(run("sysctl", ["-n", "vm.swapusage"]));
100
+ }
101
+
102
+ export const probePowerText = () => runTool("pmset", ["-g", "batt"], 1500);
103
+
104
+ // Three views of the process table: full rows for the reaper, CPU time including finished children, and a cheap
105
+ // pid/parent/group listing. The options and columns are the same for macOS ps and Linux (procps) ps, except the one
106
+ // that adds the CPU time of finished children. -ww keeps the command column whole whatever COLUMNS says.
107
+ const TABLE_COLUMNS = "pid=,ppid=,pgid=,etime=,time=,pcpu=,rss=,command=";
108
+ export function probeProcessTable({ run = runTool } = {}) {
109
+ return run("ps", ["-ww", "-Ao", TABLE_COLUMNS], 10_000);
110
+ }
111
+ /** CPU time per process including its finished children: -S on macOS, --cumulative on Linux. */
112
+ export function probeProcessCpu({ platform = process.platform, run = runTool } = {}) {
113
+ const withChildren = platform === "linux" ? "--cumulative" : "-S";
114
+ return run("ps", [withChildren, "-Ao", "pid=,ppid=,pgid=,time="], 10_000);
115
+ }
116
+ export const probeProcessTree = () => runTool("ps", ["-Ao", "pid=,ppid=,pgid="]);
117
+ /** `ps -o pid=,etime=` for the given pids; empty text for none. */
118
+ export const probeProcessAges = (pids) => {
119
+ if (!pids.length) return "";
120
+ return runTool("ps", ["-o", "pid=,etime=", "-p", pids.join(",")]);
121
+ };
122
+ /** The process group of a pid, or null when ps has no answer. */
123
+ export const probeGroupOf = (pid) => parseGroupId(runTool("ps", ["-o", "pgid=", "-p", String(pid)], 3000));
124
+
125
+ /** Shows a desktop notice: through osascript on macOS, through notify-send on Linux, and not at all elsewhere. False
126
+ * when it could not be shown, also when notify-send is not installed, as on most servers. The texts travel as
127
+ * arguments after the options, so they are never read as script code or as options. */
128
+ export function showDesktopNotice(title, message, { run = spawnSync, platform = process.platform } = {}) {
129
+ if (platform === "linux") {
130
+ try {
131
+ return run("notify-send", ["--", title, message], { stdio: "ignore", timeout: 10_000 }).status === 0;
132
+ } catch { return false; }
133
+ }
134
+ if (platform !== "darwin") return false;
135
+ const script = [
136
+ "-e", "on run argv", "-e", "display notification (item 2 of argv) with title (item 1 of argv)", "-e", "end run",
137
+ ];
138
+ try {
139
+ return run("osascript", [...script, title, message], { stdio: "ignore", timeout: 10_000 }).status === 0;
140
+ } catch { return false; }
141
+ }
142
+
143
+ /** Parses `launchctl list` output into a Map from label to { pid, exit }. */
144
+ export function parseLaunchctlList(text) {
145
+ const jobs = new Map();
146
+ for (const row of String(text ?? "").split("\n").slice(1)) {
147
+ const [pid, status, label] = row.split("\t");
148
+ if (!label) continue;
149
+ jobs.set(label, { pid: pid === "-" ? null : Number(pid), exit: status === "-" ? null : Number(status) });
150
+ }
151
+ return jobs;
152
+ }
153
+ /** The scheduler's job list, or null when it cannot be read. */
154
+ export function probeScheduledJobs(run = spawnSync) {
155
+ try {
156
+ const listed = run("launchctl", ["list"], { encoding: "utf8", timeout: 10_000, maxBuffer: BIG_OUTPUT });
157
+ return listed.status === 0 && listed.stdout ? parseLaunchctlList(listed.stdout) : null;
158
+ } catch { return null; }
159
+ }
160
+ export function probeReadPlist(file) {
161
+ try { return JSON.parse(runTool("plutil", ["-convert", "json", "-o", "-", file])); } catch { return null; }
162
+ }