@prestyj/cli 5.35.1 → 5.37.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/dist/cli/command-routing.d.ts +1 -1
- package/dist/cli/command-routing.js +2 -1
- package/dist/cli/command-routing.js.map +1 -1
- package/dist/cli/validate.d.ts +4 -0
- package/dist/cli/validate.js +267 -0
- package/dist/cli/validate.js.map +1 -0
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-notifications.d.ts +1 -1
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.js +7 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/validation/backends.d.ts +20 -0
- package/dist/core/validation/backends.js +57 -0
- package/dist/core/validation/backends.js.map +1 -0
- package/dist/core/validation/config.d.ts +30 -0
- package/dist/core/validation/config.js +247 -0
- package/dist/core/validation/config.js.map +1 -0
- package/dist/core/validation/exec.d.ts +3 -0
- package/dist/core/validation/exec.js +17 -0
- package/dist/core/validation/exec.js.map +1 -0
- package/dist/core/validation/github-actions-backend.d.ts +82 -0
- package/dist/core/validation/github-actions-backend.js +435 -0
- package/dist/core/validation/github-actions-backend.js.map +1 -0
- package/dist/core/validation/local-backend.d.ts +18 -0
- package/dist/core/validation/local-backend.js +101 -0
- package/dist/core/validation/local-backend.js.map +1 -0
- package/dist/core/validation/scheduler.d.ts +38 -0
- package/dist/core/validation/scheduler.js +133 -0
- package/dist/core/validation/scheduler.js.map +1 -0
- package/dist/core/validation/service.d.ts +175 -0
- package/dist/core/validation/service.js +905 -0
- package/dist/core/validation/service.js.map +1 -0
- package/dist/core/validation/session-hook.d.ts +3 -0
- package/dist/core/validation/session-hook.js +32 -0
- package/dist/core/validation/session-hook.js.map +1 -0
- package/dist/core/validation/store.d.ts +10 -0
- package/dist/core/validation/store.js +48 -0
- package/dist/core/validation/store.js.map +1 -0
- package/dist/core/validation/types.d.ts +177 -0
- package/dist/core/validation/types.js +16 -0
- package/dist/core/validation/types.js.map +1 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/prompt-hints.js +2 -0
- package/dist/tools/prompt-hints.js.map +1 -1
- package/dist/tools/tool-tiers.js +1 -0
- package/dist/tools/tool-tiers.js.map +1 -1
- package/dist/tools/validate.d.ts +21 -0
- package/dist/tools/validate.js +106 -0
- package/dist/tools/validate.js.map +1 -0
- package/package.json +4 -4
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
// The validation orchestrator. Sessions enqueue jobs and return immediately;
|
|
2
|
+
// one leader process (a session host or `ezcoder validate daemon`) dispatches
|
|
3
|
+
// them to backends with bounded concurrency, polls them, posts commit statuses
|
|
4
|
+
// and records results. Every process watches the shared store and tells its
|
|
5
|
+
// own sessions when a job for their project changes.
|
|
6
|
+
import { EventEmitter } from "node:events";
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
8
|
+
import fs from "node:fs/promises";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { withFileLock } from "@prestyj/core";
|
|
12
|
+
import { fits, loadBackends } from "./backends.js";
|
|
13
|
+
import { BILLING_SUMMARY } from "./github-actions-backend.js";
|
|
14
|
+
import { buildStageCommand, cacheKeyFor, loadProjectConfig, parseGitHubRepo } from "./config.js";
|
|
15
|
+
import { defaultExec } from "./exec.js";
|
|
16
|
+
import { chooseTarget, jobTarget, jobsOn, listTargets, loadOf } from "./scheduler.js";
|
|
17
|
+
import { JobStore, defaultValidationDir } from "./store.js";
|
|
18
|
+
import { isTerminal, MAX_ATTEMPTS, } from "./types.js";
|
|
19
|
+
const ACTIVE = new Set(["queued", "waiting", "running"]);
|
|
20
|
+
function nowIso() {
|
|
21
|
+
return new Date().toISOString();
|
|
22
|
+
}
|
|
23
|
+
function newJobId() {
|
|
24
|
+
return `v${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
|
|
25
|
+
}
|
|
26
|
+
function pidAlive(pid) {
|
|
27
|
+
try {
|
|
28
|
+
process.kill(pid, 0);
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
return e.code === "EPERM";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function short(sha) {
|
|
36
|
+
return sha.slice(0, 8);
|
|
37
|
+
}
|
|
38
|
+
let shared;
|
|
39
|
+
export class ValidationService {
|
|
40
|
+
dir;
|
|
41
|
+
store;
|
|
42
|
+
exec;
|
|
43
|
+
pollMs;
|
|
44
|
+
offlineWarnMs;
|
|
45
|
+
machineOfflineMs;
|
|
46
|
+
/** Targets GitHub refused to run on (billing), until when (ms epoch). In memory only. */
|
|
47
|
+
unavailable = new Map();
|
|
48
|
+
unavailableMs;
|
|
49
|
+
backends;
|
|
50
|
+
maxConcurrent;
|
|
51
|
+
injected;
|
|
52
|
+
events = new EventEmitter();
|
|
53
|
+
seen = new Map();
|
|
54
|
+
seeded = false;
|
|
55
|
+
timer;
|
|
56
|
+
ticking;
|
|
57
|
+
keepAlive = false;
|
|
58
|
+
/** Backend problems found while loading the registry. */
|
|
59
|
+
problems = [];
|
|
60
|
+
/** Start the poll loop when work is queued; short-lived commands turn this off. */
|
|
61
|
+
autoStart;
|
|
62
|
+
constructor(opts = {}) {
|
|
63
|
+
this.dir = opts.dir ?? defaultValidationDir();
|
|
64
|
+
this.store = new JobStore(this.dir);
|
|
65
|
+
this.exec = opts.exec ?? defaultExec;
|
|
66
|
+
this.pollMs = opts.pollMs ?? 20_000;
|
|
67
|
+
this.offlineWarnMs = (opts.offlineWarnMinutes ?? 10) * 60_000;
|
|
68
|
+
this.machineOfflineMs = (opts.machineOfflineRequeueMinutes ?? 5) * 60_000;
|
|
69
|
+
this.unavailableMs = (opts.billingBlockMinutes ?? 60) * 60_000;
|
|
70
|
+
this.injected = !!opts.backends;
|
|
71
|
+
this.backends = opts.backends ?? [];
|
|
72
|
+
this.maxConcurrent = opts.maxConcurrent ?? 4;
|
|
73
|
+
this.autoStart = opts.autoStart ?? true;
|
|
74
|
+
if (!opts.backends)
|
|
75
|
+
this.reloadBackends();
|
|
76
|
+
this.events.setMaxListeners(100);
|
|
77
|
+
}
|
|
78
|
+
/** One service per process. */
|
|
79
|
+
static shared() {
|
|
80
|
+
shared ??= new ValidationService();
|
|
81
|
+
return shared;
|
|
82
|
+
}
|
|
83
|
+
reloadBackends() {
|
|
84
|
+
if (this.injected)
|
|
85
|
+
return;
|
|
86
|
+
const loaded = loadBackends(this.dir, this.exec);
|
|
87
|
+
this.backends = loaded.backends;
|
|
88
|
+
this.maxConcurrent = loaded.maxConcurrent;
|
|
89
|
+
this.problems = loaded.problems;
|
|
90
|
+
}
|
|
91
|
+
getBackends() {
|
|
92
|
+
return this.backends;
|
|
93
|
+
}
|
|
94
|
+
backend(id) {
|
|
95
|
+
return this.backends.find((b) => b.id === id);
|
|
96
|
+
}
|
|
97
|
+
// ── events ───────────────────────────────────────────────
|
|
98
|
+
onJob(listener) {
|
|
99
|
+
this.events.on("job", listener);
|
|
100
|
+
return () => this.events.off("job", listener);
|
|
101
|
+
}
|
|
102
|
+
observe(jobs) {
|
|
103
|
+
const changed = [];
|
|
104
|
+
for (const job of jobs) {
|
|
105
|
+
const prev = this.seen.get(job.id);
|
|
106
|
+
const key = `${job.state}|${job.offlineWarned ? 1 : 0}|${job.requeues?.length ?? 0}|${job.noWorkerWarned ? 1 : 0}`;
|
|
107
|
+
if (prev === key)
|
|
108
|
+
continue;
|
|
109
|
+
this.seen.set(job.id, key);
|
|
110
|
+
// First look after start: only report finished jobs nobody was told about.
|
|
111
|
+
if (!this.seeded && (!isTerminal(job.state) || job.notifiedState === job.state))
|
|
112
|
+
continue;
|
|
113
|
+
changed.push(job);
|
|
114
|
+
const requeued = !!prev && (job.requeues?.length ?? 0) > Number(prev.split("|")[2] ?? 0);
|
|
115
|
+
this.events.emit("job", job, prev ? prev.split("|")[0] : undefined, {
|
|
116
|
+
requeued,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
this.seeded = true;
|
|
120
|
+
return changed;
|
|
121
|
+
}
|
|
122
|
+
// ── git ──────────────────────────────────────────────────
|
|
123
|
+
async git(cwd, args) {
|
|
124
|
+
const r = await this.exec("git", args, { cwd, timeoutMs: 15_000 });
|
|
125
|
+
return r.code === 0 ? r.stdout.trim() : undefined;
|
|
126
|
+
}
|
|
127
|
+
async gitState(cwd, ref) {
|
|
128
|
+
const sha = await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
|
|
129
|
+
const branchRaw = await this.git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
130
|
+
const status = await this.git(cwd, ["status", "--porcelain", "--untracked-files=no"]);
|
|
131
|
+
const origin = await this.git(cwd, ["remote", "get-url", "origin"]);
|
|
132
|
+
return {
|
|
133
|
+
sha,
|
|
134
|
+
branch: ref === "HEAD" && branchRaw && branchRaw !== "HEAD" ? branchRaw : undefined,
|
|
135
|
+
dirty: ref === "HEAD" && !!status,
|
|
136
|
+
originRepo: origin ? parseGitHubRepo(origin) : undefined,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
// ── public API ───────────────────────────────────────────
|
|
140
|
+
config(cwd) {
|
|
141
|
+
return loadProjectConfig(cwd);
|
|
142
|
+
}
|
|
143
|
+
async enqueue(cwdIn, opts = {}) {
|
|
144
|
+
const cwd = path.resolve(cwdIn);
|
|
145
|
+
const config = loadProjectConfig(cwd);
|
|
146
|
+
if ("error" in config)
|
|
147
|
+
throw new Error(config.error);
|
|
148
|
+
const ref = opts.ref ?? "HEAD";
|
|
149
|
+
const g = await this.gitState(cwd, ref);
|
|
150
|
+
if (!g.sha)
|
|
151
|
+
throw new Error(`"${ref}" is not a commit in ${cwd} (is this a Git repo with commits?)`);
|
|
152
|
+
const sha = g.sha;
|
|
153
|
+
const repo = config.repo ?? g.originRepo;
|
|
154
|
+
let stages = config.stages;
|
|
155
|
+
if (opts.stages?.length) {
|
|
156
|
+
const unknown = opts.stages.filter((s) => !stages.some((x) => x.name === s));
|
|
157
|
+
if (unknown.length) {
|
|
158
|
+
throw new Error(`unknown stage(s) ${unknown.join(", ")}; this project has: ${stages.map((s) => s.name).join(", ") || "none"}`);
|
|
159
|
+
}
|
|
160
|
+
stages = stages.filter((s) => opts.stages.includes(s.name));
|
|
161
|
+
}
|
|
162
|
+
if (stages.length === 0)
|
|
163
|
+
throw new Error(`no validation stages. ${config.notes.join(" ")}`);
|
|
164
|
+
const messages = [];
|
|
165
|
+
const hasRemote = this.backends.some((b) => b.runs === "remote");
|
|
166
|
+
if (g.dirty && stages.some((s) => s.run === "remote")) {
|
|
167
|
+
messages.push(`Uncommitted changes are not included in remote stages; they test commit ${short(sha)}. Commit first to test them.`);
|
|
168
|
+
}
|
|
169
|
+
const created = [];
|
|
170
|
+
const reused = [];
|
|
171
|
+
await this.store.update((jobs) => {
|
|
172
|
+
for (const stage of stages) {
|
|
173
|
+
const pin = stage.run === "local" ? undefined : stage.backend;
|
|
174
|
+
const slash = pin?.indexOf("/") ?? -1;
|
|
175
|
+
let backend = stage.run === "local" ? "local" : pin ? (slash > 0 ? pin.slice(0, slash) : pin) : "";
|
|
176
|
+
const pinnedMachine = pin && slash > 0 ? pin.slice(slash + 1) : undefined;
|
|
177
|
+
let command = buildStageCommand(stage, cacheKeyFor(repo));
|
|
178
|
+
if (stage.run === "remote" && !stage.backend && (!repo || !hasRemote)) {
|
|
179
|
+
backend = "local";
|
|
180
|
+
command = stage.setup ? `${stage.setup} && ${stage.command}` : stage.command;
|
|
181
|
+
messages.push(`${stage.name}: ${!repo ? "not a GitHub repo" : "no remote worker configured"}, so it runs on this machine.`);
|
|
182
|
+
}
|
|
183
|
+
if (backend && !this.backend(backend)) {
|
|
184
|
+
throw new Error(`stage ${stage.name} names backend "${pin ?? backend}", which isn't configured`);
|
|
185
|
+
}
|
|
186
|
+
if (pinnedMachine && !this.backend(backend)?.machines) {
|
|
187
|
+
throw new Error(`stage ${stage.name} pins "${pin}", but ${backend} isn't a pool (discover)`);
|
|
188
|
+
}
|
|
189
|
+
const isLocal = backend === "local";
|
|
190
|
+
const same = jobs
|
|
191
|
+
.filter((j) => j.project === cwd && j.sha === sha && j.stage === stage.name && j.command === command)
|
|
192
|
+
.at(-1);
|
|
193
|
+
if (same &&
|
|
194
|
+
!opts.force &&
|
|
195
|
+
(ACTIVE.has(same.state) ||
|
|
196
|
+
(same.state === "passed" && !same.dirty && !(isLocal && g.dirty)))) {
|
|
197
|
+
reused.push(same);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const at = nowIso();
|
|
201
|
+
const job = {
|
|
202
|
+
id: newJobId(),
|
|
203
|
+
project: cwd,
|
|
204
|
+
...(repo ? { repo } : {}),
|
|
205
|
+
sha,
|
|
206
|
+
...(g.branch ? { branch: g.branch } : {}),
|
|
207
|
+
stage: stage.name,
|
|
208
|
+
run: isLocal ? "local" : "remote",
|
|
209
|
+
required: stage.required,
|
|
210
|
+
command,
|
|
211
|
+
timeoutMinutes: stage.timeoutMinutes,
|
|
212
|
+
backend,
|
|
213
|
+
...(pin && !isLocal ? { pinned: true } : {}),
|
|
214
|
+
...(pinnedMachine && !isLocal ? { machine: pinnedMachine } : {}),
|
|
215
|
+
...(stage.resources ? { resources: stage.resources } : {}),
|
|
216
|
+
...(config.postCommitStatus && repo && !isLocal
|
|
217
|
+
? { statusContext: `${config.statusContextPrefix}/${stage.name}` }
|
|
218
|
+
: {}),
|
|
219
|
+
state: "queued",
|
|
220
|
+
createdAt: at,
|
|
221
|
+
updatedAt: at,
|
|
222
|
+
...(isLocal && g.dirty ? { dirty: true } : {}),
|
|
223
|
+
};
|
|
224
|
+
// A newer commit on the same branch makes older pending runs pointless.
|
|
225
|
+
if (g.branch) {
|
|
226
|
+
for (const old of jobs) {
|
|
227
|
+
if (old.project === cwd &&
|
|
228
|
+
old.branch === g.branch &&
|
|
229
|
+
old.stage === stage.name &&
|
|
230
|
+
old.sha !== sha &&
|
|
231
|
+
ACTIVE.has(old.state) &&
|
|
232
|
+
(old.state === "queued" || config.cancelSuperseded)) {
|
|
233
|
+
old.state = "superseded";
|
|
234
|
+
old.supersededBy = job.id;
|
|
235
|
+
old.summary = `superseded by ${short(sha)}`;
|
|
236
|
+
old.updatedAt = at;
|
|
237
|
+
old.finishedAt = at;
|
|
238
|
+
messages.push(`${old.stage} for ${short(old.sha)} superseded.`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
jobs.push(job);
|
|
243
|
+
created.push(job);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
if (created.length && this.autoStart)
|
|
247
|
+
this.start();
|
|
248
|
+
return { sha, branch: g.branch, dirty: g.dirty, jobs: created, reused, messages };
|
|
249
|
+
}
|
|
250
|
+
async list(cwd) {
|
|
251
|
+
const jobs = await this.store.read();
|
|
252
|
+
return cwd ? jobs.filter((j) => j.project === path.resolve(cwd)) : jobs;
|
|
253
|
+
}
|
|
254
|
+
async get(id) {
|
|
255
|
+
return (await this.store.read()).find((j) => j.id === id);
|
|
256
|
+
}
|
|
257
|
+
/** Required stages for an exact commit: ok only when every one passed at that SHA. */
|
|
258
|
+
async gate(cwdIn, ref = "HEAD") {
|
|
259
|
+
const cwd = path.resolve(cwdIn);
|
|
260
|
+
const config = loadProjectConfig(cwd);
|
|
261
|
+
if ("error" in config)
|
|
262
|
+
throw new Error(config.error);
|
|
263
|
+
const sha = await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
|
|
264
|
+
if (!sha)
|
|
265
|
+
throw new Error(`"${ref}" is not a commit`);
|
|
266
|
+
const jobs = (await this.store.read()).filter((j) => j.project === cwd && j.sha === sha && j.state !== "superseded");
|
|
267
|
+
const rows = config.stages
|
|
268
|
+
.filter((s) => s.required)
|
|
269
|
+
.map((s) => {
|
|
270
|
+
const mine = jobs.filter((j) => j.stage === s.name);
|
|
271
|
+
const job = [...mine].reverse().find((j) => j.state === "passed" && !j.dirty) ?? mine.at(-1);
|
|
272
|
+
if (!job)
|
|
273
|
+
return { stage: s.name, state: "missing" };
|
|
274
|
+
const note = job.dirty ? "ran on uncommitted changes; doesn't count" : job.summary;
|
|
275
|
+
return {
|
|
276
|
+
stage: s.name,
|
|
277
|
+
state: job.state,
|
|
278
|
+
jobId: job.id,
|
|
279
|
+
url: job.url,
|
|
280
|
+
...(note ? { note } : {}),
|
|
281
|
+
};
|
|
282
|
+
});
|
|
283
|
+
const ok = rows.every((r) => r.state === "passed" && !r.note?.includes("doesn't count"));
|
|
284
|
+
return { sha, ok, rows };
|
|
285
|
+
}
|
|
286
|
+
async cancel(id) {
|
|
287
|
+
const job = await this.store.update((jobs) => {
|
|
288
|
+
const j = jobs.find((x) => x.id === id);
|
|
289
|
+
if (!j || isTerminal(j.state))
|
|
290
|
+
return j;
|
|
291
|
+
j.state = "cancelled";
|
|
292
|
+
j.summary = "cancelled by request";
|
|
293
|
+
j.updatedAt = j.finishedAt = nowIso();
|
|
294
|
+
return { ...j };
|
|
295
|
+
});
|
|
296
|
+
if (job?.runId)
|
|
297
|
+
await this.backend(job.backend)
|
|
298
|
+
?.cancel(job)
|
|
299
|
+
.catch(() => { });
|
|
300
|
+
if (job?.statusContext && job.dispatchedAt)
|
|
301
|
+
await this.postStatus(job, "error", "cancelled");
|
|
302
|
+
return job;
|
|
303
|
+
}
|
|
304
|
+
/** Run a finished job again at the same commit. */
|
|
305
|
+
async retry(id) {
|
|
306
|
+
const created = await this.store.update((jobs) => {
|
|
307
|
+
const j = jobs.find((x) => x.id === id);
|
|
308
|
+
if (!j)
|
|
309
|
+
throw new Error(`no job ${id}`);
|
|
310
|
+
if (!isTerminal(j.state))
|
|
311
|
+
throw new Error(`job ${id} is still ${j.state}`);
|
|
312
|
+
const at = nowIso();
|
|
313
|
+
const copy = {
|
|
314
|
+
id: newJobId(),
|
|
315
|
+
project: j.project,
|
|
316
|
+
...(j.repo ? { repo: j.repo } : {}),
|
|
317
|
+
sha: j.sha,
|
|
318
|
+
...(j.branch ? { branch: j.branch } : {}),
|
|
319
|
+
stage: j.stage,
|
|
320
|
+
run: j.run,
|
|
321
|
+
required: j.required,
|
|
322
|
+
command: j.command,
|
|
323
|
+
timeoutMinutes: j.timeoutMinutes,
|
|
324
|
+
backend: j.run === "local" ? "local" : j.pinned ? j.backend : "",
|
|
325
|
+
...(j.pinned ? { pinned: true, ...(j.machine ? { machine: j.machine } : {}) } : {}),
|
|
326
|
+
...(j.resources ? { resources: j.resources } : {}),
|
|
327
|
+
...(j.statusContext ? { statusContext: j.statusContext } : {}),
|
|
328
|
+
...(j.dirty ? { dirty: true } : {}),
|
|
329
|
+
state: "queued",
|
|
330
|
+
createdAt: at,
|
|
331
|
+
updatedAt: at,
|
|
332
|
+
retryOf: j.id,
|
|
333
|
+
};
|
|
334
|
+
jobs.push(copy);
|
|
335
|
+
return copy;
|
|
336
|
+
});
|
|
337
|
+
if (this.autoStart)
|
|
338
|
+
this.start();
|
|
339
|
+
return created;
|
|
340
|
+
}
|
|
341
|
+
async logs(id, failedOnly = true) {
|
|
342
|
+
const job = await this.get(id);
|
|
343
|
+
if (!job)
|
|
344
|
+
return `No job ${id}.`;
|
|
345
|
+
const b = this.backend(job.backend);
|
|
346
|
+
if (!b)
|
|
347
|
+
return job.backend
|
|
348
|
+
? `Backend ${job.backend} is no longer configured.`
|
|
349
|
+
: "Not dispatched yet.";
|
|
350
|
+
return b.logs(job, failedOnly && job.state === "failed");
|
|
351
|
+
}
|
|
352
|
+
/** Every place jobs can run: plain backends and each pool machine. */
|
|
353
|
+
async workers() {
|
|
354
|
+
const jobs = await this.store.read();
|
|
355
|
+
const dayAgo = Date.now() - 86_400_000;
|
|
356
|
+
const targets = await listTargets(this.backends);
|
|
357
|
+
return Promise.all(targets.map(async (t) => {
|
|
358
|
+
const mine = jobsOn(t, jobs);
|
|
359
|
+
const load = loadOf(t, jobs);
|
|
360
|
+
const health = t.info
|
|
361
|
+
? { online: t.online, busy: t.online && t.busy >= t.slots, detail: t.info.detail }
|
|
362
|
+
: await t.backend.health().catch((e) => ({
|
|
363
|
+
online: false,
|
|
364
|
+
detail: e instanceof Error ? e.message : String(e),
|
|
365
|
+
}));
|
|
366
|
+
const here = (j) => j.backend === t.backend.id &&
|
|
367
|
+
(t.machine === undefined || (j.machine ?? t.backend.id) === t.machine);
|
|
368
|
+
const recent = (at) => Date.parse(at) > dayAgo;
|
|
369
|
+
return {
|
|
370
|
+
id: t.key,
|
|
371
|
+
backend: t.backend.id,
|
|
372
|
+
...(t.machine !== undefined ? { machine: t.machine } : {}),
|
|
373
|
+
kind: t.backend.kind,
|
|
374
|
+
maxConcurrent: t.slots,
|
|
375
|
+
active: mine.length,
|
|
376
|
+
used: load.used,
|
|
377
|
+
busy: t.busy,
|
|
378
|
+
queued: jobs.filter((j) => j.state === "queued" &&
|
|
379
|
+
(j.backend
|
|
380
|
+
? j.backend === t.backend.id && (!j.machine || j.machine === t.machine)
|
|
381
|
+
: t.backend.runs === "remote")).length,
|
|
382
|
+
health,
|
|
383
|
+
platform: t.platform,
|
|
384
|
+
...(t.capacity ? { capacity: t.capacity } : {}),
|
|
385
|
+
reserved: { cpus: load.reservedCpus, memoryGb: load.reservedMemoryGb },
|
|
386
|
+
...(t.cloud ? { cloud: true } : {}),
|
|
387
|
+
...(this.unavailableUntil(t.key)
|
|
388
|
+
? { blockedUntil: new Date(this.unavailableUntil(t.key)).toISOString() }
|
|
389
|
+
: {}),
|
|
390
|
+
recentFailures: jobs.filter((j) => here(j) && j.state === "error" && recent(j.updatedAt)).length +
|
|
391
|
+
jobs.flatMap((j) => j.requeues ?? []).filter((r) => r.from === t.key && recent(r.at))
|
|
392
|
+
.length,
|
|
393
|
+
};
|
|
394
|
+
}));
|
|
395
|
+
}
|
|
396
|
+
// ── scheduling loop ──────────────────────────────────────
|
|
397
|
+
/** Start (or keep) the poll loop. Cheap when idle: it stops itself. */
|
|
398
|
+
start(opts = {}) {
|
|
399
|
+
if (opts.keepAlive)
|
|
400
|
+
this.keepAlive = true;
|
|
401
|
+
if (this.timer)
|
|
402
|
+
return;
|
|
403
|
+
const loop = () => {
|
|
404
|
+
this.timer = setTimeout(async () => {
|
|
405
|
+
await this.tick().catch(() => { });
|
|
406
|
+
if (this.timer)
|
|
407
|
+
loop();
|
|
408
|
+
}, this.pollMs);
|
|
409
|
+
if (!this.keepAlive)
|
|
410
|
+
this.timer.unref();
|
|
411
|
+
};
|
|
412
|
+
void this.tick().catch(() => { });
|
|
413
|
+
loop();
|
|
414
|
+
}
|
|
415
|
+
stop() {
|
|
416
|
+
if (this.timer)
|
|
417
|
+
clearTimeout(this.timer);
|
|
418
|
+
this.timer = undefined;
|
|
419
|
+
}
|
|
420
|
+
get running() {
|
|
421
|
+
return !!this.timer;
|
|
422
|
+
}
|
|
423
|
+
/** One pass: observe, and if we lead, poll/dispatch. Returns whether work remains. */
|
|
424
|
+
async tick() {
|
|
425
|
+
if (this.ticking) {
|
|
426
|
+
await this.ticking;
|
|
427
|
+
return this.hasActive();
|
|
428
|
+
}
|
|
429
|
+
this.ticking = this.tickInner().finally(() => {
|
|
430
|
+
this.ticking = undefined;
|
|
431
|
+
});
|
|
432
|
+
await this.ticking;
|
|
433
|
+
return this.hasActive();
|
|
434
|
+
}
|
|
435
|
+
lastActive = false;
|
|
436
|
+
hasActive() {
|
|
437
|
+
return this.lastActive;
|
|
438
|
+
}
|
|
439
|
+
async tickInner() {
|
|
440
|
+
let jobs = await this.store.read();
|
|
441
|
+
this.emitAndMark(jobs);
|
|
442
|
+
const active = jobs.filter((j) => ACTIVE.has(j.state));
|
|
443
|
+
const pendingCancels = jobs.filter((j) => j.state === "superseded" && j.runId && !j.stopSent);
|
|
444
|
+
this.lastActive = active.length > 0;
|
|
445
|
+
if (!active.length && !pendingCancels.length) {
|
|
446
|
+
if (!this.keepAlive)
|
|
447
|
+
this.stop();
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (!(await this.lead()))
|
|
451
|
+
return;
|
|
452
|
+
// Superseded jobs that were already running: stop them on the worker.
|
|
453
|
+
for (const j of pendingCancels) {
|
|
454
|
+
await this.patch(j.id, { stopSent: true }, undefined, true);
|
|
455
|
+
await this.backend(j.backend)
|
|
456
|
+
?.cancel(j)
|
|
457
|
+
.catch(() => { });
|
|
458
|
+
await this.postStatus(j, "error", `superseded by a newer commit`);
|
|
459
|
+
}
|
|
460
|
+
// Poll what's in flight.
|
|
461
|
+
for (const j of active.filter((x) => x.state !== "queued")) {
|
|
462
|
+
const b = this.backend(j.backend);
|
|
463
|
+
if (!b) {
|
|
464
|
+
await this.patch(j.id, {
|
|
465
|
+
state: "error",
|
|
466
|
+
summary: `backend ${j.backend} is no longer configured`,
|
|
467
|
+
});
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
try {
|
|
471
|
+
const r = await b.poll(j);
|
|
472
|
+
if (r.blocked) {
|
|
473
|
+
await this.handleBlocked(j, r.blocked, r.url);
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (r.lost) {
|
|
477
|
+
await this.requeueLost(j, r.lost);
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const patch = {};
|
|
481
|
+
if (r.url && r.url !== j.url)
|
|
482
|
+
patch.url = r.url;
|
|
483
|
+
if (r.state !== j.state) {
|
|
484
|
+
patch.state = r.state;
|
|
485
|
+
if (r.summary)
|
|
486
|
+
patch.summary = r.summary;
|
|
487
|
+
if (r.state === "running")
|
|
488
|
+
patch.startedAt = nowIso();
|
|
489
|
+
if (isTerminal(r.state)) {
|
|
490
|
+
patch.finishedAt = nowIso();
|
|
491
|
+
if (j.run === "local" && !j.dirty && (await this.movedSince(j)))
|
|
492
|
+
patch.dirty = true;
|
|
493
|
+
if (r.state === "failed" && b.runs === "remote") {
|
|
494
|
+
patch.summary = await this.failureSummary(b, j, r.summary);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
// A run still waiting for a pool machine that went offline: move it elsewhere.
|
|
499
|
+
if (r.state === "waiting" && b.machines && j.machine) {
|
|
500
|
+
const m = (await b.machines().catch(() => [])).find((x) => x.name === j.machine);
|
|
501
|
+
if (m && !m.cloud && !m.online) {
|
|
502
|
+
const since = j.machineOfflineSince ? Date.parse(j.machineOfflineSince) : undefined;
|
|
503
|
+
if (since === undefined)
|
|
504
|
+
patch.machineOfflineSince = nowIso();
|
|
505
|
+
else if (Date.now() - since > this.machineOfflineMs) {
|
|
506
|
+
await b.cancel(j).catch(() => { });
|
|
507
|
+
await this.requeueLost(j, `machine ${jobTarget(j)} went offline before the run started`);
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
else if (j.machineOfflineSince) {
|
|
512
|
+
patch.machineOfflineSince = undefined;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
else if ((r.state === "waiting" || j.state === "waiting") &&
|
|
516
|
+
!(b.machines && j.machine) &&
|
|
517
|
+
!j.offlineWarned &&
|
|
518
|
+
j.dispatchedAt &&
|
|
519
|
+
Date.now() - Date.parse(j.dispatchedAt) > this.offlineWarnMs) {
|
|
520
|
+
const h = await b.health().catch(() => undefined);
|
|
521
|
+
if (h && !h.online) {
|
|
522
|
+
patch.offlineWarned = true;
|
|
523
|
+
patch.summary = `worker offline (${h.detail}); it stays queued on GitHub and runs when the worker is back`;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (Object.keys(patch).length) {
|
|
527
|
+
const updated = await this.patch(j.id, patch);
|
|
528
|
+
if (updated && patch.state && isTerminal(patch.state) && updated.statusContext) {
|
|
529
|
+
await this.postFinal(updated);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
catch (e) {
|
|
534
|
+
// Transient (network, rate limit): try again next tick.
|
|
535
|
+
void e;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
// Dispatch queued jobs into free slots, oldest first.
|
|
539
|
+
jobs = await this.store.read();
|
|
540
|
+
let inFlight = jobs.filter((j) => j.state === "waiting" || j.state === "running").length;
|
|
541
|
+
const queued = jobs.filter((x) => x.state === "queued");
|
|
542
|
+
const targets = queued.length ? await this.availableTargets() : [];
|
|
543
|
+
for (const j of queued) {
|
|
544
|
+
if (inFlight >= this.maxConcurrent)
|
|
545
|
+
break;
|
|
546
|
+
const t = chooseTarget(j, targets, jobs);
|
|
547
|
+
if (t === "none") {
|
|
548
|
+
await this.patch(j.id, {
|
|
549
|
+
state: "error",
|
|
550
|
+
summary: j.machine
|
|
551
|
+
? `pinned machine ${jobTarget(j)} isn't known to its pool`
|
|
552
|
+
: "no configured worker fits this stage's resources",
|
|
553
|
+
finishedAt: nowIso(),
|
|
554
|
+
});
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (t === "offline") {
|
|
558
|
+
if (!j.noWorkerWarned) {
|
|
559
|
+
await this.patch(j.id, {
|
|
560
|
+
noWorkerWarned: true,
|
|
561
|
+
summary: "no worker online; it stays queued and runs when one comes online",
|
|
562
|
+
}, "queued");
|
|
563
|
+
}
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (!t)
|
|
567
|
+
continue; // every fitting machine is full
|
|
568
|
+
const b = t.backend;
|
|
569
|
+
const claim = {
|
|
570
|
+
backend: b.id,
|
|
571
|
+
...(t.machine !== undefined ? { machine: t.machine } : {}),
|
|
572
|
+
};
|
|
573
|
+
const claimed = await this.patch(j.id, claim, "queued");
|
|
574
|
+
if (!claimed)
|
|
575
|
+
continue;
|
|
576
|
+
try {
|
|
577
|
+
if (b.runs === "remote" && j.repo && !(await this.commitOnGitHub(j.repo, j.sha))) {
|
|
578
|
+
await this.patch(j.id, {
|
|
579
|
+
state: "error",
|
|
580
|
+
summary: `commit ${short(j.sha)} isn't on GitHub; push it, then run validation again`,
|
|
581
|
+
finishedAt: nowIso(),
|
|
582
|
+
});
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const handle = await b.dispatch(claimed);
|
|
586
|
+
const at = nowIso();
|
|
587
|
+
const updated = await this.patch(j.id, { state: "waiting", dispatchedAt: at, attempts: j.attempts ?? 1, ...handle }, "queued");
|
|
588
|
+
inFlight++;
|
|
589
|
+
// Count it against the machine for the rest of this pass.
|
|
590
|
+
Object.assign(j, claim, { state: "waiting", dispatchedAt: at });
|
|
591
|
+
if (updated?.statusContext) {
|
|
592
|
+
await this.postStatus(updated, "pending", `running on ${jobTarget(updated)}`);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
catch (e) {
|
|
596
|
+
await this.patch(j.id, {
|
|
597
|
+
state: "error",
|
|
598
|
+
summary: `dispatch to ${t.key} failed: ${e instanceof Error ? e.message : String(e)}`.slice(0, 400),
|
|
599
|
+
finishedAt: nowIso(),
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
this.emitAndMark(await this.store.read());
|
|
604
|
+
}
|
|
605
|
+
/** Targets minus the ones GitHub recently refused (billing). */
|
|
606
|
+
async availableTargets() {
|
|
607
|
+
const now = Date.now();
|
|
608
|
+
for (const [k, until] of this.unavailable)
|
|
609
|
+
if (until <= now)
|
|
610
|
+
this.unavailable.delete(k);
|
|
611
|
+
return (await listTargets(this.backends)).filter((t) => !this.unavailable.has(t.key));
|
|
612
|
+
}
|
|
613
|
+
/** Is a target out of scheduling (billing), and until when? */
|
|
614
|
+
unavailableUntil(key) {
|
|
615
|
+
const until = this.unavailable.get(key);
|
|
616
|
+
return until && until > Date.now() ? until : undefined;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* GitHub refused to start the run (Actions budget/billing). Never a runner-loss loop:
|
|
620
|
+
* the target is benched for a while and the job goes back once to a self-hosted
|
|
621
|
+
* machine that fits; otherwise it ends as an infra error.
|
|
622
|
+
*/
|
|
623
|
+
async handleBlocked(j, why, url) {
|
|
624
|
+
const from = jobTarget(j);
|
|
625
|
+
this.unavailable.set(from, Date.now() + this.unavailableMs);
|
|
626
|
+
const alreadyMoved = (j.requeues ?? []).some((r) => r.reason.startsWith(BILLING_SUMMARY));
|
|
627
|
+
const selfHosted = (await this.availableTargets()).some((t) => !t.cloud &&
|
|
628
|
+
t.backend.runs === "remote" &&
|
|
629
|
+
(!j.pinned || t.backend.id === j.backend) &&
|
|
630
|
+
fits(j.resources, t.capacity));
|
|
631
|
+
const at = nowIso();
|
|
632
|
+
const reason = `${BILLING_SUMMARY} (${why})`.slice(0, 300);
|
|
633
|
+
const updated = await this.store.update((jobs) => {
|
|
634
|
+
const x = jobs.find((y) => y.id === j.id);
|
|
635
|
+
if (!x || (x.state !== "waiting" && x.state !== "running"))
|
|
636
|
+
return undefined;
|
|
637
|
+
x.updatedAt = at;
|
|
638
|
+
if (alreadyMoved || !selfHosted || (x.pinned && x.machine)) {
|
|
639
|
+
x.state = "error";
|
|
640
|
+
x.finishedAt = at;
|
|
641
|
+
x.summary = reason;
|
|
642
|
+
if (url)
|
|
643
|
+
x.url = url;
|
|
644
|
+
return { ...x };
|
|
645
|
+
}
|
|
646
|
+
x.requeues = [
|
|
647
|
+
...(x.requeues ?? []),
|
|
648
|
+
{ at, from, ...(x.runId ? { runId: x.runId } : {}), reason },
|
|
649
|
+
];
|
|
650
|
+
x.state = "queued";
|
|
651
|
+
x.avoid = [...new Set([...(x.avoid ?? []), from])];
|
|
652
|
+
x.summary = `requeued to a self-hosted worker: ${reason}`.slice(0, 400);
|
|
653
|
+
if (!x.pinned) {
|
|
654
|
+
x.backend = "";
|
|
655
|
+
delete x.machine;
|
|
656
|
+
}
|
|
657
|
+
for (const k of ["runId", "url", "dispatchedAt", "startedAt", "finishedAt"])
|
|
658
|
+
delete x[k];
|
|
659
|
+
return { ...x };
|
|
660
|
+
});
|
|
661
|
+
if (updated?.state === "error" && updated.statusContext)
|
|
662
|
+
await this.postFinal(updated);
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* A run lost its runner (or its machine went away before it started): queue the
|
|
666
|
+
* job again, up to MAX_ATTEMPTS, steering it away from that machine. Jobs that
|
|
667
|
+
* EZCODER cancelled or superseded meanwhile are left alone.
|
|
668
|
+
*/
|
|
669
|
+
async requeueLost(j, reason) {
|
|
670
|
+
const from = jobTarget(j);
|
|
671
|
+
const at = nowIso();
|
|
672
|
+
const updated = await this.store.update((jobs) => {
|
|
673
|
+
const x = jobs.find((y) => y.id === j.id);
|
|
674
|
+
if (!x || (x.state !== "waiting" && x.state !== "running"))
|
|
675
|
+
return undefined;
|
|
676
|
+
const attempts = x.attempts ?? 1;
|
|
677
|
+
x.requeues = [
|
|
678
|
+
...(x.requeues ?? []),
|
|
679
|
+
{ at, from, ...(x.runId ? { runId: x.runId } : {}), reason },
|
|
680
|
+
];
|
|
681
|
+
x.updatedAt = at;
|
|
682
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
683
|
+
x.state = "error";
|
|
684
|
+
x.finishedAt = at;
|
|
685
|
+
x.summary = `worker lost ${attempts} times; last: ${reason}`.slice(0, 400);
|
|
686
|
+
return { ...x };
|
|
687
|
+
}
|
|
688
|
+
x.state = "queued";
|
|
689
|
+
x.attempts = attempts + 1;
|
|
690
|
+
x.avoid = [...new Set([...(x.avoid ?? []), from])];
|
|
691
|
+
x.summary = `requeued (attempt ${attempts + 1}/${MAX_ATTEMPTS}): ${reason}`.slice(0, 400);
|
|
692
|
+
if (!x.pinned) {
|
|
693
|
+
x.backend = "";
|
|
694
|
+
delete x.machine;
|
|
695
|
+
}
|
|
696
|
+
for (const k of [
|
|
697
|
+
"runId",
|
|
698
|
+
"url",
|
|
699
|
+
"dispatchedAt",
|
|
700
|
+
"startedAt",
|
|
701
|
+
"finishedAt",
|
|
702
|
+
"offlineWarned",
|
|
703
|
+
"machineOfflineSince",
|
|
704
|
+
]) {
|
|
705
|
+
delete x[k];
|
|
706
|
+
}
|
|
707
|
+
return { ...x };
|
|
708
|
+
});
|
|
709
|
+
if (updated?.state === "error" && updated.statusContext)
|
|
710
|
+
await this.postFinal(updated);
|
|
711
|
+
}
|
|
712
|
+
async movedSince(job) {
|
|
713
|
+
const head = await this.git(job.project, ["rev-parse", "HEAD"]);
|
|
714
|
+
const status = await this.git(job.project, ["status", "--porcelain", "--untracked-files=no"]);
|
|
715
|
+
return head !== job.sha || !!status;
|
|
716
|
+
}
|
|
717
|
+
async failureSummary(b, j, base) {
|
|
718
|
+
const log = await b.logs(j, true).catch(() => "");
|
|
719
|
+
const lines = log
|
|
720
|
+
.split("\n")
|
|
721
|
+
.map((l) => l.trim())
|
|
722
|
+
.filter(Boolean)
|
|
723
|
+
.filter((l) => /fail|error|expected|assert|✗|×/i.test(l))
|
|
724
|
+
.slice(-4);
|
|
725
|
+
return [base ?? "failed", ...lines].join(" | ").slice(0, 480);
|
|
726
|
+
}
|
|
727
|
+
async commitOnGitHub(repo, sha) {
|
|
728
|
+
const r = await this.exec("gh", ["api", `repos/${repo}/commits/${sha}`, "--jq", ".sha"], {
|
|
729
|
+
timeoutMs: 30_000,
|
|
730
|
+
});
|
|
731
|
+
if (r.code === 0)
|
|
732
|
+
return true;
|
|
733
|
+
// Only a clear "not found" blocks; on network trouble let the worker decide.
|
|
734
|
+
return !/HTTP 4(04|22)|No commit found/i.test(r.stderr + r.stdout);
|
|
735
|
+
}
|
|
736
|
+
async postFinal(job) {
|
|
737
|
+
const state = job.state === "passed" ? "success" : job.state === "failed" ? "failure" : "error";
|
|
738
|
+
await this.postStatus(job, state, (job.summary ?? job.state).slice(0, 130));
|
|
739
|
+
}
|
|
740
|
+
async postStatus(job, state, description) {
|
|
741
|
+
if (!job.repo || !job.statusContext)
|
|
742
|
+
return;
|
|
743
|
+
const args = [
|
|
744
|
+
"api",
|
|
745
|
+
"-X",
|
|
746
|
+
"POST",
|
|
747
|
+
`repos/${job.repo}/statuses/${job.sha}`,
|
|
748
|
+
"-f",
|
|
749
|
+
`state=${state}`,
|
|
750
|
+
"-f",
|
|
751
|
+
`context=${job.statusContext}`,
|
|
752
|
+
"-f",
|
|
753
|
+
`description=${description.slice(0, 139)}`,
|
|
754
|
+
...(job.url?.startsWith("http") ? ["-f", `target_url=${job.url}`] : []),
|
|
755
|
+
];
|
|
756
|
+
const r = await this.exec("gh", args, { timeoutMs: 30_000 });
|
|
757
|
+
await this.patch(job.id, { postedStatus: r.code === 0 ? state : `failed:${state}` }, undefined, true);
|
|
758
|
+
}
|
|
759
|
+
/** Merge a patch into one stored job. With `onlyIf`, only when it's still in that state. */
|
|
760
|
+
async patch(id, patch, onlyIf, evenIfTerminal = false) {
|
|
761
|
+
return this.store.update((jobs) => {
|
|
762
|
+
const j = jobs.find((x) => x.id === id);
|
|
763
|
+
if (!j)
|
|
764
|
+
return undefined;
|
|
765
|
+
if (onlyIf && j.state !== onlyIf)
|
|
766
|
+
return undefined;
|
|
767
|
+
// Never resurrect a job someone cancelled or superseded meanwhile.
|
|
768
|
+
if (!evenIfTerminal && isTerminal(j.state) && patch.state && !isTerminal(patch.state))
|
|
769
|
+
return undefined;
|
|
770
|
+
if (!evenIfTerminal && (j.state === "cancelled" || j.state === "superseded") && patch.state) {
|
|
771
|
+
return undefined;
|
|
772
|
+
}
|
|
773
|
+
Object.assign(j, patch, { updatedAt: nowIso() });
|
|
774
|
+
return { ...j };
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
emitAndMark(jobs) {
|
|
778
|
+
const changed = this.observe(jobs);
|
|
779
|
+
const done = changed.filter((j) => isTerminal(j.state) && j.notifiedState !== j.state);
|
|
780
|
+
if (done.length && this.events.listenerCount("job") > 0) {
|
|
781
|
+
void this.store
|
|
782
|
+
.update((all) => {
|
|
783
|
+
for (const d of done) {
|
|
784
|
+
const j = all.find((x) => x.id === d.id);
|
|
785
|
+
if (j)
|
|
786
|
+
j.notifiedState = d.state;
|
|
787
|
+
}
|
|
788
|
+
})
|
|
789
|
+
.catch(() => { });
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// ── leadership ───────────────────────────────────────────
|
|
793
|
+
async lead() {
|
|
794
|
+
const file = path.join(this.dir, "leader.json");
|
|
795
|
+
const staleMs = Math.max(90_000, this.pollMs * 4);
|
|
796
|
+
await fs.mkdir(this.dir, { recursive: true });
|
|
797
|
+
return withFileLock(file, async () => {
|
|
798
|
+
try {
|
|
799
|
+
const cur = JSON.parse(await fs.readFile(file, "utf8"));
|
|
800
|
+
const mine = cur.pid === process.pid && cur.host === os.hostname();
|
|
801
|
+
const live = cur.host === os.hostname() ? pidAlive(cur.pid) : true;
|
|
802
|
+
if (!mine && live && Date.now() - cur.at < staleMs)
|
|
803
|
+
return false;
|
|
804
|
+
}
|
|
805
|
+
catch {
|
|
806
|
+
// no leader yet
|
|
807
|
+
}
|
|
808
|
+
await fs.writeFile(file, JSON.stringify({ pid: process.pid, host: os.hostname(), at: Date.now() }));
|
|
809
|
+
return true;
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
/** Is some live process leading? (Used to decide whether to start a daemon.) */
|
|
813
|
+
async leaderAlive() {
|
|
814
|
+
try {
|
|
815
|
+
const cur = JSON.parse(await fs.readFile(path.join(this.dir, "leader.json"), "utf8"));
|
|
816
|
+
return (cur.host === os.hostname() &&
|
|
817
|
+
pidAlive(cur.pid) &&
|
|
818
|
+
Date.now() - cur.at < Math.max(90_000, this.pollMs * 4));
|
|
819
|
+
}
|
|
820
|
+
catch {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
/** Plain-words one-liner for a worker / pool machine, used by the tool and the CLI. */
|
|
826
|
+
export function describeWorker(w) {
|
|
827
|
+
const cap = [
|
|
828
|
+
w.capacity?.cpus ? `${w.capacity.cpus} cpu` : "",
|
|
829
|
+
w.capacity?.memoryGb ? `${w.capacity.memoryGb} GB` : "",
|
|
830
|
+
]
|
|
831
|
+
.filter(Boolean)
|
|
832
|
+
.join(", ");
|
|
833
|
+
const reserved = w.reserved.cpus || w.reserved.memoryGb
|
|
834
|
+
? `; reserved ${w.reserved.cpus} cpu, ${w.reserved.memoryGb} GB`
|
|
835
|
+
: "";
|
|
836
|
+
const kind = w.cloud ? "cloud" : w.kind;
|
|
837
|
+
return (`${w.id} (${kind}${w.platform.length ? `, ${w.platform.join("/")}` : ""}): ` +
|
|
838
|
+
`${w.health.online ? "online" : "OFFLINE"}${w.blockedUntil ? `, blocked until ${w.blockedUntil} (billing)` : ""}; ` +
|
|
839
|
+
`slots ${w.used}/${w.maxConcurrent} used, ${w.busy} busy on GitHub, ${w.active} ours, ${w.queued} queued` +
|
|
840
|
+
`${cap ? `; ${cap}` : ""}${reserved}` +
|
|
841
|
+
`${w.recentFailures ? `; ${w.recentFailures} infra errors/lost runs in 24h` : ""} — ${w.health.detail}`);
|
|
842
|
+
}
|
|
843
|
+
/** Plain-words one-liner for a job, used by notifications, the tool and the CLI. */
|
|
844
|
+
export function describeJob(j) {
|
|
845
|
+
const where = j.backend ? ` on ${jobTarget(j)}` : "";
|
|
846
|
+
const extra = j.summary ? ` — ${j.summary}` : "";
|
|
847
|
+
const dirty = j.dirty ? " (uncommitted changes; advisory only)" : "";
|
|
848
|
+
return `${j.id} ${j.stage} @ ${short(j.sha)}${where}: ${j.state}${dirty}${extra}${j.url ? ` ${j.url}` : ""}`;
|
|
849
|
+
}
|
|
850
|
+
/** Non-urgent note that a job went back to the queue after a lost runner or billing refusal. */
|
|
851
|
+
export function requeueNotification(j) {
|
|
852
|
+
const last = j.requeues?.at(-1);
|
|
853
|
+
if (!last)
|
|
854
|
+
return undefined;
|
|
855
|
+
return (`Validation re-queued: ${j.stage} at ${short(j.sha)}: ${last.reason} on ${last.from} ` +
|
|
856
|
+
`(attempt ${j.attempts ?? 1}/${MAX_ATTEMPTS}, now ${j.state}${j.backend ? ` on ${jobTarget(j)}` : ""}). ` +
|
|
857
|
+
`Nothing to do; it runs again automatically.`);
|
|
858
|
+
}
|
|
859
|
+
/** The notification a session gets for a job change, or undefined for routine ones. */
|
|
860
|
+
export function notificationFor(j) {
|
|
861
|
+
const at = `${j.stage} at ${short(j.sha)}${j.backend ? ` on ${jobTarget(j)}` : ""}`;
|
|
862
|
+
switch (j.state) {
|
|
863
|
+
case "passed":
|
|
864
|
+
return {
|
|
865
|
+
text: `Validation passed: ${at}${j.dirty ? " (on uncommitted changes, advisory only)" : ""}.`,
|
|
866
|
+
terminal: true,
|
|
867
|
+
urgent: false,
|
|
868
|
+
};
|
|
869
|
+
case "failed":
|
|
870
|
+
return {
|
|
871
|
+
text: `Validation FAILED: ${at}${j.summary ? `: ${j.summary}` : ""}. ` +
|
|
872
|
+
`Read the log with validate logs ${j.id}, fix the cause, commit, then validate run again ` +
|
|
873
|
+
`(the new commit supersedes this one).`,
|
|
874
|
+
terminal: true,
|
|
875
|
+
urgent: true,
|
|
876
|
+
};
|
|
877
|
+
case "error":
|
|
878
|
+
return {
|
|
879
|
+
text: `Validation could not run (not a code failure): ${at}: ${j.summary ?? "unknown error"}. ` +
|
|
880
|
+
`Tell the user if it needs them; retry with validate retry ${j.id}.`,
|
|
881
|
+
terminal: true,
|
|
882
|
+
urgent: true,
|
|
883
|
+
};
|
|
884
|
+
case "queued":
|
|
885
|
+
return j.noWorkerWarned
|
|
886
|
+
? {
|
|
887
|
+
text: `No validation worker online for ${j.stage} at ${short(j.sha)}; it stays queued and ` +
|
|
888
|
+
`runs when a worker comes online. Tell the user if they're waiting on it.`,
|
|
889
|
+
terminal: false,
|
|
890
|
+
urgent: false,
|
|
891
|
+
}
|
|
892
|
+
: undefined;
|
|
893
|
+
case "waiting":
|
|
894
|
+
return j.offlineWarned
|
|
895
|
+
? {
|
|
896
|
+
text: `Validation waiting: ${at}: ${j.summary}. Not retrying; tell the user.`,
|
|
897
|
+
terminal: false,
|
|
898
|
+
urgent: true,
|
|
899
|
+
}
|
|
900
|
+
: undefined;
|
|
901
|
+
default:
|
|
902
|
+
return undefined;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
//# sourceMappingURL=service.js.map
|