deployontime 0.0.0-stage → 0.1.1

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/queue/run.mjs ADDED
@@ -0,0 +1,628 @@
1
+ // The `run` command, in four steps: planJob decides the limit and whether the job is refused, skipFor whether a check
2
+ // that already passed on this code is skipped, waitForSlot waits in line until a slot is taken (for a nested run,
3
+ // waitForPlace waits until a place under its parent job is), and runJob runs the job in its own process group under
4
+ // the limit. runCommand chains them and returns the exit code; it never ends the process itself. These come in
5
+ // through deps, so tests can drive each step: the clock, sleeping and timers, the health reading, the commit read when
6
+ // the job is queued and again when it starts, the current folder, starting the job, signals sent to it and signals
7
+ // received, messages, notifications and stored notices, and the environment in which a nested run finds the marker
8
+ // of its parent job. The rest is done directly: the slot, line, nested, place and journal files in the folders named
9
+ // by files, the git calls for the project name and the code fingerprint, the process table read by snapshot and
10
+ // killTree, and this process's own pid and node binary.
11
+ import { spawn as spawnProcess } from "node:child_process";
12
+ import { rmSync } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+ import { parseRunArgs, USAGE, USAGE_EXIT } from "./args.mjs";
15
+ import { minutesSince } from "./clock.mjs";
16
+ import { failStop } from "./failstop.mjs";
17
+ import { fingerprint } from "./fingerprint.mjs";
18
+ import { blockReason, blockText, decide, gateBlocks, shouldGiveUp } from "./gate.mjs";
19
+ import { gitState as readGitState } from "./git.mjs";
20
+ import { healthVerdict } from "./health.mjs";
21
+ import { NO_START_EXIT, readStartFailure, wrapperEnd } from "./job-wrapper.mjs";
22
+ import {
23
+ addWait, append, cmdString, jobEnd, parseLines, readLines, record, SKIPPABLE_KINDS, skipStamp,
24
+ } from "./journal.mjs";
25
+ import { alsoBuilds, cmdStem, kindOf } from "./kinds.mjs";
26
+ import { decideLimit, kindStats, stemStats } from "./limits.mjs";
27
+ import { addNotice as storeNotice, longRunAlert } from "./notices.mjs";
28
+ import {
29
+ JOB_MARKER, markerOf, NO_SKIP_MARKER, PARENT_MARKER, parentJob, placeKey, slotMarkerOf, stillRunning,
30
+ } from "./nested.mjs";
31
+ import { killTree, signalGroup } from "./proctree.mjs";
32
+ import { folderProject, jobProject } from "./project.mjs";
33
+ import { addNested, enqueue, releaseSlot, snapshot, takePlace, takeSlot, updateSlot } from "./slots.mjs";
34
+ import { afterMs, MAX_TIMER_MS, wakeableSleep } from "./timer.mjs";
35
+ import { MINUTE } from "./units.mjs";
36
+
37
+ /** The exit codes of dotime-queue itself; a job that ran passes its own code on. */
38
+ export const EXIT = { usage: USAGE_EXIT, refused: 3, gaveUp: 75, timedOut: 124, noStart: NO_START_EXIT, left: 130 };
39
+ const REPEAT_WAIT_LINE_MS = MINUTE;
40
+ const WRAPPER = fileURLToPath(new URL("./job-wrapper.mjs", import.meta.url));
41
+ // Signals that take a waiting job out of the line, and signals that are passed on to a running job.
42
+ const LEAVE_SIGNALS = ["SIGINT", "SIGTERM"];
43
+ const FORWARD_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
44
+
45
+ /** Decides the run limit of a job and whether it is refused, from the journal rows alone; reads and changes
46
+ * nothing. request: { label, command (the command line as text), kind (given with --kind, or undefined), maxRun,
47
+ * priority, afterFix, project, cwd, head, fingerprint, queuedAt, tz }.
48
+ * Returns { kind, stem, limit, refusal, afterFixUsed, details }: refusal is null or { reason }; afterFixUsed is true
49
+ * when --after-fix let through a run that would have been refused; details go into the journal line, with the
50
+ * fingerprint as fp. */
51
+ export function planJob(request, settings, journalRows) {
52
+ const { label, command, maxRun, priority, afterFix, project, cwd, head, queuedAt, tz } = request;
53
+ const limits = settings.limits;
54
+ const kind = kindOf(label, command, request.kind);
55
+ const stem = cmdStem(command);
56
+ const window = { project, now: queuedAt, windowDays: limits.windowDays };
57
+ const stats = kindStats(journalRows, { ...window, kind });
58
+ const stemRuns = stemStats(journalRows, { ...window, stem });
59
+ const limit = decideLimit({ maxRun, kind, stats, stem: stemRuns, priority }, limits);
60
+ const check = { label, cmd: command, project, cwd, head, fingerprint: request.fingerprint, at: queuedAt };
61
+ const verdict = failStop(journalRows, check, limits, tz);
62
+ const details = {
63
+ kind,
64
+ ...(stem ? { stem } : {}),
65
+ limitMin: limit.limitMin,
66
+ limitBasis: limit.basis,
67
+ // Stored as fp, the name every copy of the queue that shares the journal reads.
68
+ fp: request.fingerprint,
69
+ ...(afterFix ? { afterFix } : {}),
70
+ };
71
+ return {
72
+ kind,
73
+ stem,
74
+ limit,
75
+ refusal: verdict.refuse && !afterFix ? { reason: verdict.reason } : null,
76
+ afterFixUsed: verdict.refuse && !!afterFix,
77
+ details,
78
+ };
79
+ }
80
+
81
+ /** Could a job of this kind and these words ever be skipped? Only a kind in SKIPPABLE_KINDS, and on a guessed kind
82
+ * only when neither the label nor the command also names a build or a deploy. job: { kind, kindGiven, label,
83
+ * command }. A job that could not is run, and so is everything nested in it. */
84
+ export function canSkip(job) {
85
+ return SKIPPABLE_KINDS.includes(job.kind) && (job.kindGiven || !alsoBuilds(job.label, job.command));
86
+ }
87
+
88
+ /** The pass stamp on which a job is skipped, or null when it must run. Only a job of a kind in SKIPPABLE_KINDS is
89
+ * ever skipped, and only on a stamp from skipStamp: a run of the same project, label and command, in the same folder
90
+ * and with the same code fingerprint, that passed on this commit with a clean tree, while the tree is still clean
91
+ * now, with no failure of it on the commit since. A job whose label or command also names a build or a deploy is
92
+ * never skipped on a guessed kind, since its output may be needed; only --kind test or --kind lint allows it.
93
+ * job: { kind, kindGiven (true when --kind was given), label, command, cwd, fingerprint, folderProject (the
94
+ * project of the folder, as journal lines store it in project), commit ({ head, clean }, read when the job was
95
+ * queued), noSkip, at, tz }. rows: the journal rows. */
96
+ export function skipFor(job, rows) {
97
+ if (job.noSkip || !canSkip(job)) return null;
98
+ const folder = { project: job.folderProject, ...job.commit };
99
+ const check = { label: job.label, cmd: job.command, cwd: job.cwd, fp: job.fingerprint };
100
+ return skipStamp(rows, folder, check, { tz: job.tz, at: job.at });
101
+ }
102
+
103
+ /** The advice for a wait held by low memory or disk: free some, or lower the limit in config.json. Empty for other
104
+ * reasons to wait. */
105
+ export function lowRoomHint(blocks, configFile) {
106
+ const keys = { memory: "health.minFreeMemPct", disk: "health.minFreeDiskGB" };
107
+ const low = blocks.filter((b) => keys[b.gate]);
108
+ if (!low.length) return "";
109
+ const what = low.map((b) => b.gate).join(" or ");
110
+ return `; hint: the job starts once there is more free ${what}; to start with less, lower `
111
+ + `${low.map((b) => keys[b.gate]).join(" and ")} in ${configFile}`;
112
+ }
113
+
114
+ /** Waits in line until this job holds a slot. job: { pid, label, maxWait, slotMeta, settings, files, waitFrom,
115
+ * tally }; waitFrom and tally, when given, carry on an earlier wait, so the wait limit counts from its start and the
116
+ * time is booked with it. Priority plays no part in here: it is in the job's ticket, which orders the line, and in
117
+ * slotMeta.
118
+ * deps: { now, sleep, readHealth, say, leaving }; leaving() names a signal that asked the job to leave, or null.
119
+ * Returns { slot, tally, waitFrom }, { gaveUp: true, tally } or { left: signal, tally }; tally is the waiting time
120
+ * per gate in ms. */
121
+ export async function waitForSlot(job, deps) {
122
+ const { pid, label, maxWait, settings, files } = job;
123
+ const max = settings.slots;
124
+ const tally = { ...job.tally };
125
+ const waitFrom = job.waitFrom ?? deps.now();
126
+ let shownPosition = 0;
127
+ let shownAt = 0;
128
+ let hinted = false;
129
+ for (;;) {
130
+ const signal = deps.leaving?.() ?? null;
131
+ if (signal) return { left: signal, tally };
132
+ const snap = snapshot({ dirs: files, prune: true });
133
+ const turn = decide(snap, pid, max);
134
+ const ahead = turn.position - 1;
135
+ // One reading per poll, taken only when something needs it; the message reuses it.
136
+ let reading = null;
137
+ const health = () => (reading ??= healthVerdict(deps.readHealth(), settings.health));
138
+ // Only full slots make the health reading irrelevant to a waiter.
139
+ const slotFree = snap.holders.length < max;
140
+ const gateHealth = turn.go || slotFree ? health() : null;
141
+ if (turn.go && gateHealth.ok) {
142
+ const slot = takeSlot(pid, label, max, job.slotMeta, files);
143
+ if (slot) return { slot, tally, waitFrom };
144
+ }
145
+ const heldBy = blockReason({ holders: snap.holders, health: gateHealth, ahead }, max);
146
+ const now = deps.now();
147
+ const giveUp = shouldGiveUp({ startedAt: waitFrom, now, maxWaitMin: maxWait });
148
+ if (giveUp || turn.position !== shownPosition || now - shownAt > REPEAT_WAIT_LINE_MS) {
149
+ const all = gateBlocks({ holders: snap.holders, health: health(), ahead }, max);
150
+ const why = blockText(all) || "slot lost: another job took it a moment ago";
151
+ const waited = `${minutesSince(waitFrom, now)} min waited`;
152
+ if (giveUp) {
153
+ deps.say(`gave up: exit ${EXIT.gaveUp}, position ${turn.position}, ${waited}; ${why}; `
154
+ + "hint: --max-wait 0 waits without limit");
155
+ return { gaveUp: true, tally };
156
+ }
157
+ const limitText = maxWait ? `wait limit ${maxWait} min` : "no wait limit";
158
+ // Low memory or disk does not pass by itself as a busy CPU does, so the first time it holds the job,
159
+ // the line says what to do about it.
160
+ const hint = hinted ? "" : lowRoomHint(all, files.config);
161
+ if (hint) hinted = true;
162
+ deps.say(`in line: position ${turn.position}, ${waited}, ${limitText}; ${why}${hint}`);
163
+ shownPosition = turn.position;
164
+ shownAt = now;
165
+ }
166
+ const sleptFrom = deps.now();
167
+ await deps.sleep(settings.pollMs);
168
+ // A poll that ends with a signal pending is not booked: the job leaves at the top of the loop.
169
+ if (deps.leaving?.()) continue;
170
+ addWait(tally, heldBy, deps.now() - sleptFrom);
171
+ }
172
+ }
173
+
174
+ /** Waits until a nested run holds one of the settings.nestedPerJob places under its parent job. Only the parent's
175
+ * places count: no slot, no line and no health gate, so a nested run can never wait for its own outer job. Nested
176
+ * runs that wait under the same parent take the places in the order their notes were written. job: { pid, label,
177
+ * parent, maxWait, settings, files }, where parent is the job from outerJob(). deps: { now, sleep, say, leaving },
178
+ * as for waitForSlot. Returns { place, tally, waitFrom, atOnce }, where atOnce is true when the first look found a
179
+ * place, { gaveUp: true, tally }, { left: signal, tally }, or { parentGone: true, tally, waitFrom } once the parent
180
+ * has ended: the run is then no longer inside a job, and must not start without a slot. The parent is checked on
181
+ * every poll, and once more after a place was taken. */
182
+ export async function waitForPlace(job, deps) {
183
+ const { pid, label, parent, maxWait, settings, files } = job;
184
+ const max = settings.nestedPerJob;
185
+ const key = placeKey(parent);
186
+ const marker = markerOf(parent.file);
187
+ const under = (n) => n.outer === marker && n.outerPid === parent.pid && n.outerBorn === parent.born;
188
+ const tally = {};
189
+ const waitFrom = deps.now();
190
+ let shownPosition = 0;
191
+ let shownAt = 0;
192
+ for (;;) {
193
+ const signal = deps.leaving?.() ?? null;
194
+ if (signal) return { left: signal, tally };
195
+ const snap = snapshot({ dirs: files, prune: true });
196
+ if (!stillRunning(parent, snap)) return { parentGone: true, tally, waitFrom };
197
+ const taken = snap.places.filter((p) => p.parent === key).length;
198
+ const waiters = snap.nested.filter((n) => n.waiting && under(n)).sort((a, b) => a.at - b.at || a.pid - b.pid);
199
+ const index = waiters.findIndex((n) => n.pid === pid);
200
+ const position = index < 0 ? waiters.length + 1 : index + 1;
201
+ if (position <= max - taken) {
202
+ const place = takePlace(pid, label, key, max, files);
203
+ if (place && !stillRunning(parent, snapshot({ dirs: files }))) {
204
+ releaseSlot(place, pid);
205
+ return { parentGone: true, tally, waitFrom };
206
+ }
207
+ if (place) return { place, tally, waitFrom, atOnce: shownPosition === 0 && !Object.keys(tally).length };
208
+ }
209
+ const ahead = position - 1;
210
+ const why = taken >= max
211
+ ? `no free nested place: ${taken} of ${max} taken under "${parent.label}", pid ${parent.pid}`
212
+ : ahead > 0 ? `not first in line under "${parent.label}": ${ahead} ahead`
213
+ : "place lost: another nested run took it a moment ago";
214
+ const now = deps.now();
215
+ const giveUp = shouldGiveUp({ startedAt: waitFrom, now, maxWaitMin: maxWait });
216
+ if (giveUp || position !== shownPosition || now - shownAt > REPEAT_WAIT_LINE_MS) {
217
+ const waited = `${minutesSince(waitFrom, now)} min waited`;
218
+ if (giveUp) {
219
+ deps.say(`gave up: exit ${EXIT.gaveUp}, nested position ${position}, ${waited}; ${why}; `
220
+ + "hint: --max-wait 0 waits without limit, and nestedPerJob in config.json sets the places");
221
+ return { gaveUp: true, tally };
222
+ }
223
+ const limitText = maxWait ? `wait limit ${maxWait} min` : "no wait limit";
224
+ deps.say(`in line for a nested place: position ${position}, ${waited}, ${limitText}; ${why}`);
225
+ shownPosition = position;
226
+ shownAt = now;
227
+ }
228
+ const sleptFrom = deps.now();
229
+ await deps.sleep(settings.pollMs);
230
+ if (deps.leaving?.()) continue;
231
+ addWait(tally, [{ gate: "nested" }], deps.now() - sleptFrom);
232
+ }
233
+ }
234
+
235
+ /** Runs the job in a slot it holds and resolves with the exit code for `run`. job: { pid, label, project, cwd, cmd
236
+ * (the words), priority, kind, limit, waitFrom, settings, files, tz, journal, handOver, slotMarker }, where journal
237
+ * is the writer from journalWriter() and handOver(), when given, is called as soon as the job's own signal handlers
238
+ * are in place, so the caller can remove the ones it had until then without a moment in which a signal finds none.
239
+ * The job finds the marker of its slot in JOB_MARKER and in PARENT_MARKER. A nested run passes its note in place of
240
+ * a slot and the marker of the outermost job's slot as slotMarker, so its job finds that slot in JOB_MARKER and the
241
+ * note in PARENT_MARKER, and the note gets the job's process group and is removed at the end the same way. With
242
+ * job.noSkip (given for --no-skip, and for a job that could not be skipped itself) the job finds "1" in
243
+ * NO_SKIP_MARKER, so the runs nested in it are never skipped; without it the variable is left out.
244
+ * deps: { now, spawn, say, after, later, kill, notify, addNotice, gitState, signals }: after(minutes, fn) is the long
245
+ * timer, later(ms, fn) a short one, each returning a function that cancels it, kill(pid, signal) sends a signal,
246
+ * addNotice(key, entry, file) stores a notice, gitState(cwd) reads the commit, and signals is the process whose INT,
247
+ * TERM, HUP and exit events are watched. Every handler and timer it adds is removed at the end. A run limit whose last
248
+ * KILL is refused is reported, and journalled with stopFailed, as a stop that failed. */
249
+ export function runJob(job, slot, deps) {
250
+ const { pid, label, project, limit, settings, files, tz, journal } = job;
251
+ const killGraceMs = settings.limits.killGraceMs;
252
+ const { say, signals } = deps;
253
+ // The commit is read at this point because it is what a pass stamp will vouch for.
254
+ const commit = deps.gitState(job.cwd);
255
+ const startedAt = deps.now();
256
+ journal.note({ commit, startedAt });
257
+ if (startedAt - job.waitFrom > 5000) say(`started: ${minutesSince(job.waitFrom, startedAt)} min in line`);
258
+ // File descriptor 3 is a pipe on which the wrapper reports a command that could not be started. Whether the
259
+ // job inherits it depends on the system, so the run ends when the wrapper exits and not when the pipe closes.
260
+ const stdio = ["inherit", "inherit", "inherit", "pipe"];
261
+ const env = { ...process.env, [JOB_MARKER]: job.slotMarker ?? markerOf(slot), [PARENT_MARKER]: markerOf(slot) };
262
+ // Only this job's own --no-skip, or the one it was handed as a nested run, reaches the runs nested in it.
263
+ delete env[NO_SKIP_MARKER];
264
+ if (job.noSkip) env[NO_SKIP_MARKER] = "1";
265
+ const child = deps.spawn(process.execPath, [WRAPPER, String(pid), ...job.cmd], { stdio, detached: true, env });
266
+ updateSlot(slot, pid, { pgid: child.pid, startedAt });
267
+ const signalJob = (signal) => {
268
+ if (signalGroup(child.pid, signal, deps.kill).sent) return;
269
+ try { child.kill(signal); } catch { /* already gone */ }
270
+ };
271
+
272
+ // INT, TERM and HUP go on to the job; the first one received is kept for the journal.
273
+ let received = null;
274
+ let receivedAt = null;
275
+ const forwarders = FORWARD_SIGNALS.map((signal) => [signal, () => {
276
+ if (!received) {
277
+ received = signal;
278
+ receivedAt = deps.now();
279
+ }
280
+ signalJob(signal);
281
+ }]);
282
+ const onExit = () => { if (child.exitCode === null && child.signalCode === null) signalJob("SIGTERM"); };
283
+ for (const [signal, handler] of forwarders) signals.on(signal, handler);
284
+ signals.on("exit", onExit);
285
+ job.handOver?.();
286
+
287
+ let pastLimit = false;
288
+ let longRunAt = null;
289
+ let warnedAt = null;
290
+ let ended = false;
291
+ const timers = [];
292
+ const after = (minutes, fn) => { timers.push(deps.after(minutes, fn)); };
293
+ const later = (ms, fn) => { timers.push(deps.later(ms, fn)); };
294
+ let done;
295
+ const result = new Promise((resolve) => { done = resolve; });
296
+ const end = (exit) => {
297
+ if (ended) return;
298
+ ended = true;
299
+ releaseSlot(slot, pid);
300
+ for (const [signal, handler] of forwarders) signals.off(signal, handler);
301
+ // Safe to drop: the wrapper has exited, or the backstop ended a run whose last KILL was refused, and a TERM
302
+ // at exit would be refused the same way.
303
+ signals.off("exit", onExit);
304
+ for (const cancel of timers) cancel();
305
+ done(exit);
306
+ };
307
+ const stamps = () => ({
308
+ ...(longRunAt ? { longRunAt: new Date(longRunAt).toISOString() } : {}),
309
+ ...(warnedAt ? { warnedAt: new Date(warnedAt).toISOString() } : {}),
310
+ });
311
+ const killJob = (signal) => killTree(child.pid, signal, { kill: deps.kill });
312
+ // The last KILL decides: a process it cannot signal is still there, so the stop failed. A TERM refused earlier
313
+ // to a process that has ended since does not count.
314
+ const endTimedOut = () => {
315
+ if (ended) return;
316
+ const refused = killJob("SIGKILL").refused;
317
+ const why = refused.length ? `KILL refused for ${refused.join(", ")}` : null;
318
+ journal.finish("timed-out", EXIT.timedOut, { ...stamps(), ...(why ? { stopFailed: why } : {}) });
319
+ const how = why ? `stop failed after ${limit.killMin} min, ${why}` : `stopped after ${limit.killMin} min`;
320
+ say(`timed out: exit ${EXIT.timedOut}, ${how}; hint: the kind was taken as `
321
+ + `${job.kind} (--kind <name> overrides it), and --max-run <min> sets the limit directly`);
322
+ end(EXIT.timedOut);
323
+ };
324
+ after(limit.killMin, () => {
325
+ pastLimit = true;
326
+ say(`run limit: stopping "${label}", KILL follows TERM after ${killGraceMs / 1000} s; ran ${limit.killMin} min `
327
+ + `against a limit of ${limit.limitMin} min, set by ${limit.basis}`);
328
+ killJob("SIGTERM");
329
+ later(killGraceMs, () => killJob("SIGKILL"));
330
+ // Backstop for a wrapper that never exits.
331
+ later(Math.min(killGraceMs + 5000, MAX_TIMER_MS), endTimedOut);
332
+ });
333
+ if (job.priority) {
334
+ after(limit.limitMin, () => {
335
+ warnedAt = deps.now();
336
+ say(`priority warning: hard stop at ${limit.killMin} min, the ${limit.limitMin} min limit `
337
+ + `(set by ${limit.basis}) was passed by "${label}"`);
338
+ });
339
+ }
340
+ if (limit.notifyLongRun) {
341
+ after(limit.longRunMin, () => {
342
+ longRunAt = deps.now();
343
+ try {
344
+ const alert = longRunAlert({
345
+ label, project, pid, minutes: minutesSince(startedAt, longRunAt), longRunBasis: limit.longRunBasis,
346
+ limitMin: limit.limitMin, killMin: limit.killMin, startedAt,
347
+ waiting: snapshot({ dirs: files }).queue, now: longRunAt, tz,
348
+ });
349
+ say(alert.message);
350
+ deps.notify(alert.title, alert.message);
351
+ deps.addNotice(alert.key, alert.entry, files.notices);
352
+ } catch { /* a notice that fails must not disturb the job */ }
353
+ });
354
+ }
355
+ wrapperEnd(child, child.stdio[3]).then(({ code, signal, report }) => {
356
+ if (pastLimit) return endTimedOut();
357
+ const startFailed = readStartFailure(report);
358
+ if (startFailed !== null) {
359
+ journal.finish("could-not-start", EXIT.noStart, stamps());
360
+ say(`start failed: exit ${EXIT.noStart}, ${startFailed}`);
361
+ return end(EXIT.noStart);
362
+ }
363
+ const exit = code ?? (signal ? 1 : 0);
364
+ const how = jobEnd({ code, signal, received });
365
+ const stoppedAt = new Date(receivedAt ?? deps.now()).toISOString();
366
+ const stopped = how.signal ? { signal: how.signal, stoppedAt } : {};
367
+ journal.finish(how.outcome, exit, { ...stamps(), ...stopped });
368
+ if (how.signal) {
369
+ say(`stopped: signal ${how.signal}, ${minutesSince(startedAt, deps.now())} min run, `
370
+ + "journalled as stopped and not as failed");
371
+ }
372
+ end(exit);
373
+ });
374
+ // The wrapper is node itself, so this happens only when the system cannot start a process at all.
375
+ child.on("error", (e) => {
376
+ journal.finish("could-not-start", EXIT.noStart);
377
+ say(`start failed: exit ${EXIT.noStart}, ${e.message}`);
378
+ end(EXIT.noStart);
379
+ });
380
+ return result;
381
+ }
382
+
383
+ /** The writer of a job's one journal line. note({ startedAt, commit, tally, details }) fills in any of those as the
384
+ * job goes; finish() writes the line once and ignores later calls. pid, when given, is the pid of the `run` process,
385
+ * kept with the line so a caller that started that process can find its own line. */
386
+ export function journalWriter({ label, folder, cwd, priority, queuedAt, command, details, file, now, pid }) {
387
+ const known = { startedAt: null, commit: { head: null, clean: null }, tally: {}, details };
388
+ let written = false;
389
+ return {
390
+ note(fields) {
391
+ for (const name of Object.keys(known)) if (fields[name] !== undefined) known[name] = fields[name];
392
+ },
393
+ finish(outcome, exit, more = {}) {
394
+ if (written) return;
395
+ written = true;
396
+ const { head, clean } = known.commit;
397
+ append(record({
398
+ label, project: folder, cwd, priority, queuedAt, startedAt: known.startedAt, endedAt: now(), outcome,
399
+ exit, tally: known.tally, cmd: command, head, clean, extra: { ...(pid ? { pid } : {}), ...known.details, ...more },
400
+ }), file);
401
+ },
402
+ };
403
+ }
404
+
405
+ const sleepFor = (ms) => new Promise((done) => setTimeout(done, ms));
406
+
407
+ /** The deps of the real command. readHealth, notify and after(minutes, fn) come from the entry point. */
408
+ export function realDeps({ readHealth, notify, after }) {
409
+ return {
410
+ now: Date.now,
411
+ sleep: sleepFor,
412
+ readHealth,
413
+ spawn: spawnProcess,
414
+ say: (text) => process.stderr.write(`dotime-queue: ${text}\n`),
415
+ usage: (text) => process.stderr.write(`${text}\n`),
416
+ after,
417
+ later: afterMs,
418
+ kill: (pid, signal) => process.kill(pid, signal),
419
+ notify,
420
+ addNotice: storeNotice,
421
+ gitState: readGitState,
422
+ signals: process,
423
+ cwd: () => process.cwd(),
424
+ env: process.env,
425
+ };
426
+ }
427
+
428
+ /** The folder the job runs in: ctx.cwd when given, else the current folder, read through deps.cwd(). Returns
429
+ * { cwd } or { error } when the current folder was removed. */
430
+ export function jobFolder(ctx, deps) {
431
+ if (ctx.cwd !== undefined) return { cwd: ctx.cwd };
432
+ try {
433
+ return { cwd: deps.cwd() };
434
+ } catch (e) {
435
+ if (e.code !== "ENOENT") throw e;
436
+ return { error: "the current folder was removed; start the job from a folder that exists" };
437
+ }
438
+ }
439
+
440
+ /** Runs `dotime-queue run <args>` and resolves with its exit code. ctx: { settings, files, tz, cwd }; without cwd
441
+ * the current folder is read, and only after the arguments were found valid, so a usage error is reported the same
442
+ * way in a folder that was removed. A signal while the job waits takes it out of the line and resolves with 130
443
+ * instead of ending the process. A run whose deps.env holds a genuine marker of the job it runs in, in
444
+ * PARENT_MARKER or JOB_MARKER, is nested: once past the refusal check it runs with no slot, no place in line and no
445
+ * health gate, as soon as a place under that job is free. A test or lint check that already passed on the same clean
446
+ * commit is not run at all, nested or not, unless --no-skip is given: see skipFor. It takes no slot or place, is
447
+ * journalled as skipped with the stamp it relied on, and resolves with 0. */
448
+ export async function runCommand(args, ctx, deps) {
449
+ const { settings, files, tz } = ctx;
450
+ const { say, signals } = deps;
451
+ const parsed = parseRunArgs(args, settings);
452
+ if (parsed.error) {
453
+ if (parsed.error === USAGE) deps.usage(USAGE);
454
+ else say(parsed.error);
455
+ return EXIT.usage;
456
+ }
457
+ const folderRead = jobFolder(ctx, deps);
458
+ if (folderRead.error) {
459
+ say(folderRead.error);
460
+ return EXIT.usage;
461
+ }
462
+ const { cwd } = folderRead;
463
+ const { label, cmd, priority, maxWait, maxRun, afterFix } = parsed;
464
+ const queuedAt = deps.now();
465
+ const folder = folderProject(cwd);
466
+ const command = cmdString(cmd);
467
+ const project = jobProject({ label, project: folder, cwd });
468
+ const before = deps.gitState(cwd);
469
+ const print = fingerprint(cwd, cmd, settings.outputDirs);
470
+ const request = { label, command, kind: parsed.kind, maxRun, priority, afterFix, project, cwd, queuedAt, tz };
471
+ // The journal is read and parsed once for the whole plan.
472
+ const rows = parseLines(readLines(files.journal));
473
+ const plan = planJob({ ...request, head: before.head, fingerprint: print }, settings, rows);
474
+ const pid = process.pid;
475
+ const markers = deps.env?.[PARENT_MARKER] || deps.env?.[JOB_MARKER];
476
+ const outer = markers ? parentJob({ env: deps.env, pid, ...snapshot({ dirs: files }) }) : null;
477
+ const details = outer ? { ...plan.details, nested: true } : plan.details;
478
+ const journal = journalWriter({
479
+ label, folder, cwd, priority, queuedAt, command, details, file: files.journal, now: deps.now, pid,
480
+ });
481
+ if (plan.refusal) {
482
+ journal.note({ commit: before });
483
+ journal.finish("refused", EXIT.refused);
484
+ say(`refused: exit ${EXIT.refused}; ${plan.refusal.reason}`);
485
+ return EXIT.refused;
486
+ }
487
+ // --no-skip on the outer job reaches every run nested in it.
488
+ const noSkip = parsed.noSkip || (!!outer && deps.env?.[NO_SKIP_MARKER] === "1");
489
+ const check = { kind: plan.kind, kindGiven: parsed.kind !== undefined, label, command };
490
+ const where = { cwd, fingerprint: print, folderProject: folder, commit: before };
491
+ const stamp = skipFor({ ...check, ...where, noSkip, at: queuedAt, tz }, rows);
492
+ if (stamp) {
493
+ const ago = Math.max(0, Math.round((deps.now() - Date.parse(stamp.endedAt)) / MINUTE));
494
+ journal.note({ commit: before });
495
+ // The stamp is kept with the line, so history can tell how much run time the skip saved.
496
+ journal.finish("skipped", 0, { stamp: { head: stamp.head, endedAt: stamp.endedAt, runMin: stamp.runMin } });
497
+ say(`skipped: "${label}" already passed on commit ${String(stamp.head).slice(0, 8)} (${ago} min ago); `
498
+ + "--no-skip runs it anyway");
499
+ return 0;
500
+ }
501
+ if (plan.afterFixUsed) {
502
+ say(`--after-fix accepted: note "${afterFix}", the check had failed twice on unchanged code`);
503
+ }
504
+ const { limit, kind } = plan;
505
+ // INT and TERM wake the wait, which then returns, so the one exit path in main() ends the process. The leave
506
+ // handlers stay until runJob has added its own: with no listener at all, a signal would end the process at once,
507
+ // with no journal line and the slot, place or note left behind. A signal that arrives while the job is being
508
+ // started reaches the handlers of the job and is passed on to it.
509
+ const watch = watchLeave(signals, deps.sleep);
510
+ const job = {
511
+ pid, label, project, cwd, cmd, priority, kind, limit, settings, files, tz, journal, maxWait, handOver: watch.drop,
512
+ // Nothing nested in a job that could not be skipped itself, such as a build, is ever skipped: the job may
513
+ // need what its steps make.
514
+ noSkip: noSkip || !canSkip(check),
515
+ };
516
+ const waitDeps = { ...deps, sleep: watch.sleep, leaving: watch.leaving };
517
+ try {
518
+ if (!outer) return await runInLine(job, waitDeps, deps);
519
+ const nested = await runNested({ ...job, outer }, waitDeps, deps);
520
+ if (!nested.parentGone) return nested.exit;
521
+ say(`parent gone: "${outer.label}", pid ${outer.pid}, ended while this run waited for a nested place; `
522
+ + "joins the line as a normal run");
523
+ journal.note({ details: plan.details });
524
+ return await runInLine({ ...job, waitFrom: nested.waitFrom, tally: nested.tally }, waitDeps, deps);
525
+ } finally {
526
+ watch.drop();
527
+ }
528
+ }
529
+
530
+ /** Watches INT and TERM while a run waits: the first one is kept, and each wakes the wait. Returns { leaving, sleep,
531
+ * drop }: leaving() names that signal or gives null, sleep is deps.sleep made wakeable, and drop() removes the
532
+ * handlers; calling it again does nothing. */
533
+ function watchLeave(signals, sleep) {
534
+ let leaving = null;
535
+ let dropped = false;
536
+ const sleeps = wakeableSleep(sleep);
537
+ const leavers = LEAVE_SIGNALS.map((signal) => [signal, () => {
538
+ leaving ??= signal;
539
+ sleeps.wake();
540
+ }]);
541
+ for (const [signal, handler] of leavers) signals.on(signal, handler);
542
+ const drop = () => {
543
+ if (dropped) return;
544
+ dropped = true;
545
+ for (const [signal, handler] of leavers) signals.off(signal, handler);
546
+ };
547
+ return { leaving: () => leaving, sleep: sleeps.sleep, drop };
548
+ }
549
+
550
+ /** Journals a wait that ended without a slot or place, and gives its exit code: 130 for a signal, 75 for the wait
551
+ * limit. Gives null when the wait ended with a slot or place and no signal is pending. */
552
+ function endOfWait(waited, journal, leaving) {
553
+ journal.note({ tally: waited.tally });
554
+ if (waited.left || leaving) {
555
+ journal.finish("left", EXIT.left, { signal: waited.left ?? leaving });
556
+ return EXIT.left;
557
+ }
558
+ if (waited.gaveUp) {
559
+ journal.finish("gave-up", EXIT.gaveUp);
560
+ return EXIT.gaveUp;
561
+ }
562
+ return null;
563
+ }
564
+
565
+ /** Runs a job that waits in line for a slot. job is the one runJob takes, with maxWait, and with waitFrom and tally
566
+ * only when it carries on an earlier wait. waitDeps are deps with the wakeable sleep and leaving() of runCommand. */
567
+ async function runInLine(job, waitDeps, deps) {
568
+ const { pid, label, priority, kind, limit, project, cwd, settings, files, journal, maxWait } = job;
569
+ const { signals } = deps;
570
+ const ticket = enqueue(pid, label, priority, files);
571
+ let slot = null;
572
+ const leaveLine = () => {
573
+ rmSync(ticket, { force: true });
574
+ releaseSlot(slot, pid);
575
+ };
576
+ signals.on("exit", leaveLine);
577
+ const slotMeta = {
578
+ kind, limitMin: limit.limitMin, killMin: limit.killMin, longRunMin: limit.longRunMin, project, cwd,
579
+ ...(priority ? { priority: true } : {}),
580
+ };
581
+ try {
582
+ const { waitFrom, tally } = job;
583
+ const waited = await waitForSlot({ pid, label, maxWait, slotMeta, settings, files, waitFrom, tally }, waitDeps);
584
+ slot = waited.slot ?? null;
585
+ const ended = endOfWait(waited, journal, waitDeps.leaving());
586
+ if (ended !== null) return ended;
587
+ rmSync(ticket, { force: true });
588
+ return await runJob({ ...job, waitFrom: waited.waitFrom }, slot, deps);
589
+ } finally {
590
+ leaveLine();
591
+ signals.off("exit", leaveLine);
592
+ }
593
+ }
594
+
595
+ /** Runs a nested job: in no slot, but in one of the places under its parent job, the one in outer, waiting for one
596
+ * when all are taken. It is noted in the nested folder from the start, so `status` can show it under its parent, and
597
+ * the note is the marker its own job is handed. job is the one runJob takes, without waitFrom, and with outer and
598
+ * maxWait; waitDeps are as for runInLine. While it waits, INT and TERM take it out as they take a job out of the
599
+ * line; from the handlers runJob adds onwards everything is the same as for a job in a slot. Resolves with { exit },
600
+ * or with { parentGone: true, tally, waitFrom } when the parent ended while the run waited; its note is removed
601
+ * then, and the caller sends it to the line. */
602
+ async function runNested(job, waitDeps, deps) {
603
+ const { pid, label, outer, files, journal, maxWait, settings } = job;
604
+ const { signals, say } = deps;
605
+ const intro = `nested: inside "${outer.label}", pid ${outer.pid}`;
606
+ const parent = { marker: markerOf(outer.file), pid: outer.pid, born: outer.born, slot: slotMarkerOf(outer) };
607
+ const note = addNested(pid, label, parent, files, { waiting: true });
608
+ let place = null;
609
+ const leave = () => {
610
+ rmSync(note, { force: true });
611
+ releaseSlot(place, pid);
612
+ };
613
+ signals.on("exit", leave);
614
+ try {
615
+ const waited = await waitForPlace({ pid, label, parent: outer, maxWait, settings, files }, waitDeps);
616
+ place = waited.place ?? null;
617
+ if (waited.parentGone && !waitDeps.leaving()) return waited;
618
+ const ended = endOfWait(waited, journal, waitDeps.leaving());
619
+ if (ended !== null) return { exit: ended };
620
+ say(waited.atOnce ? `${intro}; starts at once: no slot, no place in line, no health gate`
621
+ : `${intro}; starts now that a nested place is free: no slot, no place in line, no health gate`);
622
+ updateSlot(note, pid, { waiting: undefined });
623
+ return { exit: await runJob({ ...job, waitFrom: waited.waitFrom, slotMarker: parent.slot }, note, deps) };
624
+ } finally {
625
+ leave();
626
+ signals.off("exit", leave);
627
+ }
628
+ }