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.
- package/LICENSE +661 -0
- package/README.md +259 -2
- package/SECURITY.md +61 -0
- package/mcp/jobs.mjs +137 -0
- package/mcp/runner.mjs +64 -0
- package/mcp/server.mjs +209 -0
- package/mcp/tools.mjs +380 -0
- package/package.json +47 -4
- package/queue/README.md +880 -0
- package/queue/args.mjs +136 -0
- package/queue/cli.mjs +207 -0
- package/queue/clock.mjs +49 -0
- package/queue/commands.mjs +35 -0
- package/queue/failstop.mjs +45 -0
- package/queue/files.mjs +71 -0
- package/queue/fingerprint.mjs +63 -0
- package/queue/gate.mjs +37 -0
- package/queue/git.mjs +61 -0
- package/queue/health.mjs +154 -0
- package/queue/idle.mjs +63 -0
- package/queue/job-wrapper.mjs +116 -0
- package/queue/journal.mjs +216 -0
- package/queue/kinds.mjs +95 -0
- package/queue/limits.mjs +79 -0
- package/queue/linux.mjs +72 -0
- package/queue/nested.mjs +83 -0
- package/queue/notices.mjs +114 -0
- package/queue/notify.mjs +47 -0
- package/queue/probes.mjs +162 -0
- package/queue/proctree.mjs +124 -0
- package/queue/project.mjs +26 -0
- package/queue/ps.mjs +54 -0
- package/queue/reaper.mjs +278 -0
- package/queue/run.mjs +612 -0
- package/queue/schedule-check.mjs +177 -0
- package/queue/settings.mjs +145 -0
- package/queue/setup.mjs +270 -0
- package/queue/slots.mjs +144 -0
- package/queue/stats.mjs +8 -0
- package/queue/stray.mjs +38 -0
- package/queue/timer.mjs +47 -0
- package/queue/units.mjs +8 -0
package/queue/git.mjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The queue's own git calls. They only look at a repository: no index lock is taken, and no watcher program named
|
|
2
|
+
// in a repository's settings is started. Every call has a time limit, and a call that fails answers null.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { basename, dirname } from "node:path";
|
|
5
|
+
|
|
6
|
+
/** The environment for the queue's git calls. GIT_OPTIONAL_LOCKS=0: the index lock is never taken, so an agent's
|
|
7
|
+
* own `git add` or `git commit` at the same moment cannot fail because of the queue. core.fsmonitor=false: a
|
|
8
|
+
* watcher program named in a repository's settings is not started. */
|
|
9
|
+
export function readOnlyGit(env = process.env) {
|
|
10
|
+
const n = Number(env.GIT_CONFIG_COUNT) || 0;
|
|
11
|
+
return {
|
|
12
|
+
...env,
|
|
13
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
14
|
+
GIT_CONFIG_COUNT: String(n + 1),
|
|
15
|
+
[`GIT_CONFIG_KEY_${n}`]: "core.fsmonitor",
|
|
16
|
+
[`GIT_CONFIG_VALUE_${n}`]: "false",
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The output of `git -C <cwd> <args>`, or null when git is missing, fails, or runs out of time or buffer.
|
|
21
|
+
* opts: timeout in ms (10 s), maxBuffer in bytes, encoding "utf8" or "buffer". Without maxBuffer the key is left
|
|
22
|
+
* out, so Node's default of 1 MB applies: a maxBuffer of undefined would mean no limit at all. */
|
|
23
|
+
export function git(cwd, args, { timeout = 10_000, maxBuffer, encoding = "utf8" } = {}) {
|
|
24
|
+
const options = { encoding, timeout, ...(maxBuffer === undefined ? {} : { maxBuffer }), env: readOnlyGit() };
|
|
25
|
+
try {
|
|
26
|
+
const ran = spawnSync("git", ["-C", cwd, ...args], options);
|
|
27
|
+
return ran.status === 0 ? ran.stdout : null;
|
|
28
|
+
} catch { return null; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Is `git status --porcelain` output free of changes? The one line it forgives is a link named `node_modules`
|
|
32
|
+
* that git lists as untracked: a `node_modules/` ignore rule matches folders only, and that link is no source. */
|
|
33
|
+
export function porcelainClean(status) {
|
|
34
|
+
return String(status).split("\n").filter(Boolean).every((entry) => /^\?\? (.*\/)?node_modules$/.test(entry));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Returns { head, clean }, each null when git has no answer. */
|
|
38
|
+
export function gitState(cwd) {
|
|
39
|
+
const head = git(cwd, ["rev-parse", "HEAD"])?.trim() || null;
|
|
40
|
+
const status = head ? git(cwd, ["status", "--porcelain"]) : null;
|
|
41
|
+
return { head, clean: status == null ? null : porcelainClean(status) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Is the folder inside a git repository? True also for a repository that has no commits yet. */
|
|
45
|
+
export function isRepository(cwd) {
|
|
46
|
+
return git(cwd, ["rev-parse", "--git-dir"], { timeout: 3000 }) !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The folder name of the repository a folder belongs to, or null outside git. A linked worktree reports its main
|
|
50
|
+
* repository. */
|
|
51
|
+
export function repoName(cwd) {
|
|
52
|
+
const gitDir = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"], { timeout: 3000 })?.trim();
|
|
53
|
+
if (!gitDir) return null;
|
|
54
|
+
return basename(gitDir.endsWith("/.git") ? dirname(gitDir) : gitDir);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The top folder of the repository a folder belongs to (the worktree's own, for a linked worktree), or null outside
|
|
58
|
+
* git. */
|
|
59
|
+
export function repoTop(cwd) {
|
|
60
|
+
return git(cwd, ["rev-parse", "--show-toplevel"], { timeout: 3000 })?.trim() || null;
|
|
61
|
+
}
|
package/queue/health.mjs
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// The health gate. A new job may start only while load, free memory, free disk and battery are inside their limits.
|
|
2
|
+
// healthVerdict() judges a reading and names each failed limit; readHealth() takes the reading; cachedHealth()
|
|
3
|
+
// shares one reading between jobs that wait at the same time. The 1-minute load lags behind: it stays high for a while
|
|
4
|
+
// after heavy work has ended. So a high load holds a job only while the CPU is also busy right now.
|
|
5
|
+
import {
|
|
6
|
+
cpuBusyPct, pause, probeCpuTimes, probeDiskFreeGB, probeLoad, probeMemoryFreePct, probePowerText, validCpuTimes,
|
|
7
|
+
} from "./probes.mjs";
|
|
8
|
+
import { readPowerSupplies, supplyBattery } from "./linux.mjs";
|
|
9
|
+
import { dropOldTemps, readJson, writeJsonAtomic } from "./files.mjs";
|
|
10
|
+
import { DEFAULTS } from "./settings.mjs";
|
|
11
|
+
|
|
12
|
+
/** Returns { ok, blocks: [{ gate, text }] }. A reading of null is unknown and passes; 0 is a real value. limits:
|
|
13
|
+
* the health settings. A load above its limit holds a job unless the live CPU reading (busyCpuPct) is known and
|
|
14
|
+
* below limits.busyCpuPct; limits without busyCpuPct use the default. */
|
|
15
|
+
export function healthVerdict({ load, cores, busyCpuPct = null, freePct, diskGB, battery = null }, limits) {
|
|
16
|
+
const blocks = [];
|
|
17
|
+
const loadCap = cores * limits.loadPerCore;
|
|
18
|
+
const cpuKnown = Number.isFinite(busyCpuPct);
|
|
19
|
+
if (load > loadCap && (!cpuKnown || busyCpuPct >= (limits.busyCpuPct ?? DEFAULTS.health.busyCpuPct))) {
|
|
20
|
+
const cpu = cpuKnown ? `; CPU ${Math.round(busyCpuPct)}% busy now` : "";
|
|
21
|
+
const text = `load too high: ${load.toFixed(1)} now, ${loadCap.toFixed(1)} allowed${cpu}`;
|
|
22
|
+
blocks.push({ gate: "load", text });
|
|
23
|
+
}
|
|
24
|
+
if (freePct != null && freePct < limits.minFreeMemPct) {
|
|
25
|
+
blocks.push({ gate: "memory", text: `memory too low: ${freePct}% free, ${limits.minFreeMemPct}% needed` });
|
|
26
|
+
}
|
|
27
|
+
if (diskGB != null && diskGB < limits.minFreeDiskGB) {
|
|
28
|
+
const text = `disk too low: ${diskGB.toFixed(1)} GB free, ${limits.minFreeDiskGB} GB needed`;
|
|
29
|
+
blocks.push({ gate: "disk", text });
|
|
30
|
+
}
|
|
31
|
+
if (battery?.onBattery === true && Number.isFinite(battery.pct) && battery.pct <= limits.minBatteryPct) {
|
|
32
|
+
const supply = battery.plugged ? "plugged in but still draining" : "not plugged in";
|
|
33
|
+
const text = `battery too low: ${battery.pct}% left, more than ${limits.minBatteryPct}% needed, ${supply}`;
|
|
34
|
+
blocks.push({ gate: "battery", text });
|
|
35
|
+
}
|
|
36
|
+
return { ok: blocks.length === 0, blocks };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Parses `pmset -g batt` output into { ac: true | false | null, pct, charge }. */
|
|
40
|
+
export function parsePower(text) {
|
|
41
|
+
const report = String(text ?? "");
|
|
42
|
+
const source = report.match(/Now drawing from '([^']+)'/)?.[1], level = report.match(/(\d{1,3})%;/)?.[1];
|
|
43
|
+
return {
|
|
44
|
+
ac: source ? source === "AC Power" : null,
|
|
45
|
+
pct: level == null ? null : Number(level),
|
|
46
|
+
charge: report.match(/\d{1,3}%;\s*([^;\n]+)/)?.[1].trim() ?? null,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Returns { onBattery: true | false | null, plugged }. A plugged-in computer that still loses charge counts as on
|
|
51
|
+
* battery. */
|
|
52
|
+
export function powerState(power) {
|
|
53
|
+
if (power?.ac === false) return { onBattery: true, plugged: false };
|
|
54
|
+
if (power?.ac !== true) return { onBattery: null, plugged: false };
|
|
55
|
+
return { onBattery: power.charge === "discharging", plugged: true };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The battery reading for the gate, or null when it is unknown or there is no battery. On Linux it comes from the
|
|
59
|
+
* power supplies in /sys (supplies), elsewhere from the `pmset -g batt` text that probe returns. */
|
|
60
|
+
export function readBattery(
|
|
61
|
+
probe = probePowerText, { platform = process.platform, supplies = readPowerSupplies } = {},
|
|
62
|
+
) {
|
|
63
|
+
try {
|
|
64
|
+
if (platform === "linux") return supplyBattery(supplies());
|
|
65
|
+
const power = parsePower(probe());
|
|
66
|
+
const state = powerState(power);
|
|
67
|
+
if (state.onBattery == null || power.pct == null) return null;
|
|
68
|
+
return { onBattery: state.onBattery, pct: power.pct, plugged: state.plugged };
|
|
69
|
+
} catch { return null; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The oldest shared reading a job may start on, whatever the poll time. */
|
|
73
|
+
export const MAX_SHARED_READING_MS = 5000;
|
|
74
|
+
|
|
75
|
+
/** The shortest span of saved CPU times a live CPU reading is measured over. */
|
|
76
|
+
export const MIN_CPU_SPAN_MS = 500;
|
|
77
|
+
|
|
78
|
+
/** The span a live CPU reading of its own is measured over, when no usable CPU times were saved. */
|
|
79
|
+
export const OWN_CPU_SPAN_MS = 1000;
|
|
80
|
+
|
|
81
|
+
/** CPU times now, or null when they cannot be read. */
|
|
82
|
+
function cpuTimesNow(read) {
|
|
83
|
+
try { return read.cpuTimes(); } catch { return null; }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** { busyCpuPct, cpuTimes }: the live CPU reading and the CPU times it ended on. Valid saved CPU times (since) up to
|
|
87
|
+
* MAX_SHARED_READING_MS old are measured against: at once when they are at least MIN_CPU_SPAN_MS old, after waiting
|
|
88
|
+
* the rest of MIN_CPU_SPAN_MS when they are younger. Otherwise the reading waits OWN_CPU_SPAN_MS between two
|
|
89
|
+
* snapshots of its own. */
|
|
90
|
+
function busyCpuNow(since, read) {
|
|
91
|
+
let times = cpuTimesNow(read);
|
|
92
|
+
const age = times?.at - since?.at;
|
|
93
|
+
if (validCpuTimes(since?.cpus) && age >= 0 && age <= MAX_SHARED_READING_MS) {
|
|
94
|
+
if (age < MIN_CPU_SPAN_MS) {
|
|
95
|
+
read.wait(MIN_CPU_SPAN_MS - age);
|
|
96
|
+
times = cpuTimesNow(read);
|
|
97
|
+
}
|
|
98
|
+
const busyCpuPct = cpuBusyPct(since.cpus, times?.cpus);
|
|
99
|
+
if (busyCpuPct != null) return { busyCpuPct, cpuTimes: times };
|
|
100
|
+
}
|
|
101
|
+
if (!times) return { busyCpuPct: null, cpuTimes: null };
|
|
102
|
+
read.wait(OWN_CPU_SPAN_MS);
|
|
103
|
+
const after = cpuTimesNow(read);
|
|
104
|
+
return { busyCpuPct: cpuBusyPct(times.cpus, after?.cpus), cpuTimes: after };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Does a limit other than the load hold a job? The reading is judged with a load of 0, so only the others count. */
|
|
108
|
+
function otherLimitsHold(cores, rest, limits) {
|
|
109
|
+
return !healthVerdict({ load: 0, cores, ...rest }, limits).ok;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The current reading: { load, cores, busyCpuPct, freePct, diskGB, battery }. probes replaces single readings.
|
|
113
|
+
* The live CPU reading is taken only when limits (the health settings) are given, the load is above its limit and
|
|
114
|
+
* no other limit already holds a job; otherwise busyCpuPct is null. With limits the reading also carries cpuTimes,
|
|
115
|
+
* the CPU times it ended on; handed back as cpuSince to a later reading, they let that reading measure the CPU
|
|
116
|
+
* without waiting. */
|
|
117
|
+
export function readHealth({ probes = {}, limits = null, cpuSince = null } = {}) {
|
|
118
|
+
const read = {
|
|
119
|
+
load: probeLoad, cpuTimes: probeCpuTimes, wait: pause, memory: probeMemoryFreePct,
|
|
120
|
+
disk: probeDiskFreeGB, battery: readBattery, ...probes,
|
|
121
|
+
};
|
|
122
|
+
const { load, cores } = read.load();
|
|
123
|
+
const rest = { freePct: read.memory(), diskGB: read.disk(), battery: read.battery() };
|
|
124
|
+
if (!limits) return { load, cores, busyCpuPct: null, ...rest };
|
|
125
|
+
const loadHolds = load > cores * limits.loadPerCore;
|
|
126
|
+
const { busyCpuPct, cpuTimes } = loadHolds && !otherLimitsHold(cores, rest, limits)
|
|
127
|
+
? busyCpuNow(cpuSince, read)
|
|
128
|
+
: { busyCpuPct: null, cpuTimes: cpuTimesNow(read) };
|
|
129
|
+
return { load, cores, busyCpuPct, ...rest, cpuTimes };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The CPU times kept in the file of the shared reading (see cachedHealth), or null when there are none. */
|
|
133
|
+
export function savedCpuTimes(file) {
|
|
134
|
+
return cpuTimesOf(readJson(file, null));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const cpuTimesOf = (saved) => saved?.cpuTimes ?? null;
|
|
138
|
+
|
|
139
|
+
/** A reading shared through a file in the state folder, so jobs that wait at the same time take one reading per
|
|
140
|
+
* poll between them instead of one each. A saved reading is used while it is younger than maxAgeMs (the poll
|
|
141
|
+
* time) and than MAX_SHARED_READING_MS; an older one is read fresh. The file also keeps the CPU times of the last
|
|
142
|
+
* reading, which the next reading measures the CPU against, and the time a reading finished, so a reading that
|
|
143
|
+
* took a while is not already old when it is saved. A cache that cannot be read or written only means a fresh
|
|
144
|
+
* reading. Temporary files of the cache that a process left behind when it died while writing are removed when a
|
|
145
|
+
* reading is saved. read is handed { cpuSince }. clock gives the time now. */
|
|
146
|
+
export function cachedHealth(file, maxAgeMs, read = readHealth, clock = Date.now) {
|
|
147
|
+
const saved = readJson(file, null);
|
|
148
|
+
const age = clock() - saved?.at;
|
|
149
|
+
if (saved?.reading && age >= 0 && age < Math.min(maxAgeMs, MAX_SHARED_READING_MS)) return saved.reading;
|
|
150
|
+
const { cpuTimes, ...reading } = read({ cpuSince: cpuTimesOf(saved) });
|
|
151
|
+
try { writeJsonAtomic(file, { at: clock(), reading, cpuTimes }); } catch { /* the next poll reads again */ }
|
|
152
|
+
dropOldTemps(file);
|
|
153
|
+
return reading;
|
|
154
|
+
}
|
package/queue/idle.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Idle detection from CPU samples. A dev-server group that used almost no CPU over the idle window may be stopped
|
|
2
|
+
// by the reaper; a job that holds a slot without using CPU only earns a notice. A sample is { t, cpu }, where cpu is
|
|
3
|
+
// the summed CPU seconds of the whole group, and samples are ordered oldest first.
|
|
4
|
+
import { TEST_RUN_RE } from "./commands.mjs";
|
|
5
|
+
import { MINUTE } from "./units.mjs";
|
|
6
|
+
|
|
7
|
+
/** A test for dev-server commands, from the reaper.serverPattern setting, compiled once: (command) => boolean. A
|
|
8
|
+
* one-shot test command is never a server. A pattern that does not compile matches nothing. */
|
|
9
|
+
export function serverTest(pattern) {
|
|
10
|
+
let matcher;
|
|
11
|
+
try { matcher = new RegExp(pattern); } catch { return () => false; }
|
|
12
|
+
return (command) => matcher.test(command) && !TEST_RUN_RE.test(command);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// marginMin: how much longer than the idle window samples are kept. bandMin: how far past the window the older
|
|
16
|
+
// sample of a server comparison may lie. toleranceMs: how much short of the window a slot comparison may fall,
|
|
17
|
+
// because a scheduler never fires exactly on time.
|
|
18
|
+
export const SAMPLING = { marginMin: 25, bandMin: 15, toleranceMs: 30_000 };
|
|
19
|
+
/** How long samples are kept for an idle window of the given length. */
|
|
20
|
+
export const sampleKeepMs = (windowMin, sampling = SAMPLING) => (windowMin + sampling.marginMin) * MINUTE;
|
|
21
|
+
|
|
22
|
+
/** Cuts the samples at the last decrease of the CPU total. A total only decreases when a process exits and its
|
|
23
|
+
* time drops out of the sum, so samples from before that cannot be compared with later ones. */
|
|
24
|
+
export function sinceReset(samples) {
|
|
25
|
+
let start = 0;
|
|
26
|
+
for (let i = 1; i < samples.length; i++) if (samples[i].cpu < samples[i - 1].cpu) start = i;
|
|
27
|
+
return samples.slice(start);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** CPU use and time span as a phrase: "1.5 s of CPU in 12 min". */
|
|
31
|
+
export const idleText = ({ usedS, minutes }) => `${usedS.toFixed(1)} s of CPU in ${minutes} min`;
|
|
32
|
+
|
|
33
|
+
/** Returns { idle, state, usedS?, minutes? } with state one of protected, new, sampling, restarted, active, idle. */
|
|
34
|
+
export function serverIdleVerdict({ ageMs, samples, now, exempt }, idle, sampling = SAMPLING) {
|
|
35
|
+
const windowMs = idle.serverIdleMin * MINUTE;
|
|
36
|
+
if (exempt) return { idle: false, state: "protected" };
|
|
37
|
+
if (ageMs < windowMs) return { idle: false, state: "new" };
|
|
38
|
+
const usable = sinceReset(samples);
|
|
39
|
+
const newest = usable.at(-1);
|
|
40
|
+
const older = usable.find((s) => now - s.t >= windowMs && now - s.t < windowMs + sampling.bandMin * MINUTE);
|
|
41
|
+
if (!older || !newest) return { idle: false, state: usable.length < samples.length ? "restarted" : "sampling" };
|
|
42
|
+
const usedS = newest.cpu - older.cpu;
|
|
43
|
+
const minutes = Math.round((now - older.t) / MINUTE);
|
|
44
|
+
if (usedS < idle.serverCpuS) return { idle: true, state: "idle", usedS, minutes };
|
|
45
|
+
return { idle: false, state: "active", usedS, minutes };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The same question for a job in a slot. Returns { idle, state, usedS?, minutes?, since? } with state new, sampling,
|
|
49
|
+
* restarted, active or idle. */
|
|
50
|
+
export function slotIdleVerdict({ startedAt, samples, now }, idle, sampling = SAMPLING) {
|
|
51
|
+
const windowMs = idle.slotIdleMin * MINUTE;
|
|
52
|
+
if (now - startedAt < windowMs) return { idle: false, state: "new" };
|
|
53
|
+
const usable = sinceReset(samples);
|
|
54
|
+
const newest = usable.at(-1);
|
|
55
|
+
const older = usable.findLast((s) => now - s.t >= windowMs - sampling.toleranceMs);
|
|
56
|
+
if (!older || !newest || older === newest) {
|
|
57
|
+
return { idle: false, state: usable.length < samples.length ? "restarted" : "sampling" };
|
|
58
|
+
}
|
|
59
|
+
const usedS = Math.round((newest.cpu - older.cpu) * 10) / 10;
|
|
60
|
+
const minutes = Math.round((now - older.t) / MINUTE);
|
|
61
|
+
if (usedS < idle.slotCpuS) return { idle: true, state: "idle", usedS, minutes, since: older.t };
|
|
62
|
+
return { idle: false, state: "active", usedS, minutes };
|
|
63
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Wrapper that the queue starts in a new process group: `node job-wrapper.mjs <queue pid> <command> [args]`.
|
|
3
|
+
// Because the job and everything it starts share that group, one signal reaches all of it. The wrapper ends the way
|
|
4
|
+
// the job ended, and it stops the group when the queue process that started it is gone. When the command cannot be
|
|
5
|
+
// started at all, the wrapper says so on file descriptor 3 if the queue opened one, so the queue can tell that apart
|
|
6
|
+
// from a job that ran and exited 127.
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { writeSync } from "node:fs";
|
|
9
|
+
import { constants as osConstants } from "node:os";
|
|
10
|
+
import { isMainModule, loadSettings } from "./settings.mjs";
|
|
11
|
+
import { alive, signalGroup } from "./proctree.mjs";
|
|
12
|
+
|
|
13
|
+
const FORWARDED = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
14
|
+
export const NO_START_EXIT = 127;
|
|
15
|
+
|
|
16
|
+
/** How the wrapper ends once the job has ended: { exit } with a code, or { reraise, orExit } to die by the same
|
|
17
|
+
* signal, so the queue can tell a stopped job from one that exited, with orExit as the code for a signal Node does
|
|
18
|
+
* not die by. SIGUSR1 is never raised again: it would open Node's debugger in this process instead of ending it,
|
|
19
|
+
* so that one ends with the exit code a shell would give. */
|
|
20
|
+
export function exitPlan({ code = null, signal = null }) {
|
|
21
|
+
if (!signal) return { exit: code ?? 0 };
|
|
22
|
+
const shellCode = 128 + (osConstants.signals[signal] ?? 0);
|
|
23
|
+
if (signal === "SIGUSR1") return { exit: shellCode };
|
|
24
|
+
return { reraise: signal, orExit: shellCode };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** True when the queue process that started the wrapper is gone: it is no longer the parent, or it has died. */
|
|
28
|
+
export const queueGone = ({ ppid, queuePid, isAlive = alive }) => ppid !== queuePid || !isAlive(queuePid);
|
|
29
|
+
|
|
30
|
+
/** The line the wrapper sends on file descriptor 3 when the command cannot be started. */
|
|
31
|
+
export const startFailureLine = (message) => `${JSON.stringify({ startFailed: message })}\n`;
|
|
32
|
+
|
|
33
|
+
/** The message from a start-failure line in the text read from file descriptor 3, or null when there is none.
|
|
34
|
+
* Other lines and a line that was cut short are passed over. */
|
|
35
|
+
export function readStartFailure(text) {
|
|
36
|
+
for (const line of String(text).split("\n")) {
|
|
37
|
+
let sent;
|
|
38
|
+
try { sent = JSON.parse(line); } catch { continue; /* not a report line */ }
|
|
39
|
+
if (typeof sent?.startFailed === "string") return sent.startFailed;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How long the queue keeps reading the report after the wrapper has exited. */
|
|
45
|
+
export const REPORT_DRAIN_MS = 500;
|
|
46
|
+
|
|
47
|
+
/** Resolves with { code, signal, report } once the wrapper has exited and its report on file descriptor 3 has been
|
|
48
|
+
* read. The report is read for at most drainMs after the exit: on systems where the job inherits the descriptor,
|
|
49
|
+
* a process the job leaves behind keeps it open, and that must not keep the queue waiting. */
|
|
50
|
+
export function wrapperEnd(child, report, drainMs = REPORT_DRAIN_MS) {
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
let text = "";
|
|
53
|
+
let exit = null;
|
|
54
|
+
let drained = !report;
|
|
55
|
+
let timer = null;
|
|
56
|
+
let settled = false;
|
|
57
|
+
const settle = () => {
|
|
58
|
+
if (settled || !exit || !drained) return;
|
|
59
|
+
settled = true;
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
report?.destroy();
|
|
62
|
+
resolve({ ...exit, report: text });
|
|
63
|
+
};
|
|
64
|
+
const stopReading = () => { drained = true; settle(); };
|
|
65
|
+
report?.setEncoding("utf8");
|
|
66
|
+
report?.on("data", (part) => { text += part; });
|
|
67
|
+
for (const event of ["end", "close", "error"]) report?.on(event, stopReading);
|
|
68
|
+
child.on("exit", (code, signal) => {
|
|
69
|
+
exit = { code, signal };
|
|
70
|
+
timer = setTimeout(stopReading, drainMs);
|
|
71
|
+
settle();
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function main() {
|
|
77
|
+
const queuePid = Number(process.argv[2]), [program, ...args] = process.argv.slice(3);
|
|
78
|
+
// The queue process has already reported any setting that does not fit.
|
|
79
|
+
const { orphanCheckMs, killGraceMs } = loadSettings(process.env, { warn: () => {} }).limits;
|
|
80
|
+
const ignore = () => {};
|
|
81
|
+
// A group that is already gone needs no signal.
|
|
82
|
+
const signalOwnGroup = (signal) => signalGroup(process.pid, signal);
|
|
83
|
+
|
|
84
|
+
// With default handlers the wrapper would die before the job and lose its exit status.
|
|
85
|
+
for (const signal of FORWARDED) process.on(signal, ignore);
|
|
86
|
+
const job = spawn(program, args, { stdio: "inherit" });
|
|
87
|
+
|
|
88
|
+
let orphaned = false;
|
|
89
|
+
const watch = setInterval(() => {
|
|
90
|
+
if (!queueGone({ ppid: process.ppid, queuePid })) return;
|
|
91
|
+
clearInterval(watch);
|
|
92
|
+
orphaned = true;
|
|
93
|
+
signalOwnGroup("SIGTERM");
|
|
94
|
+
setTimeout(() => signalOwnGroup("SIGKILL"), killGraceMs);
|
|
95
|
+
}, orphanCheckMs);
|
|
96
|
+
watch.unref();
|
|
97
|
+
|
|
98
|
+
job.on("error", (e) => {
|
|
99
|
+
try {
|
|
100
|
+
writeSync(3, startFailureLine(e.message));
|
|
101
|
+
} catch {
|
|
102
|
+
process.stderr.write(`dotime-queue: start failed: exit ${NO_START_EXIT}, ${e.message}\n`);
|
|
103
|
+
}
|
|
104
|
+
process.exit(NO_START_EXIT);
|
|
105
|
+
});
|
|
106
|
+
job.on("exit", (code, signal) => {
|
|
107
|
+
if (orphaned) signalOwnGroup("SIGKILL");
|
|
108
|
+
const plan = exitPlan({ code, signal });
|
|
109
|
+
if (!plan.reraise) process.exit(plan.exit);
|
|
110
|
+
for (const name of FORWARDED) process.off(name, ignore);
|
|
111
|
+
process.kill(process.pid, plan.reraise);
|
|
112
|
+
setTimeout(() => process.exit(plan.orExit), 1000);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (isMainModule(import.meta.url)) main();
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// The journal: one JSON line per job in $DOTIME_HOME/journal.jsonl, holding its label and project, waiting time per
|
|
2
|
+
// gate, run time, outcome, command and the commit it ran on. Run limits, the repeated-failure stop, pass stamps and
|
|
3
|
+
// `history` all read it. A failed write is reported by a return value and never interrupts a job. This module only
|
|
4
|
+
// reads and writes the journal file; the git facts in a line come from git.mjs.
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { dateTime, dayOf, dayStart, shiftDay } from "./clock.mjs";
|
|
7
|
+
import { jobProject } from "./project.mjs";
|
|
8
|
+
import { pctl } from "./stats.mjs";
|
|
9
|
+
import { appendLine } from "./files.mjs";
|
|
10
|
+
import { MINUTE, oneDecimal } from "./units.mjs";
|
|
11
|
+
|
|
12
|
+
const minutes = (ms) => oneDecimal(ms / MINUTE);
|
|
13
|
+
|
|
14
|
+
/** Journal lines as objects; text that is not JSON is skipped. */
|
|
15
|
+
export function parseLines(lines) {
|
|
16
|
+
const rows = [];
|
|
17
|
+
for (const line of lines) {
|
|
18
|
+
if (typeof line !== "string") { if (line) rows.push(line); continue; }
|
|
19
|
+
try { rows.push(JSON.parse(line)); } catch { /* skipped */ }
|
|
20
|
+
}
|
|
21
|
+
return rows;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Books waiting time to each gate named by the blocks ([{ gate }]). */
|
|
25
|
+
export function addWait(tally, blocks, ms) {
|
|
26
|
+
for (const { gate } of blocks) tally[gate] = (tally[gate] ?? 0) + ms;
|
|
27
|
+
return tally;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Joins arguments with spaces, JSON-quoting any that a shell would not read as one plain word. */
|
|
31
|
+
export function cmdString(args) {
|
|
32
|
+
return (args ?? []).map((arg) => (arg === "" || /[^\w@%+=:,./-]/.test(arg) ? JSON.stringify(arg) : arg)).join(" ");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Signals that mean someone stopped the job, and the exit codes (128 + number) that shells report for them.
|
|
36
|
+
const STOP_SIGNALS = { SIGHUP: 1, SIGINT: 2, SIGKILL: 9, SIGTERM: 15 };
|
|
37
|
+
const STOP_EXITS = Object.fromEntries(Object.entries(STOP_SIGNALS).map(([name, number]) => [128 + number, name]));
|
|
38
|
+
/** A signal that reached the queue process during the run (received) settles it as stopped, whatever the exit code.
|
|
39
|
+
* Otherwise the job's own stop signal, or the exit code a shell gives for one, does. Everything else just ran. */
|
|
40
|
+
export function jobEnd({ code = null, signal = null, received = null }) {
|
|
41
|
+
const stopper = received ?? (signal in STOP_SIGNALS ? signal : STOP_EXITS[code] ?? null);
|
|
42
|
+
return stopper ? { outcome: "stopped", signal: stopper } : { outcome: "ran" };
|
|
43
|
+
}
|
|
44
|
+
export const isStopped = (row) => row.outcome === "stopped" || (row.outcome === "ran" && row.exit in STOP_EXITS);
|
|
45
|
+
export const isFailedRun = (row) => row.outcome === "ran" && row.exit !== 0 && !isStopped(row);
|
|
46
|
+
/** A job that `run` did not start because the same check had already passed on the same commit. */
|
|
47
|
+
export const isSkipped = (row) => row.outcome === "skipped";
|
|
48
|
+
|
|
49
|
+
const isoOrNull = (ms) => (ms ? new Date(ms).toISOString() : null);
|
|
50
|
+
/** Builds a journal line. outcome: ran, stopped, timed-out, refused, skipped, gave-up, left or could-not-start. */
|
|
51
|
+
export function record(job) {
|
|
52
|
+
const { label, project, cwd, priority, queuedAt, startedAt, endedAt, outcome, exit, tally } = job;
|
|
53
|
+
const { cmd, head, clean, extra } = job;
|
|
54
|
+
return {
|
|
55
|
+
v: 1, label, project, projectKey: jobProject({ label, project, cwd }), cwd, priority: !!priority,
|
|
56
|
+
queuedAt: isoOrNull(queuedAt), startedAt: isoOrNull(startedAt), endedAt: isoOrNull(endedAt),
|
|
57
|
+
waitMin: minutes((startedAt ?? endedAt) - queuedAt), runMin: startedAt ? minutes(endedAt - startedAt) : 0,
|
|
58
|
+
outcome, exit: exit ?? null,
|
|
59
|
+
waitBy: Object.fromEntries(Object.entries(tally ?? {}).map(([gate, ms]) => [gate, minutes(ms)])),
|
|
60
|
+
cmd: cmd ?? null, head: head ?? null, clean: clean ?? null, ...(extra ?? {}),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export const lineProject = (row) => row.projectKey ?? jobProject(row);
|
|
64
|
+
|
|
65
|
+
export function append(row, file) {
|
|
66
|
+
return appendLine(file, `${JSON.stringify(row)}\n`);
|
|
67
|
+
}
|
|
68
|
+
export function readLines(file) {
|
|
69
|
+
try { return readFileSync(file, "utf8").split("\n").filter(Boolean); } catch { return []; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const shortId = (commit) => String(commit).slice(0, 8);
|
|
73
|
+
/** Looks for a passing run on the commit a folder is at. folder = { project, head, clean, repository }, where
|
|
74
|
+
* repository says whether a folder without a head is a git repository that has no commits yet; match narrows the
|
|
75
|
+
* runs to those with the text in their label or command. Returns { stamp: the run or null, text: one line to print }. */
|
|
76
|
+
export function findStamp(lines, folder, match, { tz, at = Date.now() }) {
|
|
77
|
+
const none = (why) => ({ stamp: null, text: `no stamp: ${why}` });
|
|
78
|
+
const wanted = String(match).toLowerCase();
|
|
79
|
+
if (!folder.head && folder.repository) return none("the current branch has no commits yet");
|
|
80
|
+
if (!folder.head) return none("this folder is not a git checkout");
|
|
81
|
+
if (folder.clean == null) return none("git status could not be read");
|
|
82
|
+
if (!folder.clean) return none("the working tree has uncommitted changes");
|
|
83
|
+
const runs = parseLines(lines)
|
|
84
|
+
.filter((row) => row.project === folder.project && row.head && row.outcome === "ran" && !isStopped(row))
|
|
85
|
+
.filter((row) => !wanted || `${row.label ?? ""}\n${row.cmd ?? ""}`.toLowerCase().includes(wanted))
|
|
86
|
+
.sort((a, b) => Date.parse(b.endedAt) - Date.parse(a.endedAt));
|
|
87
|
+
const scope = `project ${folder.project}${wanted ? `, filter "${match}"` : ""}`;
|
|
88
|
+
const ended = (row) => dateTime(Date.parse(row.endedAt), tz);
|
|
89
|
+
if (!runs.length) return none(`no finished run on record, ${scope}`);
|
|
90
|
+
const onCommit = runs.filter((row) => row.head === folder.head);
|
|
91
|
+
if (!onCommit.length) {
|
|
92
|
+
const newest = `newest run at ${shortId(runs[0].head)} (ended ${ended(runs[0])})`;
|
|
93
|
+
return none(`commit differs, folder at ${shortId(folder.head)}, ${newest}, ${scope}`);
|
|
94
|
+
}
|
|
95
|
+
const run = onCommit.find((row) => row.clean === true);
|
|
96
|
+
if (!run) return none(`every run at ${shortId(folder.head)} began with uncommitted changes, ${scope}`);
|
|
97
|
+
if (run.exit !== 0) {
|
|
98
|
+
const facts = `exit ${run.exit}, commit ${shortId(run.head)}, ended ${ended(run)}`;
|
|
99
|
+
return none(`newest clean run failed, "${run.label}", ${facts}`);
|
|
100
|
+
}
|
|
101
|
+
const ago = Math.max(0, Math.round((at - Date.parse(run.endedAt)) / MINUTE));
|
|
102
|
+
const text = `stamp: commit ${shortId(run.head)}, passed ${ago} min ago by "${run.label}", `
|
|
103
|
+
+ `command ${run.cmd ?? "not recorded"}, run time ${run.runMin} min, tree clean at start, `
|
|
104
|
+
+ `finished ${ended(run)}`;
|
|
105
|
+
return { stamp: run, text };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The kinds of job that `run` may skip on a pass stamp. A build, a deploy or any other job may leave output that is
|
|
109
|
+
* needed, so those always run. */
|
|
110
|
+
export const SKIPPABLE_KINDS = Object.freeze(["test", "lint"]);
|
|
111
|
+
|
|
112
|
+
/** The pass stamp that lets `run` skip a job, or null. job = { label, cmd, cwd, fp }: the stamp must come from a run
|
|
113
|
+
* with the same label and the same command line, in the same folder, found by findStamp under its own conditions (a
|
|
114
|
+
* clean folder at a commit, and a newest clean run of that check on the commit that passed). Its code fingerprint
|
|
115
|
+
* must equal the job's, so a changed file that the command names outside git is not skipped; a missing fingerprint
|
|
116
|
+
* on either side is no match. On top of that, no run of the same check on that commit may have failed, hit its run
|
|
117
|
+
* limit or failed to start after the stamp, even one that began with uncommitted changes. Lines of skipped jobs never count:
|
|
118
|
+
* findStamp only takes runs that ran. */
|
|
119
|
+
export function skipStamp(lines, folder, job, { tz, at = Date.now() }) {
|
|
120
|
+
const sameCheck = parseLines(lines)
|
|
121
|
+
.filter((row) => row.label === job.label && row.cmd === job.cmd && row.cwd === job.cwd);
|
|
122
|
+
const { stamp } = findStamp(sameCheck, folder, "", { tz, at });
|
|
123
|
+
const stampPrint = stamp?.fp ?? stamp?.fingerprint;
|
|
124
|
+
if (!stamp || !job.fp || !stampPrint || stampPrint !== job.fp) return null;
|
|
125
|
+
const passedAt = Date.parse(stamp.endedAt);
|
|
126
|
+
const failedLater = sameCheck.some((row) => row.project === folder.project && row.head === folder.head
|
|
127
|
+
&& Date.parse(row.endedAt) > passedAt
|
|
128
|
+
&& (isFailedRun(row) || row.outcome === "timed-out" || row.outcome === "could-not-start"));
|
|
129
|
+
return failedLater ? null : stamp;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The time range `history` covers. Returns { from, to, title }. day picks one calendar day; otherwise the range is the
|
|
133
|
+
* last `days` calendar days up to now, both counted in the zone. */
|
|
134
|
+
export function historyWindow({ day = null, days = 7, now = Date.now(), tz }) {
|
|
135
|
+
if (day) {
|
|
136
|
+
const nextDay = dayStart(shiftDay(day, 1), tz);
|
|
137
|
+
return { from: dayStart(day, tz), to: Math.min(now, nextDay), title: `${day}, zone ${tz}` };
|
|
138
|
+
}
|
|
139
|
+
const count = Math.max(1, Math.ceil(days));
|
|
140
|
+
const today = dayOf(now, tz);
|
|
141
|
+
const first = shiftDay(today, 1 - count);
|
|
142
|
+
const title = count === 1 ? `${today} so far, zone ${tz}` : `${first} through ${today} (${count} days), zone ${tz}`;
|
|
143
|
+
return { from: dayStart(first, tz), to: now, title };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const interval = (from, to, cap) => (Number.isFinite(from) && Number.isFinite(to) ? [from, Math.min(to, cap)] : null);
|
|
147
|
+
function waitInterval(row, cap) {
|
|
148
|
+
const from = Date.parse(row.queuedAt);
|
|
149
|
+
const to = Date.parse(row.startedAt ?? row.endedAt);
|
|
150
|
+
return interval(from, Number.isFinite(to) ? to : from + (row.waitMin ?? 0) * MINUTE, cap);
|
|
151
|
+
}
|
|
152
|
+
function runInterval(row, cap) {
|
|
153
|
+
const from = Date.parse(row.startedAt);
|
|
154
|
+
const to = Date.parse(row.endedAt);
|
|
155
|
+
return interval(from, Number.isFinite(to) ? to : from + (row.runMin ?? 0) * MINUTE, cap);
|
|
156
|
+
}
|
|
157
|
+
/** A sweep over wait and run intervals. waitWallMin: time with one or more jobs waiting, overlaps merged.
|
|
158
|
+
* blockedOnlyMin: the share of that time in which nothing was running. */
|
|
159
|
+
export function clockMinutes(waits, runs = []) {
|
|
160
|
+
const edges = [];
|
|
161
|
+
for (const w of waits) if (w && w[1] > w[0]) edges.push([w[0], 1, 0], [w[1], -1, 0]);
|
|
162
|
+
for (const r of runs) if (r && r[1] > r[0]) edges.push([r[0], 0, 1], [r[1], 0, -1]);
|
|
163
|
+
edges.sort((a, b) => a[0] - b[0]);
|
|
164
|
+
let waiting = 0;
|
|
165
|
+
let running = 0;
|
|
166
|
+
let previous = 0;
|
|
167
|
+
let wall = 0;
|
|
168
|
+
let blocked = 0;
|
|
169
|
+
for (const [t, waitStep, runStep] of edges) {
|
|
170
|
+
if (waiting > 0) { wall += t - previous; if (running === 0) blocked += t - previous; }
|
|
171
|
+
waiting += waitStep; running += runStep; previous = t;
|
|
172
|
+
}
|
|
173
|
+
return { waitWallMin: minutes(wall), blockedOnlyMin: minutes(blocked) };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function totals(rows, until) {
|
|
177
|
+
// A skipped job never waited, so it is left out of the wait percentiles.
|
|
178
|
+
const waits = rows.filter((row) => !isSkipped(row)).map((row) => row.waitMin);
|
|
179
|
+
const waitBy = {};
|
|
180
|
+
for (const row of rows) {
|
|
181
|
+
for (const [gate, min] of Object.entries(row.waitBy ?? {})) {
|
|
182
|
+
waitBy[gate] = oneDecimal((waitBy[gate] ?? 0) + min);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const count = (test) => rows.filter(test).length;
|
|
186
|
+
return {
|
|
187
|
+
jobs: rows.length,
|
|
188
|
+
waited: count((row) => row.waitMin >= 1),
|
|
189
|
+
waitMinTotal: oneDecimal(waits.reduce((a, b) => a + b, 0)),
|
|
190
|
+
...clockMinutes(rows.map((row) => waitInterval(row, until)), rows.map((row) => runInterval(row, until))),
|
|
191
|
+
waitMedian: pctl(waits, 0.5) ?? 0,
|
|
192
|
+
waitP90: pctl(waits, 0.9) ?? 0,
|
|
193
|
+
runMinTotal: oneDecimal(rows.reduce((sum, row) => sum + (row.runMin ?? 0), 0)),
|
|
194
|
+
gaveUp: count((row) => row.outcome === "gave-up"), failed: count(isFailedRun), stopped: count(isStopped),
|
|
195
|
+
timedOut: count((row) => row.outcome === "timed-out"),
|
|
196
|
+
refused: count((row) => row.outcome === "refused"),
|
|
197
|
+
skipped: count(isSkipped),
|
|
198
|
+
// The run time of the passing run each skipped job relied on: about the time the skip saved.
|
|
199
|
+
savedMin: oneDecimal(rows.filter(isSkipped).reduce((sum, row) => sum + (row.stamp?.runMin ?? 0), 0)),
|
|
200
|
+
waitBy,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/** Returns { all, byProject } for jobs whose queue time lies in [since, until); the project that waited longest
|
|
204
|
+
* comes first. */
|
|
205
|
+
export function summarize(lines, since = 0, until = Infinity) {
|
|
206
|
+
const inRange = (row) => Date.parse(row.queuedAt) >= since && Date.parse(row.queuedAt) < until;
|
|
207
|
+
const rows = parseLines(lines).filter(inRange);
|
|
208
|
+
const groups = new Map();
|
|
209
|
+
for (const row of rows) {
|
|
210
|
+
const name = lineProject(row);
|
|
211
|
+
(groups.get(name) ?? groups.set(name, []).get(name)).push(row);
|
|
212
|
+
}
|
|
213
|
+
const perProject = [...groups].map(([name, group]) => [name, totals(group, until)])
|
|
214
|
+
.sort((a, b) => b[1].waitWallMin - a[1].waitWallMin || b[1].waitMinTotal - a[1].waitMinTotal);
|
|
215
|
+
return { all: totals(rows, until), byProject: Object.fromEntries(perProject) };
|
|
216
|
+
}
|