forgedock 1.60.1 → 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/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 +38 -6
- package/bin/lean/lean.test.mjs +61 -0
- 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/verify-settle.test.mjs +156 -0
- package/bin/lean/verify.mjs +98 -3
- package/bin/pool/agent.mjs +57 -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 +1 -0
- package/bin/pool/router.mjs +18 -0
- package/bin/pool/warm.mjs +1 -1
- 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/templates/github-actions/forge-env/action.yml +65 -0
package/bin/pool/agent.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
|
13
13
|
import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
|
|
14
14
|
import { jsonStore } from "./store.mjs";
|
|
15
15
|
import { makeWarm } from "./warm.mjs";
|
|
16
|
-
import { resolveLaneImage, laneImageNow } from "./lane-tools.mjs";
|
|
16
|
+
import { resolveLaneImage, laneImageNow, laneToolsTag } from "./lane-tools.mjs";
|
|
17
17
|
|
|
18
18
|
const LABEL = "computeshare=1";
|
|
19
19
|
const LOG_CHUNK = 256 * 1024;
|
|
@@ -52,7 +52,29 @@ export function liveHeadroom(cfg = {}) {
|
|
|
52
52
|
}
|
|
53
53
|
export const dindName = (name) => `${name}-dind`;
|
|
54
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;
|
|
55
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
|
+
}
|
|
56
78
|
const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
|
|
57
79
|
|
|
58
80
|
/**
|
|
@@ -96,6 +118,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
96
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 });
|
|
97
119
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
98
120
|
let diskCache = { at: 0, mb: {} };
|
|
121
|
+
let lastWorkSweep = -Infinity;
|
|
99
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); };
|
|
100
123
|
function diskView() {
|
|
101
124
|
const out = {};
|
|
@@ -113,6 +136,20 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
113
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 }])) };
|
|
114
137
|
}
|
|
115
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
|
+
|
|
116
153
|
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
117
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 });
|
|
118
155
|
const existing = own(spec.id);
|
|
@@ -137,15 +174,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
137
174
|
const envFile = join(dir, "env");
|
|
138
175
|
const credToken = randomBytes(24).toString("hex");
|
|
139
176
|
const withDocker = Boolean(spec.docker);
|
|
140
|
-
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
|
|
141
179
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
142
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 };
|
|
143
181
|
sb()[spec.id] = rec;
|
|
144
182
|
store.save();
|
|
145
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);
|
|
146
186
|
// Public resolvers: host resolvers like Tailscale MagicDNS are not reachable from the container network.
|
|
147
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)])];
|
|
148
188
|
let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
|
|
189
|
+
const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
|
|
149
190
|
try {
|
|
150
191
|
// #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
|
|
151
192
|
const laneImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
|
|
@@ -157,7 +198,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
157
198
|
if (limit) { dCpus = limit.dind_cpus; dMem = limit.dind_mem_gb; laneCpus = limit.lane_cpus; laneMem = limit.lane_mem_gb; }
|
|
158
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; }
|
|
159
200
|
({ cpus: dCpus, mem: dMem } = clampToVm(dCpus, dMem));
|
|
160
|
-
work =
|
|
201
|
+
work = cacheMount; // the daemon sees the checkout at the same /cache/work path as the lane
|
|
161
202
|
await docker.run([
|
|
162
203
|
"--name", dindName(name), "--label", LABEL, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
|
|
163
204
|
"--privileged", "--cpus", String(dCpus), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
|
|
@@ -176,10 +217,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
176
217
|
"--cpus", String(laneCpus), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
177
218
|
"--env-file", envFile, ...laneNet, ...work,
|
|
178
219
|
...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
|
|
179
|
-
|
|
220
|
+
...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
|
|
180
221
|
laneImage, ...spec.command.map(String),
|
|
181
222
|
]);
|
|
182
223
|
rec.state = "running";
|
|
224
|
+
if (spec.env_snapshots?.enabled && spec.repo?.slug) ensureEnv({ volume: rec.cacheVolume, spec, net: netArgs });
|
|
183
225
|
} catch (e) {
|
|
184
226
|
rec.state = "exited";
|
|
185
227
|
rec.finishedAt = now();
|
|
@@ -228,7 +270,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
228
270
|
if (!r) return false;
|
|
229
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;
|
|
230
272
|
await docker.remove(r.name);
|
|
231
|
-
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
|
|
232
276
|
try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
233
277
|
rmSync(r.dir, { recursive: true, force: true });
|
|
234
278
|
delete sb()[r.id];
|
|
@@ -254,8 +298,15 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
254
298
|
const r = await resize(pendingResize);
|
|
255
299
|
log.info?.(`pending resize applied: HTTP ${r.status} ${JSON.stringify(r.body)}`);
|
|
256
300
|
}
|
|
257
|
-
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)));
|
|
258
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
|
+
}
|
|
259
310
|
store.save();
|
|
260
311
|
}
|
|
261
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
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { appendFileSync, readdirSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { CI_EVENT_TYPES, createCiEvents, validateEvent } from "./ci-events.mjs";
|
|
8
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
+
|
|
10
|
+
const ev = (type, extra = {}) => ({ type, repo: "o/r", sha: "abc", run_id: 7, job: "unit", ts: "2026-11-15T00:00:00Z", ...extra });
|
|
11
|
+
const fail = (status, key) => (e) => e.status === status && (key ? e.message.includes(key) : true);
|
|
12
|
+
|
|
13
|
+
test("all 6 event types validate; optional keys are kept", () => {
|
|
14
|
+
for (const t of CI_EVENT_TYPES) assert.equal(validateEvent(ev(t)).type, t);
|
|
15
|
+
const e = validateEvent(ev("test_failed", { pr: 12, step: "s", exit_code: 1, class: "code", lines: ["a"], test: { id: "t1", file: "f.py", line: 3, message: "boom" }, junk: 1 }));
|
|
16
|
+
assert.deepEqual([e.pr, e.step, e.exit_code, e.class, e.lines, e.test.id, e.junk], [12, "s", 1, "code", ["a"], "t1", undefined]);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("missing repo/sha/ts/run_id/job and an unknown type are 400 naming the key", () => {
|
|
20
|
+
for (const k of ["repo", "sha", "ts", "run_id", "job"]) { const e = ev("step_failed"); delete e[k]; assert.throws(() => validateEvent(e), fail(400, k)); }
|
|
21
|
+
assert.throws(() => validateEvent(ev("nope")), fail(400, "type"));
|
|
22
|
+
assert.throws(() => validateEvent(ev("step_failed", { pr: "x" })), fail(400, "pr"));
|
|
23
|
+
assert.throws(() => validateEvent(ev("step_failed", { exit_code: "1" })), fail(400, "exit_code"));
|
|
24
|
+
assert.throws(() => validateEvent(null), fail(400));
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("more than 40 lines, a line over 500 chars, or more than 200 events is 413", () => {
|
|
28
|
+
assert.throws(() => validateEvent(ev("step_failed", { lines: Array(41).fill("x") })), fail(413, "lines"));
|
|
29
|
+
assert.equal(validateEvent(ev("step_failed", { lines: Array(40).fill("x".repeat(500)) })).lines.length, 40);
|
|
30
|
+
assert.throws(() => validateEvent(ev("step_failed", { lines: ["x".repeat(501)] })), fail(413, "lines"));
|
|
31
|
+
const s = createCiEvents({});
|
|
32
|
+
assert.throws(() => s.ingest(Array(201).fill(ev("job_started"))), fail(413));
|
|
33
|
+
assert.equal(s.ingest(Array(200).fill(ev("job_started"))).accepted, 200);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("a bad event rejects the whole array and stores nothing", () => {
|
|
37
|
+
const s = createCiEvents({});
|
|
38
|
+
assert.throws(() => s.ingest([ev("job_started"), ev("step_failed", { sha: undefined })]), fail(400, "sha"));
|
|
39
|
+
assert.equal(s.size(), 0);
|
|
40
|
+
assert.equal(s.seq, 0);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("seq is monotonic; sha and pr filters and since work", () => {
|
|
44
|
+
const s = createCiEvents({});
|
|
45
|
+
s.ingest([ev("job_started"), ev("step_failed", { sha: "def", pr: 5 }), ev("step_failed", { pr: 5 })]);
|
|
46
|
+
const all = s.query({ repo: "o/r", sha: "abc" });
|
|
47
|
+
assert.deepEqual(all.events.map((e) => e.seq), [1, 3]);
|
|
48
|
+
assert.equal(all.next, 3);
|
|
49
|
+
assert.deepEqual(s.query({ repo: "o/r", pr: 5 }).events.map((e) => e.sha), ["def", "abc"]);
|
|
50
|
+
assert.equal(s.query({ repo: "o/r", sha: "abc" }, 1).events.length, 1);
|
|
51
|
+
const none = s.query({ repo: "o/r", sha: "abc" }, 3);
|
|
52
|
+
assert.deepEqual([none.events.length, none.next], [0, 3]);
|
|
53
|
+
assert.equal(s.query({ repo: "other", sha: "abc" }).events.length, 0);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("ring cap keeps the newest events; TTL expires old ones", () => {
|
|
57
|
+
let t = 1_000_000;
|
|
58
|
+
const s = createCiEvents({ cap: 5, ttlMs: 1000, now: () => t });
|
|
59
|
+
for (let i = 0; i < 8; i++) s.ingest(ev("step_started", { step: `s${i}` }));
|
|
60
|
+
assert.deepEqual(s.query({ repo: "o/r", sha: "abc" }).events.map((e) => e.step), ["s3", "s4", "s5", "s6", "s7"]);
|
|
61
|
+
t += 1500;
|
|
62
|
+
assert.equal(s.query({ repo: "o/r", sha: "abc" }).events.length, 0);
|
|
63
|
+
t += 61000;
|
|
64
|
+
s.query({ repo: "o/r", sha: "abc" });
|
|
65
|
+
assert.equal(s.size(), 0);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("NDJSON is written, rotates on a new UTC day, and a restart reloads and resumes seq", () => {
|
|
69
|
+
const dir = tmpDir("ci-ev-");
|
|
70
|
+
let t = Date.parse("2026-11-15T10:00:00Z");
|
|
71
|
+
const a = createCiEvents({ dir, now: () => t });
|
|
72
|
+
a.ingest([ev("job_started"), ev("step_failed")]);
|
|
73
|
+
const [f] = readdirSync(dir);
|
|
74
|
+
assert.match(f, /^o_r-[0-9a-f]{8}\.ndjson$/);
|
|
75
|
+
assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 2);
|
|
76
|
+
t = Date.parse("2026-11-16T01:00:00Z");
|
|
77
|
+
a.ingest(ev("job_finished"));
|
|
78
|
+
assert.ok(readdirSync(dir).some((n) => /\.2026-11-15\.ndjson$/.test(n)), "yesterday's file rotated");
|
|
79
|
+
assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 1);
|
|
80
|
+
t += 3600000;
|
|
81
|
+
const b = createCiEvents({ dir, now: () => t });
|
|
82
|
+
assert.equal(b.seq, 3);
|
|
83
|
+
assert.deepEqual(b.query({ repo: "o/r", sha: "abc" }, 1).events.map((e) => e.type), ["step_failed", "job_finished"]);
|
|
84
|
+
assert.equal(b.ingest(ev("job_started")).seq, 4);
|
|
85
|
+
t += 25 * 3600000; // past the TTL
|
|
86
|
+
assert.equal(createCiEvents({ dir, now: () => t }).size(), 0);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a restart ignores a torn trailing line", () => {
|
|
90
|
+
const dir = tmpDir("ci-ev-");
|
|
91
|
+
createCiEvents({ dir }).ingest(ev("job_started"));
|
|
92
|
+
appendFileSync(join(dir, readdirSync(dir)[0]), '{"seq":2,"rec');
|
|
93
|
+
const b = createCiEvents({ dir });
|
|
94
|
+
assert.deepEqual([b.size(), b.seq], [1, 1]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("long-poll wakes within 200 ms of a matching POST and ignores non-matching ones", async () => {
|
|
98
|
+
const s = createCiEvents({});
|
|
99
|
+
const t0 = performance.now();
|
|
100
|
+
const p = s.wait({ repo: "o/r", sha: "abc" }, 0, 30);
|
|
101
|
+
setTimeout(() => { s.ingest(ev("step_failed", { sha: "zzz" })); s.ingest(ev("step_failed")); }, 20);
|
|
102
|
+
const r = await p;
|
|
103
|
+
assert.ok(performance.now() - t0 < 200);
|
|
104
|
+
assert.deepEqual([r.events.length, r.events[0].sha, r.next], [1, "abc", 2]);
|
|
105
|
+
const empty = await s.wait({ repo: "o/r", sha: "abc" }, 2, 0.05);
|
|
106
|
+
assert.deepEqual([empty.events.length, empty.next], [0, 2]);
|
|
107
|
+
assert.equal((await s.wait({ repo: "o/r", sha: "abc" }, 0, 30)).events.length, 1, "existing events return at once");
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("bench: 10000 events ingest at 2000+/s with under 50 MB RSS growth", () => {
|
|
111
|
+
const s = createCiEvents({ dir: tmpDir("ci-ev-") });
|
|
112
|
+
const batch = (i) => Array.from({ length: 200 }, (_, j) => ev("test_failed", { sha: `sha${(i + j) % 5}`, lines: ["AssertionError: x".repeat(4)], test: { id: `t${i}-${j}`, file: "a.py", line: 1, message: "m" } }));
|
|
113
|
+
const rss0 = process.memoryUsage().rss, t0 = performance.now();
|
|
114
|
+
for (let i = 0; i < 50; i++) s.ingest(batch(i));
|
|
115
|
+
const secs = (performance.now() - t0) / 1000, rate = 10000 / secs, grow = (process.memoryUsage().rss - rss0) / 1048576;
|
|
116
|
+
console.log(`# ci-events bench: ${rate.toFixed(0)} events/s, rss +${grow.toFixed(1)} MB`);
|
|
117
|
+
assert.equal(s.seq, 10000);
|
|
118
|
+
assert.ok(rate >= 2000, `${rate} events/s`);
|
|
119
|
+
assert.ok(grow < 50, `rss +${grow} MB`);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("ingest classifies step_failed/test_failed without a class (#5690)", () => {
|
|
123
|
+
const ci = createCiEvents({ dir: tmpDir("ci-class") });
|
|
124
|
+
ci.ingest([
|
|
125
|
+
ev("step_failed", { lines: ["sh: tsc: command not found"] }),
|
|
126
|
+
ev("test_failed", { test: { id: "t1", message: "AssertionError: 1 !== 2" } }),
|
|
127
|
+
ev("step_failed", { lines: ["sh: tsc: command not found"], class: "infra" }),
|
|
128
|
+
ev("step_failed"),
|
|
129
|
+
ev("job_started", { lines: ["sh: tsc: command not found"] }),
|
|
130
|
+
]);
|
|
131
|
+
const got = ci.query({ repo: "o/r", sha: "abc" }).events;
|
|
132
|
+
assert.deepEqual(got.map((e) => e.class), ["deterministic-setup", "code", "infra", undefined, undefined]);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("ingest uses an injected classifier and flake ledger; a throwing classifier never rejects the batch (#5690)", () => {
|
|
136
|
+
let seen;
|
|
137
|
+
const ci = createCiEvents({ dir: tmpDir("ci-class2"), classify: (x) => { seen = x; return { class: "flaky-suspect" }; }, flakes: () => ["f"] });
|
|
138
|
+
ci.ingest(ev("step_failed", { lines: ["x"] }));
|
|
139
|
+
assert.deepEqual(seen.flakes, ["f"]);
|
|
140
|
+
assert.equal(ci.query({ repo: "o/r", sha: "abc" }).events[0].class, "flaky-suspect");
|
|
141
|
+
const bad = createCiEvents({ dir: tmpDir("ci-class3"), classify: () => { throw new Error("x"); } });
|
|
142
|
+
assert.equal(bad.ingest(ev("step_failed", { lines: ["x"] })).accepted, 1);
|
|
143
|
+
});
|
package/bin/pool/docker.mjs
CHANGED
|
@@ -56,6 +56,13 @@ export const dockerCli = {
|
|
|
56
56
|
return res;
|
|
57
57
|
},
|
|
58
58
|
async build(dir, tag, buildArgs = {}) { return docker(["build", "-q", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000 }); },
|
|
59
|
+
/** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
|
|
60
|
+
async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: 120000 }); },
|
|
61
|
+
/** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
|
|
62
|
+
async pruneWorkDirs(volume, image, keep) {
|
|
63
|
+
const script = 'for d in /cache/work/* /cache/work/.[!.]*; do [ -e "$d" ] || continue; for k in "$@"; do [ "$d" = "$k" ] && continue 2; done; rm -rf -- "$d"; done';
|
|
64
|
+
await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", script, "sh", ...keep], { timeoutMs: 120000 });
|
|
65
|
+
},
|
|
59
66
|
/** Removes files the root-owned lane container wrote into a bind mount, using the lane image itself. */
|
|
60
67
|
async wipe(dir, image) { await docker(["run", "--rm", "--network", "none", "-v", `${dir}:/d`, "--entrypoint", "sh", image, "-c", "rm -rf /d/* /d/.[!.]* 2>/dev/null; true"], { timeoutMs: 120000 }); },
|
|
61
68
|
};
|
package/bin/pool/lane-tools.mjs
CHANGED
|
@@ -15,6 +15,7 @@ const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-
|
|
|
15
15
|
export const RECIPES = {
|
|
16
16
|
"postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
|
|
17
17
|
python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
|
|
18
|
+
xvfb: { versioned: false, steps: () => [apt("xvfb xauth")] }, // headless X for browser/GUI tests that call xvfb-run
|
|
18
19
|
playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
|
|
19
20
|
// Example of a release-tarball tool; the version is required.
|
|
20
21
|
promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
|
package/bin/pool/router.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { execFile, spawn } from "node:child_process";
|
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
11
|
+
import { createCiEvents, MAX_WAIT_S } from "./ci-events.mjs";
|
|
11
12
|
import { jsonStore } from "./store.mjs";
|
|
12
13
|
import { versionOf } from "./version.mjs";
|
|
13
14
|
|
|
@@ -29,6 +30,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
29
30
|
const store = jsonStore(join(cfg.state_dir, "router-state.json"), { agents: {}, sandboxes: {} });
|
|
30
31
|
const agents = () => store.data.agents;
|
|
31
32
|
const sbx = () => store.data.sandboxes;
|
|
33
|
+
// #5688: CI runner events (POST by a `ci` token or the fd token, GET long-poll by the fd token); state in <state_dir>/ci-events/.
|
|
34
|
+
const ciEvents = createCiEvents({ dir: join(cfg.state_dir, "ci-events"), now });
|
|
35
|
+
const ciOk = (req) => bearerOk(req, cfg.forgedock_token) || (cfg.ci_tokens ?? []).some((t) => bearerOk(req, t));
|
|
36
|
+
const ciQuery = (url) => {
|
|
37
|
+
const repo = url.searchParams.get("repo"), sha = url.searchParams.get("sha"), pr = url.searchParams.get("pr");
|
|
38
|
+
if (!repo || (!sha && !pr)) return { status: 400, body: { error: "repo and one of sha or pr are required" } };
|
|
39
|
+
if (pr && !/^\d{1,9}$/.test(pr)) return { status: 400, body: { error: "pr must be an integer" } };
|
|
40
|
+
const since = Number(url.searchParams.get("since") ?? 0), waitS = Number(url.searchParams.get("wait") ?? 0);
|
|
41
|
+
if (!Number.isInteger(since) || since < 0 || !Number.isFinite(waitS) || waitS < 0 || waitS > MAX_WAIT_S) return { status: 400, body: { error: `since must be a non-negative integer and wait 0-${MAX_WAIT_S}` } };
|
|
42
|
+
return { q: { repo, ...(sha ? { sha } : {}), ...(pr ? { pr: Number(pr) } : {}) }, since, waitS };
|
|
43
|
+
};
|
|
32
44
|
const lane = { cpus: cfg.lane?.cpus ?? 2, mem_gb: cfg.lane?.mem_gb ?? 3 };
|
|
33
45
|
const abandonMs = (cfg.abandon_after_s ?? 1800) * 1000;
|
|
34
46
|
const codes = () => (store.data.codes ??= {});
|
|
@@ -354,6 +366,11 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
354
366
|
return { status: r.status, body: r.data };
|
|
355
367
|
})],
|
|
356
368
|
[route("GET", "/version"), fd(async () => ({ status: 200, body: versionOf(cfg.repo_root) }))],
|
|
369
|
+
[route("POST", "/ci/events"), { fn: async (_p, body) => ({ status: 202, body: ciEvents.ingest(body) }), auth: "ci" }], // #5688
|
|
370
|
+
[route("GET", "/ci/events"), fd(async (_p, _b, url) => {
|
|
371
|
+
const c = ciQuery(url);
|
|
372
|
+
return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
|
|
373
|
+
})],
|
|
357
374
|
[route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
|
|
358
375
|
[route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
|
|
359
376
|
[route("GET", "/bootstrap/bundle.tar.gz"), { fn: async () => ({ bundle: true }), auth: "enroll" }],
|
|
@@ -374,6 +391,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
374
391
|
const p = match(req, url);
|
|
375
392
|
if (!p) continue;
|
|
376
393
|
if (r.auth === "forgedock" && !bearerOk(req, cfg.forgedock_token)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
|
|
394
|
+
if (r.auth === "ci" && !ciOk(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
|
|
377
395
|
if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
|
|
378
396
|
if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
|
|
379
397
|
const body = req.method === "POST" ? await readJson(req) : null;
|
package/bin/pool/warm.mjs
CHANGED
|
@@ -23,7 +23,7 @@ export function makeWarm({ store, sb, own, now, launch, destroy, view, log = con
|
|
|
23
23
|
function configure({ spec, cpus, mem_gb, limit = null, n }) {
|
|
24
24
|
const key = keyOf(spec), want = Math.min(MAX_WARM, Number.isInteger(n) ? n : 0);
|
|
25
25
|
if (want <= 0) { delete wanted()[key]; store.save(); return { key, n: 0 }; }
|
|
26
|
-
wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}) } };
|
|
26
|
+
wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}), ...(spec.env_snapshots?.enabled ? { env_snapshots: spec.env_snapshots } : {}) } };
|
|
27
27
|
store.save();
|
|
28
28
|
return { key, n: want };
|
|
29
29
|
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5692: `forgedock stats --ci-awareness`. Per lane (one RUN_START slice of a run log): time from the failing step's
|
|
5
|
+
* completion (CI_AWARE `event_ts`) to the lane's awareness (`aware_ts`), CI fix rounds per PR and wall time per round
|
|
6
|
+
* (CI_FIX_ROUND to the next round, or to RUN_TERMINAL for the last). Grouped by engine version, so the lanes before and
|
|
7
|
+
* after the event-driven wait are separate rows. Local run logs only; no network, no model.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { runsDir } from "./local-source.mjs";
|
|
12
|
+
|
|
13
|
+
const ms = (t) => { const v = Date.parse(t ?? ""); return Number.isFinite(v) ? v : null; };
|
|
14
|
+
const quant = (xs, q) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)]; };
|
|
15
|
+
const round1 = (x) => (x == null ? null : Math.round(x * 10) / 10);
|
|
16
|
+
const dist = (xs) => ({ n: xs.length, median: round1(quant(xs, 0.5)), p90: round1(quant(xs, 0.9)) });
|
|
17
|
+
|
|
18
|
+
/** Lanes of one parsed log: [{version, awareness_s: [], rounds: {pr: n}, round_wall_s: []}]. */
|
|
19
|
+
export function lanesOf(events) {
|
|
20
|
+
const lanes = [];
|
|
21
|
+
let cur = null;
|
|
22
|
+
const closeRound = (endTs) => { if (cur?.openRound != null && endTs != null) cur.round_wall_s.push((endTs - cur.openRound) / 1000); if (cur) cur.openRound = null; };
|
|
23
|
+
for (const e of events) {
|
|
24
|
+
const t = ms(e.ts);
|
|
25
|
+
if (e.event === "RUN_START") { closeRound(null); cur = { version: e.version ?? null, start: t, awareness_s: [], rounds: {}, round_wall_s: [], openRound: null }; lanes.push(cur); continue; }
|
|
26
|
+
if (!cur) continue;
|
|
27
|
+
if (e.event === "CI_AWARE") { const a = ms(e.aware_ts) ?? t, b = ms(e.event_ts); if (a != null && b != null && a >= b) cur.awareness_s.push((a - b) / 1000); }
|
|
28
|
+
else if (e.event === "CI_FIX_ROUND") { closeRound(t); const k = String(e.pr ?? "?"); cur.rounds[k] = (cur.rounds[k] ?? 0) + 1; cur.openRound = t; }
|
|
29
|
+
else if (e.event === "RUN_TERMINAL") closeRound(t);
|
|
30
|
+
}
|
|
31
|
+
return lanes.filter((l) => l.awareness_s.length || Object.keys(l.rounds).length || true);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Report over parsed logs `[{events}]`: per version, awareness latency (median/p90), rounds per PR and wall per round.
|
|
36
|
+
* `sinceMs` keeps only the lanes whose RUN_START is at or after it (`--since <date>`); a lane with no start time is dropped then.
|
|
37
|
+
*/
|
|
38
|
+
export function ciAwarenessReport(logs, { sinceMs = null } = {}) {
|
|
39
|
+
const by = new Map();
|
|
40
|
+
for (const lg of logs) for (const l of lanesOf(lg)) {
|
|
41
|
+
if (sinceMs != null && !(l.start >= sinceMs)) continue;
|
|
42
|
+
const g = by.get(l.version ?? "unknown") ?? { version: l.version ?? "unknown", lanes: 0, awareness_s: [], rounds_per_pr: [], round_wall_s: [] };
|
|
43
|
+
g.lanes++; g.awareness_s.push(...l.awareness_s); g.round_wall_s.push(...l.round_wall_s);
|
|
44
|
+
g.rounds_per_pr.push(...Object.values(l.rounds));
|
|
45
|
+
by.set(g.version, g);
|
|
46
|
+
}
|
|
47
|
+
const versions = [...by.values()].sort((a, b) => String(a.version).localeCompare(String(b.version), undefined, { numeric: true }))
|
|
48
|
+
.map((g) => ({ version: g.version, lanes: g.lanes, awareness_s: dist(g.awareness_s), rounds_per_pr: { ...dist(g.rounds_per_pr), mean: g.rounds_per_pr.length ? round1(g.rounds_per_pr.reduce((a, b) => a + b, 0) / g.rounds_per_pr.length) : null }, round_wall_s: dist(g.round_wall_s), event_driven: g.awareness_s.length > 0 }));
|
|
49
|
+
const all = [...by.values()], aw = all.flatMap((g) => g.awareness_s), rp = all.flatMap((g) => g.rounds_per_pr), rw = all.flatMap((g) => g.round_wall_s);
|
|
50
|
+
return { total: { lanes: all.reduce((n, g) => n + g.lanes, 0), awareness_s: dist(aw), rounds_per_pr: { ...dist(rp), mean: rp.length ? round1(rp.reduce((a, b) => a + b, 0) / rp.length) : null }, round_wall_s: dist(rw) }, versions };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Parse the `*.jsonl` run logs of `dir` (optionally only this repo's `<owner>__<repo>__<issue>.jsonl`); unreadable files are skipped. */
|
|
54
|
+
export function readCiLogs(dir = runsDir(), repo = null) {
|
|
55
|
+
if (!existsSync(dir)) return [];
|
|
56
|
+
const slug = repo ? `${repo.replace("/", "__")}__` : null;
|
|
57
|
+
return readdirSync(dir).sort().filter((f) => f.endsWith(".jsonl") && (!slug || f.startsWith(slug))).flatMap((f) => {
|
|
58
|
+
try { return [readFileSync(join(dir, f), "utf8").split("\n").flatMap((l) => { try { return l.trim() ? [JSON.parse(l)] : []; } catch { return []; } })]; } catch { return []; }
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const fmt = (d, u = "s") => (d.n ? `median ${d.median}${u}, p90 ${d.p90}${u} (n=${d.n})` : "no data");
|
|
63
|
+
export function renderCiAwareness(r) {
|
|
64
|
+
const row = (x, label) => [`${label}${x.lanes != null ? ` (${x.lanes} lanes)` : ""}`, ` awareness latency: ${fmt(x.awareness_s)}`, ` CI rounds per PR: ${x.rounds_per_pr.n ? `median ${x.rounds_per_pr.median}, mean ${x.rounds_per_pr.mean}, p90 ${x.rounds_per_pr.p90} (n=${x.rounds_per_pr.n})` : "no data"}`, ` wall per round: ${fmt(x.round_wall_s)}`].join("\n");
|
|
65
|
+
return ["CI awareness (#5692)", row(r.total, "all"), ...r.versions.map((v) => row(v, `version ${v.version}${v.event_driven ? " [event-driven]" : ""}`))].join("\n");
|
|
66
|
+
}
|