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,144 @@
1
+ // Slots, the waiting line, the nested runs and their places, stored as small JSON files in the state folder so
2
+ // unrelated processes can share them without a server. A slot, and a nested run's place under its parent job, is
3
+ // claimed with a hard link, which only one process can win. Every file is written under a temporary name and then
4
+ // moved into place, so a reader never meets half a file.
5
+ import { linkSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { probeProcessAges } from "./probes.mjs";
8
+ import { parseElapsed } from "./ps.mjs";
9
+ import { alive } from "./proctree.mjs";
10
+ import { dropOldTemp, readJson, tempName, writeJsonAtomic } from "./files.mjs";
11
+
12
+ // When this process started (wall clock, ms). Its own entries carry it, so a reader can tell this process from a newer
13
+ // one that was given the same pid after it ended without cleaning up.
14
+ const BORN = Math.round(Date.now() - process.uptime() * 1000);
15
+ const SAME_START_MS = 5000;
16
+ const bornOf = (pid) => (pid === process.pid ? { born: BORN } : {});
17
+
18
+ /** Seconds each of the given processes has run, by pid. */
19
+ const processAges = (pids) => parseElapsed(probeProcessAges(pids));
20
+ const isEntryName = (name) => name.endsWith(".json");
21
+ // dirs: the slots and waitingLine folders, as paths() names them.
22
+ function makeDirs(dirs) {
23
+ mkdirSync(dirs.slots, { recursive: true });
24
+ mkdirSync(dirs.waitingLine, { recursive: true });
25
+ }
26
+ // An entry whose pid now belongs to a process that started later than the entry says.
27
+ function pidReused(data, seconds, now) {
28
+ return seconds !== undefined && Math.abs(now - seconds * 1000 - data.born) > SAME_START_MS;
29
+ }
30
+ const lineOrder = (a, b) => Number(!!b.priority) - Number(!!a.priority) || a.at - b.at || a.pid - b.pid;
31
+
32
+ /** Returns { holders, queue }: the jobs holding a slot, and the line in start order; each entry carries the path of
33
+ * its file. When dirs names a nested folder, nested lists the nested runs too, and when it names a places folder,
34
+ * places lists the places nested runs hold. Entries of dead processes, and
35
+ * entries whose pid now belongs to a process that started later, are left out. Only with prune are their files, and
36
+ * abandoned temporary files, deleted and the slot and line folders created: a job that waits for a slot prunes, so
37
+ * the slot of a dead job comes free; `status` and other readers change nothing. */
38
+ export function snapshot({ dirs, isAlive = alive, ages = processAges, now = Date.now(), prune = false }) {
39
+ if (prune) makeDirs(dirs);
40
+ const liveEntries = (dir) => {
41
+ let names = [];
42
+ try { names = readdirSync(dir); } catch { /* no folder yet */ }
43
+ const found = [];
44
+ for (const name of names) {
45
+ const file = join(dir, name);
46
+ // A temporary name is a write in progress by another process: leave it alone unless it was abandoned.
47
+ if (!isEntryName(name)) {
48
+ if (prune) dropOldTemp(file, now);
49
+ continue;
50
+ }
51
+ const data = readJson(file);
52
+ found.push({ file, data, ok: Number.isInteger(data?.pid) && isAlive(data.pid) });
53
+ }
54
+ // An entry that names its start time is compared with the age of the process that has its pid now.
55
+ const known = ages(found.filter((e) => e.ok && Number.isFinite(e.data.born)).map((e) => e.data.pid));
56
+ const entries = [];
57
+ for (const { file, data, ok } of found) {
58
+ const seconds = ok && Number.isFinite(data.born) ? known.get(data.pid) : undefined;
59
+ if (ok && !pidReused(data, seconds, now)) entries.push({ file, ...data });
60
+ else if (prune) rmSync(file, { force: true });
61
+ }
62
+ return entries;
63
+ };
64
+ const holders = liveEntries(dirs.slots);
65
+ const queue = liveEntries(dirs.waitingLine).sort(lineOrder);
66
+ return {
67
+ holders, queue,
68
+ ...(dirs.nested ? { nested: liveEntries(dirs.nested) } : {}),
69
+ ...(dirs.places ? { places: liveEntries(dirs.places) } : {}),
70
+ };
71
+ }
72
+
73
+ /** Notes a nested run, one that runs inside another job and takes no slot itself. outer: { marker, pid, born, slot },
74
+ * the marker of the job it runs in, its direct parent (a slot holder or another nested run), and that job's pid and
75
+ * start time, stored as outer, outerPid and outerBorn so the note is never taken for one of a later job with the same
76
+ * marker; slot, when given, is the marker of the outermost job's slot, which the run hands its own job. waiting:
77
+ * the run waits for a place under that job, which updateSlot(file, pid, { waiting: undefined }) ends. The file is
78
+ * named nested-<pid>.json, and its name without the ending is the marker of the direct parent the run hands its own
79
+ * job. Returns the file; deleting it removes the note. */
80
+ export function addNested(pid, label, outer, dirs, { waiting = false, now = Date.now() } = {}) {
81
+ mkdirSync(dirs.nested, { recursive: true });
82
+ const file = join(dirs.nested, `nested-${pid}.json`);
83
+ const from = { outer: outer.marker, outerPid: outer.pid, outerBorn: outer.born, ...(outer.slot ? { slot: outer.slot } : {}) };
84
+ writeJsonAtomic(file, { pid, label, ...from, at: now, ...(waiting ? { waiting: true } : {}), ...bornOf(pid) });
85
+ return file;
86
+ }
87
+
88
+ /** Claims one of the max places under a parent job for a nested run. parent: the key of that job, from placeKey().
89
+ * Returns the place file, or null when all are taken. releaseSlot() frees it. */
90
+ export function takePlace(pid, label, parent, max, dirs, now = Date.now()) {
91
+ mkdirSync(dirs.places, { recursive: true });
92
+ for (let n = 0; n < max; n++) {
93
+ const place = join(dirs.places, `${parent}.${n}.json`);
94
+ const temp = tempName(place);
95
+ writeFileSync(temp, JSON.stringify({ pid, label, parent, at: now, ...bornOf(pid) }));
96
+ try {
97
+ linkSync(temp, place);
98
+ return place;
99
+ } catch { /* another nested run holds this place */ } finally { rmSync(temp, { force: true }); }
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /** Joins the line. Returns the ticket file; deleting it leaves the line. */
105
+ export function enqueue(pid, label, priority, dirs, now = Date.now()) {
106
+ makeDirs(dirs);
107
+ const ticket = join(dirs.waitingLine, `${now}-${pid}.json`);
108
+ writeJsonAtomic(ticket, { pid, label, at: now, ...(priority ? { priority: true } : {}), ...bornOf(pid) });
109
+ return ticket;
110
+ }
111
+
112
+ /** Claims a free slot. Returns the slot file, or null when all are taken. */
113
+ export function takeSlot(pid, label, max, meta, dirs) {
114
+ makeDirs(dirs);
115
+ for (let n = 0; n < max; n++) {
116
+ const slot = join(dirs.slots, `slot-${n}.json`);
117
+ const temp = tempName(slot);
118
+ writeFileSync(temp, JSON.stringify({ pid, label, at: Date.now(), ...meta, ...bornOf(pid) }));
119
+ try {
120
+ linkSync(temp, slot);
121
+ return slot;
122
+ } catch { /* another process holds this slot */ } finally { rmSync(temp, { force: true }); }
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /** Frees a slot or a place, but only for the pid that holds it. */
128
+ export function releaseSlot(slot, pid) {
129
+ if (slot && readJson(slot)?.pid === pid) rmSync(slot, { force: true });
130
+ }
131
+
132
+ /** Merges `fields` into `slot` if `pid` owns it; false otherwise, and false when the write fails. It never throws:
133
+ * a job calls it after its command has started, and a failed note must not end the job and leave the command
134
+ * running on its own. */
135
+ export function updateSlot(slot, pid, fields) {
136
+ const current = slot && readJson(slot);
137
+ if (current?.pid !== pid) return false;
138
+ try {
139
+ writeJsonAtomic(slot, { ...current, ...fields });
140
+ } catch {
141
+ return false;
142
+ }
143
+ return true;
144
+ }
@@ -0,0 +1,8 @@
1
+ // Statistics shared by the run limits and `history`, so both mean the same thing by a percentile.
2
+
3
+ /** Nearest-rank percentile, p from 0 to 1; null for an empty list. */
4
+ export function pctl(values, p) {
5
+ if (!values.length) return null;
6
+ const sorted = [...values].sort((a, b) => a - b);
7
+ return sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)];
8
+ }
@@ -0,0 +1,38 @@
1
+ // Finds large test runs that did not come through the queue, so the reaper can report them. A run belongs to the
2
+ // queue when it descends from a process that holds a slot. Small runs outside the queue are left alone.
3
+ import { ancestors, descendants, treeIndex } from "./proctree.mjs";
4
+ import { SHELL_PROGRAM_RE, STRAY_TEST_RE } from "./commands.mjs";
5
+
6
+ // Reported when the run has at least two test processes using minMB together, or minProcs test processes of any size.
7
+ export const STRAY = { minMB: 2048, minProcs: 5 };
8
+
9
+ // "sh -c jest" matches through its argument; a shell is only the launcher of the run.
10
+ const isTestProcess = (row) => STRAY_TEST_RE.test(row.cmd) && !SHELL_PROGRAM_RE.test(row.cmd);
11
+
12
+ /** rows: [{ pid, ppid, rss (KB), cmd }]; holders: slot entries with pid and pgid.
13
+ * Returns [{ rootPid, procs, rssMB, cmd }], largest first. */
14
+ export function strayRuns(rows, { holders = [], minMB = STRAY.minMB, minProcs = STRAY.minProcs } = {}) {
15
+ const index = treeIndex(rows);
16
+ const queuePids = new Set(holders.flatMap((h) => [h.pid, h.pgid]).filter(Number.isInteger));
17
+ // The same check on ppid covers a holder that is missing from the rows.
18
+ const underQueue = (chain) => chain.some((p) => queuePids.has(p.pid) || queuePids.has(p.ppid));
19
+
20
+ const roots = new Map();
21
+ for (const row of rows) {
22
+ if (!isTestProcess(row)) continue;
23
+ const chain = ancestors(index, row.pid);
24
+ if (underQueue(chain)) continue;
25
+ const top = chain.findLast(isTestProcess);
26
+ roots.set(top.pid, top);
27
+ }
28
+
29
+ const found = [];
30
+ for (const root of roots.values()) {
31
+ const tree = [...descendants(index, [root.pid])].map((pid) => index.byPid.get(pid));
32
+ const tests = tree.filter(isTestProcess);
33
+ const rssMB = Math.round(tests.reduce((sum, p) => sum + (p.rss || 0), 0) / 1024);
34
+ const large = (rssMB >= minMB && tests.length >= 2) || tests.length >= minProcs;
35
+ if (large) found.push({ rootPid: root.pid, procs: tests.length, rssMB, cmd: root.cmd });
36
+ }
37
+ return found.sort((a, b) => b.rssMB - a.rssMB);
38
+ }
@@ -0,0 +1,47 @@
1
+ // Long timers, and a sleep that can be ended early. Node fires a timer longer than about 24 days after 1 ms, so a
2
+ // longer wait is made of several timers in a row.
3
+ import { MINUTE } from "./units.mjs";
4
+
5
+ /** The longest wait one Node timer can hold, in ms. */
6
+ export const MAX_TIMER_MS = 2 ** 31 - 1;
7
+
8
+ /** An unref'd timer measured in minutes. Returns a function that cancels it, also when the wait is made of several
9
+ * timers in a row. schedule and unschedule stand in for setTimeout and clearTimeout. */
10
+ export function afterMinutes(min, fn, schedule = setTimeout, unschedule = clearTimeout) {
11
+ let current = null;
12
+ const step = (ms) => {
13
+ const next = () => (ms > MAX_TIMER_MS ? step(ms - MAX_TIMER_MS) : fn());
14
+ current = schedule(next, Math.min(ms, MAX_TIMER_MS)).unref();
15
+ };
16
+ step(min * MINUTE);
17
+ return () => unschedule(current);
18
+ }
19
+
20
+ /** An unref'd timer in ms. Returns a function that cancels it. */
21
+ export function afterMs(ms, fn) {
22
+ const timer = setTimeout(fn, ms).unref();
23
+ return () => clearTimeout(timer);
24
+ }
25
+
26
+ /** Wraps sleep(ms) so that wake() ends the current sleeps and makes every later one end at once. A sleep that has
27
+ * ended, either way, is dropped from the list of sleeps to wake, so many sleeps in a row keep nothing.
28
+ * pending() is the number of sleeps that have not ended. */
29
+ export function wakeableSleep(sleep) {
30
+ const sleeping = new Set();
31
+ let woken = false;
32
+ return {
33
+ sleep(ms) {
34
+ if (woken) return Promise.resolve();
35
+ return new Promise((resolve) => {
36
+ const finish = () => { if (sleeping.delete(finish)) resolve(); };
37
+ sleeping.add(finish);
38
+ sleep(ms).then(finish);
39
+ });
40
+ },
41
+ wake() {
42
+ woken = true;
43
+ for (const finish of [...sleeping]) finish();
44
+ },
45
+ pending: () => sleeping.size,
46
+ };
47
+ }
@@ -0,0 +1,8 @@
1
+ // Time units and rounding that several modules use, written once.
2
+
3
+ export const MINUTE = 60_000;
4
+ export const HOUR = 60 * MINUTE;
5
+ export const DAY = 24 * HOUR;
6
+
7
+ /** A number rounded to one decimal place. */
8
+ export const oneDecimal = (x) => Math.round(x * 10) / 10;