forgedock 1.60.0 → 1.61.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/bin/config-schema.mjs +44 -1
- package/bin/engine/runlog.mjs +52 -0
- package/bin/engine-cli.mjs +9 -4
- package/bin/env/bench.mjs +38 -0
- package/bin/env/cli.mjs +134 -0
- package/bin/env/env.mjs +339 -0
- package/bin/forgedock.mjs +32 -3
- package/bin/help-text.mjs +2 -0
- package/bin/lean/ci-budget.mjs +3 -1
- package/bin/lean/ci-classify.mjs +74 -0
- package/bin/lean/ci-classify.test.mjs +147 -0
- package/bin/lean/ci-emit.mjs +175 -0
- package/bin/lean/ci-emit.test.mjs +177 -0
- package/bin/lean/ci-preflight.mjs +183 -0
- package/bin/lean/ci-preflight.test.mjs +122 -0
- package/bin/lean/ci-runner-health.mjs +213 -0
- package/bin/lean/ci-runner-health.test.mjs +113 -0
- package/bin/lean/ci-watch.mjs +79 -0
- package/bin/lean/ci-watch.test.mjs +80 -0
- package/bin/lean/conformance.mjs +7 -1
- package/bin/lean/conformance.test.mjs +7 -1
- package/bin/lean/depcache.mjs +38 -8
- package/bin/lean/deploy-stages.mjs +514 -0
- package/bin/lean/deploy-stages.test.mjs +580 -0
- package/bin/lean/effects.mjs +50 -0
- package/bin/lean/execution.mjs +8 -1
- package/bin/lean/lean.mjs +61 -12
- package/bin/lean/lean.test.mjs +87 -0
- package/bin/lean/preflight.mjs +62 -1
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/release-deploy.mjs +12 -6
- package/bin/lean/release-flakes.mjs +16 -0
- package/bin/lean/release-flakes.test.mjs +15 -0
- package/bin/lean/release-gates.mjs +24 -1
- package/bin/lean/release-ledger.mjs +21 -0
- package/bin/lean/release-minutes-timing.test.mjs +57 -0
- package/bin/lean/release-minutes.mjs +98 -0
- package/bin/lean/release-promote.mjs +444 -0
- package/bin/lean/release-promote.test.mjs +470 -0
- package/bin/lean/release-rollback.mjs +14 -6
- package/bin/lean/release.mjs +31 -2
- package/bin/lean/sandbox-remote.mjs +11 -3
- package/bin/lean/testengine-recall.mjs +82 -0
- package/bin/lean/testengine-recall.test.mjs +103 -0
- package/bin/lean/testengine-shard.mjs +150 -0
- package/bin/lean/testengine-shard.test.mjs +111 -0
- package/bin/lean/testengine.mjs +486 -0
- package/bin/lean/testengine.test.mjs +303 -0
- package/bin/lean/validate-catalog.mjs +16 -0
- package/bin/lean/validate-catalog.test.mjs +14 -1
- package/bin/lean/verify-settle.test.mjs +156 -0
- package/bin/lean/verify.mjs +98 -3
- package/bin/pool/agent.mjs +65 -6
- package/bin/pool/ci-events.mjs +183 -0
- package/bin/pool/ci-events.test.mjs +143 -0
- package/bin/pool/docker.mjs +7 -0
- package/bin/pool/lane-tools.mjs +32 -0
- package/bin/pool/router.mjs +21 -1
- package/bin/pool/warm.mjs +14 -3
- package/bin/stats/ci-awareness.mjs +66 -0
- package/bin/stats/index.mjs +44 -3
- package/bin/stats/release-ledger.test.mjs +226 -0
- package/bin/stats/release.mjs +365 -1
- package/bin/stats/stats.test.mjs +36 -0
- package/docs/CI.md +31 -0
- package/docs/CONFIG.md +235 -2
- package/docs/ENV-LIBRARY.md +172 -0
- package/docs/STATS.md +43 -0
- package/docs/ci-events.md +88 -0
- package/docs/test-engine.md +98 -0
- package/package.json +1 -1
- package/pool/README.md +1 -0
- package/pool/image/entrypoint.sh +15 -3
- package/pool/services/docker-compose.yml +53 -0
- package/pool/services/git-mirror.sh +22 -0
- package/scripts/acceptance-red-green.sh +5 -2
- package/scripts/acceptance-red-green.test.sh +11 -0
- package/templates/github-actions/forge-env/action.yml +65 -0
package/bin/lean/verify.mjs
CHANGED
|
@@ -29,6 +29,30 @@ export const VERIFY_CHECK_NAME = "forgedock/verify";
|
|
|
29
29
|
/** Checks API output.text limit is 65535 characters; stay well under it. */
|
|
30
30
|
export const VERIFY_TEXT_CAP = 60000;
|
|
31
31
|
const OK = ["success", "neutral", "skipped"];
|
|
32
|
+
/** #5718 `verify.cancel_superseded`: off (default) | own (runs this actor triggered) | all (every run of the branch). */
|
|
33
|
+
export const CANCEL_SUPERSEDED_MODES = Object.freeze(["off", "own", "all"]);
|
|
34
|
+
export const parseCancelSuperseded = (v) => { const s = String(v ?? "").trim().toLowerCase(); return s === "true" ? "own" : CANCEL_SUPERSEDED_MODES.includes(s) ? s : "off"; };
|
|
35
|
+
/**
|
|
36
|
+
* #5718 `verify.settle`: how long gate checks that have not reported are waited on. `fixed` (default): the whole grace
|
|
37
|
+
* period, as before. `condition`: until the head's check suites say nothing more can report (settleKnown), at most the
|
|
38
|
+
* grace period. `shadow`: waits as `fixed` and records when `condition` would have decided and whether the gating set
|
|
39
|
+
* was the same.
|
|
40
|
+
*/
|
|
41
|
+
export const SETTLE_MODES = Object.freeze(["fixed", "shadow", "condition"]);
|
|
42
|
+
/** The condition never holds before this long after the push: GitHub creates check suites asynchronously. */
|
|
43
|
+
export const SETTLE_MIN_MS = 20000;
|
|
44
|
+
/**
|
|
45
|
+
* #5718: true when the required set of a head is known: its check suites were read on two consecutive polls with the
|
|
46
|
+
* same ids, at least one exists, every suite is completed, and `minMs` has passed. A suite that is queued or in progress
|
|
47
|
+
* may still register checks, so the set is not known. `prev` is the id list of the previous poll (null on the first).
|
|
48
|
+
* @returns {{known: boolean, ids: string[]}}
|
|
49
|
+
*/
|
|
50
|
+
export function settleKnown({ suites, prev, elapsedMs, minMs = SETTLE_MIN_MS }) {
|
|
51
|
+
const list = Array.isArray(suites) ? suites : [];
|
|
52
|
+
const ids = list.map((x) => String(x?.id)).sort();
|
|
53
|
+
const stable = Array.isArray(prev) && prev.length === ids.length && prev.every((id, i) => id === ids[i]);
|
|
54
|
+
return { known: ids.length > 0 && stable && elapsedMs >= minMs && list.every((x) => String(x?.status).toLowerCase() === "completed"), ids };
|
|
55
|
+
}
|
|
32
56
|
|
|
33
57
|
/**
|
|
34
58
|
* forge.yaml `verify:` section (block style; parseForgeYaml gives strings) → {mode, workflow, pathsInput, skipPaths,
|
|
@@ -56,6 +80,7 @@ export function parseVerify(sec = {}) {
|
|
|
56
80
|
const rawChecks = Array.isArray(s.checks) ? s.checks : str(s.checks).split(",");
|
|
57
81
|
const names = rawChecks.map((x) => String(x ?? "").trim()).filter(Boolean);
|
|
58
82
|
const checks = names.length ? [...new Set(names)] : null;
|
|
83
|
+
const settle = SETTLE_MODES.includes(str(s.settle).toLowerCase()) ? str(s.settle).toLowerCase() : "fixed"; // #5718: both keys are absent from the result at their defaults
|
|
59
84
|
const postMerge = str(s.post_merge) || null;
|
|
60
85
|
// a flow list (`[a, "b c"]`) arrives as one scalar from the one-level reader: strip the brackets and quotes
|
|
61
86
|
const rawFlaky = Array.isArray(s.flaky) ? s.flaky : str(s.flaky).trim().replace(/^\[(.*)\]$/s, "$1").split(",");
|
|
@@ -75,7 +100,7 @@ export function parseVerify(sec = {}) {
|
|
|
75
100
|
const baselines = parseBaselines(s.baselines); // #5448: suites validate runs when matching paths change
|
|
76
101
|
const precheckBlock = str(s.precheck_block).toLowerCase() === "true"; // #5079: a still-failing declared check stops the lane (ci.red)
|
|
77
102
|
const guardBlock = str(s.guard_block).toLowerCase() !== "false"; // #5239: verify.invariants (the pre-merge guard set) block the merge unless false
|
|
78
|
-
return { mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s) };
|
|
103
|
+
return { ...(settle !== "fixed" ? { settle } : {}), ...(parseCancelSuperseded(s.cancel_superseded) !== "off" ? { cancelSuperseded: parseCancelSuperseded(s.cancel_superseded) } : {}), mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s) };
|
|
79
104
|
}
|
|
80
105
|
|
|
81
106
|
const globRe = (g) => new RegExp(`^${g.split("**").map((p) => p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")).join(".*")}$`);
|
|
@@ -170,8 +195,11 @@ const sameSha = (a, b) => Boolean(a && b) && (String(a).startsWith(b) || String(
|
|
|
170
195
|
* (rerunTarget) makes the re-verify after a rerun wait for newer attempts than the ones judged red.
|
|
171
196
|
*/
|
|
172
197
|
export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMaxMinutes = 360, now = () => Date.now(), sleep, random = Math.random,
|
|
173
|
-
push = async () => {}, exclude = [], onPoll = async () => {}, graceMs = DEFAULT_GRACE_MS, gate = null, rerunOf = null }) {
|
|
198
|
+
push = async () => {}, exclude = [], onPoll = async () => {}, graceMs = DEFAULT_GRACE_MS, gate = null, rerunOf = null, onSettle = () => {} }) {
|
|
174
199
|
const v = verify ?? parseVerify({});
|
|
200
|
+
// #5718: `fixed` never reads check suites; the two other modes need the seam, else they are `fixed` too.
|
|
201
|
+
const settleMode = SETTLE_MODES.includes(v.settle) && v.settle !== "fixed" && io?.checkSuites ? v.settle : "fixed";
|
|
202
|
+
const st = { prev: null, knownAt: null, knownNames: null, reported: false };
|
|
175
203
|
const files = verifiableFiles(changedFiles);
|
|
176
204
|
if (skipsCi(files, v.skipPaths)) return { result: "skipped", failures: [], runUrl: null, detail: `all ${files.length} changed file(s) match skip_paths` };
|
|
177
205
|
await push();
|
|
@@ -211,7 +239,20 @@ export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMa
|
|
|
211
239
|
const gating = gateSet ? latest.filter((c) => gateSet.has(c.name)) : [];
|
|
212
240
|
const relevant = gating.length ? gating : latest;
|
|
213
241
|
const missing = gateSet ? [...gateSet].filter((n) => !latest.some((c) => c.name === n)) : [];
|
|
214
|
-
|
|
242
|
+
let waitMissing = missing.length && now() - startedAt < graceMs;
|
|
243
|
+
if (settleMode !== "fixed" && missing.length && st.knownAt === null && waitMissing) {
|
|
244
|
+
let suites = null;
|
|
245
|
+
try { suites = await io.checkSuites(head); } catch { suites = null; } // unreadable: not known, keep waiting
|
|
246
|
+
const k = settleKnown({ suites, prev: st.prev, elapsedMs: now() - startedAt });
|
|
247
|
+
st.prev = suites ? k.ids : null;
|
|
248
|
+
if (k.known) { st.knownAt = now() - startedAt; st.knownNames = (gating.length ? gating : latest).map((c) => c.name).sort(); }
|
|
249
|
+
}
|
|
250
|
+
if (settleMode === "condition" && st.knownAt !== null) waitMissing = false;
|
|
251
|
+
if (settleMode !== "fixed" && missing.length && !waitMissing && !st.reported) {
|
|
252
|
+
st.reported = true;
|
|
253
|
+
const names = relevant.map((c) => c.name).sort();
|
|
254
|
+
try { onSettle({ mode: settleMode, missing, waited_ms: now() - startedAt, known_at_ms: st.knownAt, grace_ms: graceMs, agreed: st.knownNames === null ? null : JSON.stringify(st.knownNames) === JSON.stringify(names) }); } catch { /* a record, never a verdict */ }
|
|
255
|
+
}
|
|
215
256
|
if (relevant.length && !waitMissing && relevant.every((c) => c.state !== "pending")) {
|
|
216
257
|
const failed = relevant.filter((c) => c.state === "failure");
|
|
217
258
|
const ignored = gating.length ? latest.filter((c) => !gateSet.has(c.name) && c.state === "failure").map((c) => c.name) : [];
|
|
@@ -227,6 +268,37 @@ export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMa
|
|
|
227
268
|
}
|
|
228
269
|
}
|
|
229
270
|
|
|
271
|
+
/** Events whose runs only verify a head; a push or dispatch run may deploy, so it is never cancelled here. */
|
|
272
|
+
export const SUPERSEDED_EVENTS = Object.freeze(["pull_request", "pull_request_target"]);
|
|
273
|
+
/**
|
|
274
|
+
* #5718: the runs of `branch` a push of `head` superseded (pure): queued or running, of a verification event, for another
|
|
275
|
+
* head sha, created before `pushedAt` when it is given, and under `own` triggered by `actor`. `runs`: [{id, headSha, status, event, actor, createdAt}].
|
|
276
|
+
*/
|
|
277
|
+
export function supersededRuns({ runs, head, mode = "own", actor = null, events = SUPERSEDED_EVENTS, pushedAt = null }) {
|
|
278
|
+
if (mode !== "own" && mode !== "all") return [];
|
|
279
|
+
if (!head || (mode === "own" && !actor)) return [];
|
|
280
|
+
const live = ["queued", "in_progress", "waiting", "pending", "requested"];
|
|
281
|
+
return (runs ?? []).filter((r) => r?.id != null && r.headSha && !sameSha(r.headSha, head) && live.includes(String(r.status).toLowerCase()) && events.includes(r.event)
|
|
282
|
+
&& (mode === "all" || String(r.actor ?? "").toLowerCase() === String(actor).toLowerCase()) && (pushedAt == null || !(Date.parse(r.createdAt) > pushedAt)));
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* #5718: cancel the superseded runs of `branch` after `head` was pushed. Seams: `io.branchRuns(branch)`, `io.cancelRun(id)`,
|
|
286
|
+
* `io.viewerLogin()` (only for `own`). Never throws and never touches a run of `head`: {cancelled: id[], failed: id[], skipped?: why}.
|
|
287
|
+
*/
|
|
288
|
+
export async function cancelSuperseded({ io, branch, head, mode = "off", pushedAt = null, dryRun = false }) {
|
|
289
|
+
if (mode !== "own" && mode !== "all") return { cancelled: [], failed: [], skipped: "off" };
|
|
290
|
+
if (!io?.branchRuns || !io?.cancelRun) return { cancelled: [], failed: [], skipped: "no seam" };
|
|
291
|
+
let runs = [], actor = null;
|
|
292
|
+
try { actor = mode === "own" ? await io.viewerLogin?.() : null; runs = (await io.branchRuns(branch)) ?? []; } catch { return { cancelled: [], failed: [], skipped: "runs unreadable" }; }
|
|
293
|
+
if (mode === "own" && !actor) return { cancelled: [], failed: [], skipped: "actor unknown" };
|
|
294
|
+
const out = { cancelled: [], failed: [] };
|
|
295
|
+
for (const r of supersededRuns({ runs, head, mode, actor, pushedAt })) {
|
|
296
|
+
if (dryRun) { out.cancelled.push(r.id); continue; }
|
|
297
|
+
try { await io.cancelRun(r.id); out.cancelled.push(r.id); } catch { out.failed.push(r.id); } // already finished (409) or no permission: the run just completes
|
|
298
|
+
}
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
230
302
|
const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "untracked_deferral"];
|
|
231
303
|
/**
|
|
232
304
|
* #4270: the `forgedock/verify` check-run payload from the results the lane already computed (no gate logic of its own).
|
|
@@ -265,3 +337,26 @@ export function verifyReport({ head = null, commands = null, structure = null, u
|
|
|
265
337
|
if (json.length > VERIFY_TEXT_CAP) json = JSON.stringify({ head, conclusion, truncated: true, gates: gates.map((g) => ({ id: g.id, ok: g.ok, ran: g.ran, evidence: JSON.stringify(g.evidence).slice(0, Math.floor(VERIFY_TEXT_CAP / (gates.length + 1))) })) }, null, 2);
|
|
266
338
|
return { conclusion, gates, title, summary, text: "```json\n" + json + "\n```" };
|
|
267
339
|
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* #5718 `forgedock ci cancel-superseded (--pr N | --branch B) [--repo o/r] [--mode own|all] [--dry-run]`: cancel the
|
|
343
|
+
* verification runs an older head of a branch still has in flight. The mode comes from forge.yaml
|
|
344
|
+
* `verify.cancel_superseded` unless `--mode` is given; off does nothing. `deps`: {seams({repo}), gh(args), config, print}.
|
|
345
|
+
*/
|
|
346
|
+
export async function cancelSupersededFromCli(argv, deps) {
|
|
347
|
+
const print = deps.print ?? ((s) => process.stdout.write(`${s}\n`));
|
|
348
|
+
const opt = (name) => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : null; };
|
|
349
|
+
const pr = opt("--pr"), dryRun = argv.includes("--dry-run");
|
|
350
|
+
let branch = opt("--branch"), head = null;
|
|
351
|
+
const mode = opt("--mode") ? parseCancelSuperseded(opt("--mode")) : deps.config?.cancelSuperseded ?? "off";
|
|
352
|
+
const repo = opt("--repo") ?? deps.repo ?? null;
|
|
353
|
+
if (!repo || (!pr && !branch) || (pr && !/^\d+$/.test(pr))) { print("usage: forgedock ci cancel-superseded (--pr N | --branch B) [--repo owner/repo] [--mode own|all] [--dry-run]"); return 2; }
|
|
354
|
+
if (mode === "off") { print("cancel-superseded: off (set verify.cancel_superseded: own|all in forge.yaml, or pass --mode)"); return 0; }
|
|
355
|
+
try {
|
|
356
|
+
if (pr) { const v = JSON.parse(await deps.gh(["pr", "view", pr, "-R", repo, "--json", "headRefName,headRefOid"])); branch = v.headRefName; head = v.headRefOid; }
|
|
357
|
+
else head = String(await deps.gh(["api", `repos/${repo}/branches/${encodeURIComponent(branch)}`, "--jq", ".commit.sha"])).trim();
|
|
358
|
+
} catch (e) { print(`cancel-superseded: cannot read the head of ${pr ? `#${pr}` : branch}: ${String(e?.stderr ?? e?.message ?? e).split("\n")[0].slice(0, 200)}`); return 1; }
|
|
359
|
+
const r = await cancelSuperseded({ io: deps.seams({ repo }), branch, head, mode, dryRun });
|
|
360
|
+
print(`cancel-superseded: ${branch} at ${String(head).slice(0, 12)} (${mode}${dryRun ? ", dry run" : ""}): ${r.skipped ? `skipped (${r.skipped})` : `${r.cancelled.length} run(s) ${dryRun ? "would be cancelled" : "cancelled"}${r.cancelled.length ? `: ${r.cancelled.join(", ")}` : ""}${r.failed.length ? `; ${r.failed.length} could not be cancelled` : ""}`}`);
|
|
361
|
+
return r.skipped && r.skipped !== "off" ? 1 : 0;
|
|
362
|
+
}
|
package/bin/pool/agent.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { createServer } from "node:http";
|
|
4
|
+
/** Retry-After for a launch whose lane_tools image is still building: lanes cap capacity deferrals at 3, so 3 × 5 min covers a cold build. */
|
|
5
|
+
const LANE_BUILD_RETRY_AFTER_S = 300;
|
|
4
6
|
import { randomBytes } from "node:crypto";
|
|
5
7
|
import { execFile, spawn } from "node:child_process";
|
|
6
8
|
import { promisify } from "node:util";
|
|
@@ -11,7 +13,7 @@ import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
|
11
13
|
import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
|
|
12
14
|
import { jsonStore } from "./store.mjs";
|
|
13
15
|
import { makeWarm } from "./warm.mjs";
|
|
14
|
-
import { resolveLaneImage } from "./lane-tools.mjs";
|
|
16
|
+
import { resolveLaneImage, laneImageNow, laneToolsTag } from "./lane-tools.mjs";
|
|
15
17
|
|
|
16
18
|
const LABEL = "computeshare=1";
|
|
17
19
|
const LOG_CHUNK = 256 * 1024;
|
|
@@ -50,7 +52,29 @@ export function liveHeadroom(cfg = {}) {
|
|
|
50
52
|
}
|
|
51
53
|
export const dindName = (name) => `${name}-dind`;
|
|
52
54
|
export const workVolume = (name) => `cs-work-${name.replace(/^cs-/, "")}`;
|
|
55
|
+
/** #5696: the lane worktree is a plain dir on the cache volume (one mount), so depcache hardlinks never hit EXDEV. */
|
|
56
|
+
export const workDirOf = (name) => `/cache/work/${name.replace(/^cs-/, "")}`;
|
|
57
|
+
const WORK_SWEEP_MS = 10 * 60000;
|
|
53
58
|
export const safeName = (id) => `cs-${String(id).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 100)}`;
|
|
59
|
+
/** Minimum gap between two environment-snapshot ensure runs for one cache volume. */
|
|
60
|
+
export const ENV_ENSURE_GAP_MS = 5 * 60000;
|
|
61
|
+
/**
|
|
62
|
+
* `docker run` args for the environment-snapshot helper (env.snapshots): a short-lived container of the lane image that
|
|
63
|
+
* reads the repo's bare mirror in the cache volume, builds the snapshot for the ref's lockfiles when it is missing,
|
|
64
|
+
* stages `ready` hardlink copies and collects old snapshots. It writes only under /cache/env, on the same volume as the
|
|
65
|
+
* lane worktrees (/cache/work), so a lane claims a staged copy with a rename. Pure.
|
|
66
|
+
*/
|
|
67
|
+
export function envEnsureArgs({ volume, image, slug, ref = null, laneTools = [], snapshots = {}, net = [], cpus = 2, mem_gb = 4 }) {
|
|
68
|
+
const int = (v, d) => (Number.isInteger(v) && v >= 0 ? v : d);
|
|
69
|
+
return [
|
|
70
|
+
"--rm", "--name", `cs-envbuild-${volume.replace(/^cs-cache-/, "")}`.slice(0, 120), "--label", "computeshare.env=1",
|
|
71
|
+
"--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, ...net, "-v", `${volume}:/cache`,
|
|
72
|
+
"-e", "FORGE_ENV_ROOT=/cache/env", "-e", `FORGE_ENV_IMAGE=${image}`, "-e", "FORGE_DEPCACHE_ROOT=/cache/forge-depcache", "-e", "npm_config_store_dir=/cache/pnpm-store",
|
|
73
|
+
"--entrypoint", "forgedock", image, "env", "ensure", "--mirror", `/cache/git/${String(slug).replace(/\//g, "_")}.git`, ...(ref ? ["--ref", String(ref)] : []),
|
|
74
|
+
"--repo", String(slug), "--ready", String(int(snapshots.ready, 2)), "--keep", String(int(snapshots.keep, 3)), "--max-age-days", String(int(snapshots.max_age_days, 14)),
|
|
75
|
+
...(laneTools.length ? ["--lane-tools", [...laneTools].sort().join(",")] : []),
|
|
76
|
+
];
|
|
77
|
+
}
|
|
54
78
|
const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
|
|
55
79
|
|
|
56
80
|
/**
|
|
@@ -94,6 +118,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
94
118
|
const used = () => Object.values(sb()).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
95
119
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
96
120
|
let diskCache = { at: 0, mb: {} };
|
|
121
|
+
let lastWorkSweep = -Infinity;
|
|
97
122
|
const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
|
|
98
123
|
function diskView() {
|
|
99
124
|
const out = {};
|
|
@@ -111,6 +136,20 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
111
136
|
return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), cpus_total: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active: Object.values(sb()).filter((s) => s.state !== "exited").length, ...diskView(), paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
112
137
|
}
|
|
113
138
|
|
|
139
|
+
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
140
|
+
const envImageOf = (spec) => (spec.lane_tools?.length ? laneToolsTag(spec.image ?? image, spec.lane_tools) : (spec.image ?? image));
|
|
141
|
+
const envEnsured = new Map(); // cache volume -> last ensure start
|
|
142
|
+
/**
|
|
143
|
+
* env.snapshots: start the snapshot helper for the repo, at most once per ENV_ENSURE_GAP_MS and one at a time per cache
|
|
144
|
+
* volume (the fixed container name refuses a second). Never awaited by a launch and never fails one.
|
|
145
|
+
*/
|
|
146
|
+
function ensureEnv({ volume, spec, net }) {
|
|
147
|
+
if (now() - (envEnsured.get(volume) ?? -Infinity) < ENV_ENSURE_GAP_MS) return null;
|
|
148
|
+
envEnsured.set(volume, now());
|
|
149
|
+
const args = envEnsureArgs({ volume, image: envImageOf(spec), slug: spec.repo.slug, ref: spec.repo.ref ?? null, laneTools: spec.lane_tools ?? [], snapshots: spec.env_snapshots, net, cpus: cfg.env_build_cpus ?? 2, mem_gb: cfg.env_build_mem_gb ?? 4 });
|
|
150
|
+
return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
|
|
151
|
+
}
|
|
152
|
+
|
|
114
153
|
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
115
154
|
if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id) || !Array.isArray(spec.command) || !spec.command.length) throw Object.assign(new Error("spec.id ([A-Za-z0-9._-], max 128) and spec.command are required"), { status: 400 });
|
|
116
155
|
const existing = own(spec.id);
|
|
@@ -121,6 +160,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
121
160
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
122
161
|
const h = live(cfg);
|
|
123
162
|
if (!h.ok) return { status: 503, body: { error: `host busy: ${h.reason}`, live: h }, retryAfter: 60 };
|
|
163
|
+
if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
|
|
164
|
+
let st;
|
|
165
|
+
try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
|
|
166
|
+
if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
|
|
167
|
+
if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
|
|
168
|
+
}
|
|
124
169
|
const name = safeName(spec.id);
|
|
125
170
|
const dir = join(stateDir, "sandboxes", name);
|
|
126
171
|
mkdirSync(join(dir, "result"), { recursive: true });
|
|
@@ -129,15 +174,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
129
174
|
const envFile = join(dir, "env");
|
|
130
175
|
const credToken = randomBytes(24).toString("hex");
|
|
131
176
|
const withDocker = Boolean(spec.docker);
|
|
132
|
-
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? ""
|
|
177
|
+
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
178
|
+
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
133
179
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
134
180
|
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker };
|
|
135
181
|
sb()[spec.id] = rec;
|
|
136
182
|
store.save();
|
|
137
183
|
const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
|
|
184
|
+
rec.cacheVolume = `cs-cache-${cacheKey}`;
|
|
185
|
+
rec.workDir = workDirOf(name);
|
|
138
186
|
// Public resolvers: host resolvers like Tailscale MagicDNS are not reachable from the container network.
|
|
139
187
|
const netArgs = ["--add-host", "host.docker.internal:host-gateway", ...(cfg.dns ?? ["1.1.1.1", "8.8.8.8"]).flatMap((d) => ["--dns", String(d)])];
|
|
140
188
|
let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
|
|
189
|
+
const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
|
|
141
190
|
try {
|
|
142
191
|
// #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
|
|
143
192
|
const laneImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
|
|
@@ -149,7 +198,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
149
198
|
if (limit) { dCpus = limit.dind_cpus; dMem = limit.dind_mem_gb; laneCpus = limit.lane_cpus; laneMem = limit.lane_mem_gb; }
|
|
150
199
|
else { dCpus = Math.min(cfg.dind_cpus ?? 1, cpus - 1); dMem = Math.min(cfg.dind_mem_gb ?? 2, mem_gb - 1); laneCpus = cpus - dCpus; laneMem = mem_gb - dMem; }
|
|
151
200
|
({ cpus: dCpus, mem: dMem } = clampToVm(dCpus, dMem));
|
|
152
|
-
work =
|
|
201
|
+
work = cacheMount; // the daemon sees the checkout at the same /cache/work path as the lane
|
|
153
202
|
await docker.run([
|
|
154
203
|
"--name", dindName(name), "--label", LABEL, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
|
|
155
204
|
"--privileged", "--cpus", String(dCpus), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
|
|
@@ -168,10 +217,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
168
217
|
"--cpus", String(laneCpus), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
169
218
|
"--env-file", envFile, ...laneNet, ...work,
|
|
170
219
|
...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
|
|
171
|
-
|
|
220
|
+
...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
|
|
172
221
|
laneImage, ...spec.command.map(String),
|
|
173
222
|
]);
|
|
174
223
|
rec.state = "running";
|
|
224
|
+
if (spec.env_snapshots?.enabled && spec.repo?.slug) ensureEnv({ volume: rec.cacheVolume, spec, net: netArgs });
|
|
175
225
|
} catch (e) {
|
|
176
226
|
rec.state = "exited";
|
|
177
227
|
rec.finishedAt = now();
|
|
@@ -220,7 +270,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
220
270
|
if (!r) return false;
|
|
221
271
|
const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
|
|
222
272
|
await docker.remove(r.name);
|
|
223
|
-
if (r.docker)
|
|
273
|
+
if (r.docker) await docker.remove(dindName(r.name));
|
|
274
|
+
if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { log.warn?.(`work dir ${r.workDir}: ${String(e.stderr || e.message).slice(0, 200)}`); } }
|
|
275
|
+
else if (r.docker) await docker.removeVolume(workVolume(r.name)); // sandbox launched before #5696
|
|
224
276
|
try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
225
277
|
rmSync(r.dir, { recursive: true, force: true });
|
|
226
278
|
delete sb()[r.id];
|
|
@@ -246,8 +298,15 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
246
298
|
const r = await resize(pendingResize);
|
|
247
299
|
log.info?.(`pending resize applied: HTTP ${r.status} ${JSON.stringify(r.body)}`);
|
|
248
300
|
}
|
|
249
|
-
const knownVols = new Set(Object.values(sb()).map((r) => workVolume(r.name)));
|
|
301
|
+
const knownVols = new Set(Object.values(sb()).filter((r) => !r.workDir).map((r) => workVolume(r.name)));
|
|
250
302
|
for (const v of await docker.listVolumes("cs-work-")) if (!knownVols.has(v)) { await docker.removeVolume(v); log.info?.(`removed orphan volume ${v}`); }
|
|
303
|
+
if (t - lastWorkSweep >= WORK_SWEEP_MS) {
|
|
304
|
+
lastWorkSweep = t;
|
|
305
|
+
const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
|
|
306
|
+
for (const v of await docker.listVolumes("cs-cache-")) {
|
|
307
|
+
try { await docker.pruneWorkDirs(v, image, keep); } catch (e) { log.warn?.(`work sweep ${v}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
308
|
+
}
|
|
309
|
+
}
|
|
251
310
|
store.save();
|
|
252
311
|
}
|
|
253
312
|
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { classifyCiFailure } from "../lean/ci-classify.mjs";
|
|
7
|
+
|
|
8
|
+
/** #5688: CI runner events pushed to the pool router and long-polled by agents (parent #5687). */
|
|
9
|
+
export const CI_EVENT_TYPES = ["job_started", "step_started", "step_failed", "test_failed", "job_finished", "runner_unhealthy"];
|
|
10
|
+
export const MAX_BATCH = 200, MAX_LINES = 40, MAX_LINE_CHARS = 500, RING_CAP = 2000, TTL_MS = 24 * 3600 * 1000, MAX_WAIT_S = 60;
|
|
11
|
+
const MAX_STR = 500;
|
|
12
|
+
const DAY_MS = 24 * 3600 * 1000;
|
|
13
|
+
|
|
14
|
+
const bad = (key, why, status = 400) => Object.assign(new Error(`invalid event: ${key} ${why}`), { status, key });
|
|
15
|
+
const str = (e, key, required) => {
|
|
16
|
+
const v = e[key];
|
|
17
|
+
if (v === undefined || v === null) { if (required) throw bad(key, "is required"); return undefined; }
|
|
18
|
+
if (typeof v !== "string" || !v || v.length > MAX_STR) throw bad(key, "must be a non-empty string of at most 500 chars");
|
|
19
|
+
return v;
|
|
20
|
+
};
|
|
21
|
+
const int = (e, key) => {
|
|
22
|
+
const v = e[key];
|
|
23
|
+
if (v === undefined || v === null) return undefined;
|
|
24
|
+
if (!Number.isInteger(v)) throw bad(key, "must be an integer");
|
|
25
|
+
return v;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** Returns the normalized event (known keys only) or throws an error carrying `status` (400 bad key, 413 over a limit) and `key`. */
|
|
29
|
+
export function validateEvent(e) {
|
|
30
|
+
if (!e || typeof e !== "object" || Array.isArray(e)) throw bad("event", "must be an object");
|
|
31
|
+
if (!CI_EVENT_TYPES.includes(e.type)) throw bad("type", `must be one of ${CI_EVENT_TYPES.join(", ")}`);
|
|
32
|
+
const out = { type: e.type, repo: str(e, "repo", true), sha: str(e, "sha", true) };
|
|
33
|
+
const run = e.run_id;
|
|
34
|
+
if (run === undefined || run === null) throw bad("run_id", "is required");
|
|
35
|
+
if (!(typeof run === "string" && run && run.length <= MAX_STR) && !Number.isInteger(run)) throw bad("run_id", "must be a string or integer");
|
|
36
|
+
out.run_id = run;
|
|
37
|
+
out.job = str(e, "job", true);
|
|
38
|
+
const ts = e.ts;
|
|
39
|
+
if (ts === undefined || ts === null) throw bad("ts", "is required");
|
|
40
|
+
if (!(typeof ts === "string" && ts && ts.length <= MAX_STR) && !Number.isFinite(ts)) throw bad("ts", "must be a string or number");
|
|
41
|
+
out.ts = ts;
|
|
42
|
+
if (e.pr !== undefined && e.pr !== null) {
|
|
43
|
+
if (!Number.isInteger(e.pr) && !(typeof e.pr === "string" && /^\d{1,9}$/.test(e.pr))) throw bad("pr", "must be an integer");
|
|
44
|
+
out.pr = Number(e.pr);
|
|
45
|
+
}
|
|
46
|
+
const step = str(e, "step"), cls = str(e, "class"), code = int(e, "exit_code");
|
|
47
|
+
if (step !== undefined) out.step = step;
|
|
48
|
+
if (cls !== undefined) out.class = cls;
|
|
49
|
+
if (code !== undefined) out.exit_code = code;
|
|
50
|
+
if (e.lines !== undefined && e.lines !== null) {
|
|
51
|
+
if (!Array.isArray(e.lines) || !e.lines.every((l) => typeof l === "string")) throw bad("lines", "must be a list of strings");
|
|
52
|
+
if (e.lines.length > MAX_LINES) throw bad("lines", `has more than ${MAX_LINES} entries`, 413);
|
|
53
|
+
if (e.lines.some((l) => l.length > MAX_LINE_CHARS)) throw bad("lines", `has an entry over ${MAX_LINE_CHARS} chars`, 413);
|
|
54
|
+
out.lines = e.lines;
|
|
55
|
+
}
|
|
56
|
+
if (e.test !== undefined && e.test !== null) {
|
|
57
|
+
const t = e.test;
|
|
58
|
+
if (typeof t !== "object" || Array.isArray(t)) throw bad("test", "must be an object");
|
|
59
|
+
const tid = str(t, "id", true), file = str(t, "file"), line = int(t, "line"), message = t.message;
|
|
60
|
+
if (message !== undefined && (typeof message !== "string" || message.length > 4 * MAX_STR)) throw bad("test.message", "must be a string of at most 2000 chars");
|
|
61
|
+
out.test = { id: tid, ...(file !== undefined ? { file } : {}), ...(line !== undefined ? { line } : {}), ...(message !== undefined ? { message } : {}) };
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Fixed-capacity circular buffer: pushing past the cap overwrites the oldest entry without shifting. */
|
|
67
|
+
class Ring {
|
|
68
|
+
constructor(cap) { this.cap = cap; this.a = new Array(cap); this.start = 0; this.len = 0; }
|
|
69
|
+
push(v) {
|
|
70
|
+
if (this.len < this.cap) this.a[(this.start + this.len++) % this.cap] = v;
|
|
71
|
+
else { this.a[this.start] = v; this.start = (this.start + 1) % this.cap; }
|
|
72
|
+
}
|
|
73
|
+
dropWhile(pred) { while (this.len && pred(this.a[this.start])) { this.a[this.start] = undefined; this.start = (this.start + 1) % this.cap; this.len--; } }
|
|
74
|
+
*[Symbol.iterator]() { for (let i = 0; i < this.len; i++) yield this.a[(this.start + i) % this.cap]; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const repoKey = (repo) => `${repo.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80)}-${createHash("sha1").update(repo).digest("hex").slice(0, 8)}`;
|
|
78
|
+
const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Event store. Memory: a ring per (repo, sha), 2000 events, 24 h TTL. Disk: `<dir>/<repo-key>.ndjson`, rotated to
|
|
82
|
+
* `<repo-key>.<YYYY-MM-DD>.ndjson` when the UTC day changes; the last 24 h are reloaded on creation and `seq` resumes.
|
|
83
|
+
*/
|
|
84
|
+
/** `classify(event, flakes)` fills `class` on failures that lack one; `flakes()` returns the ledger list (default none). Neither cancels anything. */
|
|
85
|
+
export function createCiEvents({ dir, now = () => Date.now(), cap = RING_CAP, ttlMs = TTL_MS, classify = classifyCiFailure, flakes = () => [] } = {}) {
|
|
86
|
+
const rings = new Map(); // `${repo}\n${sha}` -> Ring
|
|
87
|
+
const fileDay = new Map(); // repo-key -> UTC day of its active file's last write
|
|
88
|
+
const waiters = new Set();
|
|
89
|
+
let seq = 0, lastSweep = now();
|
|
90
|
+
|
|
91
|
+
const keep = (e, t) => t - e.received_at < ttlMs;
|
|
92
|
+
const put = (e) => {
|
|
93
|
+
const k = `${e.repo}\n${e.sha}`;
|
|
94
|
+
let r = rings.get(k);
|
|
95
|
+
if (!r) rings.set(k, (r = new Ring(cap)));
|
|
96
|
+
r.push(e);
|
|
97
|
+
};
|
|
98
|
+
const sweep = (t) => {
|
|
99
|
+
lastSweep = t;
|
|
100
|
+
for (const [k, r] of rings) { r.dropWhile((e) => !keep(e, t)); if (!r.len) rings.delete(k); }
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
function load() {
|
|
104
|
+
if (!dir || !existsSync(dir)) return;
|
|
105
|
+
const t = now(), all = [];
|
|
106
|
+
for (const f of readdirSync(dir)) {
|
|
107
|
+
if (!f.endsWith(".ndjson")) continue;
|
|
108
|
+
const p = join(dir, f);
|
|
109
|
+
try { if (t - statSync(p).mtimeMs > ttlMs + DAY_MS) continue; } catch { continue; }
|
|
110
|
+
for (const line of readFileSync(p, "utf8").split("\n")) {
|
|
111
|
+
if (!line) continue;
|
|
112
|
+
try { const e = JSON.parse(line); if (Number.isFinite(e.seq) && Number.isFinite(e.received_at)) all.push(e); } catch { /* torn line */ }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
all.sort((a, b) => a.seq - b.seq);
|
|
116
|
+
for (const e of all) { seq = Math.max(seq, e.seq); if (keep(e, t)) put(e); }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function persist(batch) {
|
|
120
|
+
if (!dir) return;
|
|
121
|
+
mkdirSync(dir, { recursive: true });
|
|
122
|
+
const t = now(), today = dayOf(t), byFile = new Map();
|
|
123
|
+
for (const e of batch) { const k = repoKey(e.repo); (byFile.get(k) ?? byFile.set(k, []).get(k)).push(e); }
|
|
124
|
+
for (const [k, es] of byFile) {
|
|
125
|
+
const file = join(dir, `${k}.ndjson`);
|
|
126
|
+
let day = fileDay.get(k);
|
|
127
|
+
if (!day && existsSync(file)) day = dayOf(statSync(file).mtimeMs);
|
|
128
|
+
if (day && day !== today && existsSync(file)) renameSync(file, join(dir, `${k}.${day}.ndjson`));
|
|
129
|
+
fileDay.set(k, today);
|
|
130
|
+
appendFileSync(file, es.map((e) => JSON.stringify(e)).join("\n") + "\n", { mode: 0o600 });
|
|
131
|
+
}
|
|
132
|
+
if (byFile.size) for (const f of readdirSync(dir)) { // drop rotated files whose whole day is past the TTL
|
|
133
|
+
const m = /\.(\d{4}-\d{2}-\d{2})\.ndjson$/.exec(f);
|
|
134
|
+
if (m && t - Date.parse(`${m[1]}T00:00:00Z`) > ttlMs + DAY_MS) try { unlinkSync(join(dir, f)); } catch { /* raced */ }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const matches = (e, q) => e.repo === q.repo && (q.sha === undefined || e.sha === q.sha) && (q.pr === undefined || e.pr === q.pr);
|
|
139
|
+
|
|
140
|
+
/** Events of `q` ({repo, sha?, pr?}) with seq > since, oldest first; `next` is the cursor to resume from. */
|
|
141
|
+
function query(q, since = 0) {
|
|
142
|
+
const t = now();
|
|
143
|
+
if (t - lastSweep > 60000) sweep(t);
|
|
144
|
+
const out = [];
|
|
145
|
+
if (q.sha !== undefined) { const r = rings.get(`${q.repo}\n${q.sha}`); if (r) for (const e of r) if (e.seq > since && keep(e, t) && matches(e, q)) out.push(e); }
|
|
146
|
+
else for (const [k, r] of rings) if (k.startsWith(`${q.repo}\n`)) for (const e of r) if (e.seq > since && keep(e, t) && matches(e, q)) out.push(e);
|
|
147
|
+
out.sort((a, b) => a.seq - b.seq);
|
|
148
|
+
return { events: out, next: out.length ? out[out.length - 1].seq : Math.max(since, seq) };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const safeFlakes = () => { try { return flakes() ?? []; } catch { return []; } };
|
|
152
|
+
const withClass = (e, fl) => {
|
|
153
|
+
if (!classify || e.class !== undefined || (!e.lines?.length && !e.test) || (e.type !== "step_failed" && e.type !== "test_failed")) return e;
|
|
154
|
+
try { const c = classify({ step: e.step, lines: e.lines, test: e.test, flakes: fl }); return c?.class ? { ...e, class: c.class } : e; } catch { return e; }
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** Validates the whole list first (nothing is stored when one event is bad), then stamps `received_at` and `seq`. */
|
|
158
|
+
function ingest(input) {
|
|
159
|
+
const list = Array.isArray(input) ? input : [input];
|
|
160
|
+
if (!list.length) throw Object.assign(new Error("invalid event: body is empty"), { status: 400 });
|
|
161
|
+
if (list.length > MAX_BATCH) throw Object.assign(new Error(`too many events (max ${MAX_BATCH})`), { status: 413 });
|
|
162
|
+
const clean = list.map((e, i) => { try { return validateEvent(e); } catch (err) { if (list.length > 1) err.message = `${err.message} (event ${i})`; throw err; } });
|
|
163
|
+
const t = now(), fl = classify ? safeFlakes() : [];
|
|
164
|
+
const stamped = clean.map((e) => ({ ...withClass(e, fl), seq: ++seq, received_at: t }));
|
|
165
|
+
persist(stamped);
|
|
166
|
+
for (const e of stamped) put(e);
|
|
167
|
+
for (const w of [...waiters]) { const r = query(w.q, w.since); if (r.events.length) { waiters.delete(w); clearTimeout(w.timer); w.resolve(r); } }
|
|
168
|
+
return { accepted: stamped.length, seq };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Long-poll: resolves at once when events exist, else on the next matching ingest or after `waitS` seconds (max 60). */
|
|
172
|
+
function wait(q, since = 0, waitS = 0) {
|
|
173
|
+
const r = query(q, since), ms = Math.min(Math.max(Number(waitS) || 0, 0), MAX_WAIT_S) * 1000;
|
|
174
|
+
if (r.events.length || !ms) return Promise.resolve(r);
|
|
175
|
+
return new Promise((resolve) => {
|
|
176
|
+
const w = { q, since, resolve, timer: setTimeout(() => { waiters.delete(w); resolve(query(q, since)); }, ms) };
|
|
177
|
+
waiters.add(w);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
load();
|
|
182
|
+
return { ingest, query, wait, get seq() { return seq; }, size: () => [...rings.values()].reduce((n, r) => n + r.len, 0) };
|
|
183
|
+
}
|