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.
Files changed (78) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/conformance.mjs +7 -1
  21. package/bin/lean/conformance.test.mjs +7 -1
  22. package/bin/lean/depcache.mjs +38 -8
  23. package/bin/lean/deploy-stages.mjs +514 -0
  24. package/bin/lean/deploy-stages.test.mjs +580 -0
  25. package/bin/lean/effects.mjs +50 -0
  26. package/bin/lean/execution.mjs +8 -1
  27. package/bin/lean/lean.mjs +61 -12
  28. package/bin/lean/lean.test.mjs +87 -0
  29. package/bin/lean/preflight.mjs +62 -1
  30. package/bin/lean/preflight.test.mjs +30 -1
  31. package/bin/lean/release-deploy.mjs +12 -6
  32. package/bin/lean/release-flakes.mjs +16 -0
  33. package/bin/lean/release-flakes.test.mjs +15 -0
  34. package/bin/lean/release-gates.mjs +24 -1
  35. package/bin/lean/release-ledger.mjs +21 -0
  36. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  37. package/bin/lean/release-minutes.mjs +98 -0
  38. package/bin/lean/release-promote.mjs +444 -0
  39. package/bin/lean/release-promote.test.mjs +470 -0
  40. package/bin/lean/release-rollback.mjs +14 -6
  41. package/bin/lean/release.mjs +31 -2
  42. package/bin/lean/sandbox-remote.mjs +11 -3
  43. package/bin/lean/testengine-recall.mjs +82 -0
  44. package/bin/lean/testengine-recall.test.mjs +103 -0
  45. package/bin/lean/testengine-shard.mjs +150 -0
  46. package/bin/lean/testengine-shard.test.mjs +111 -0
  47. package/bin/lean/testengine.mjs +486 -0
  48. package/bin/lean/testengine.test.mjs +303 -0
  49. package/bin/lean/validate-catalog.mjs +16 -0
  50. package/bin/lean/validate-catalog.test.mjs +14 -1
  51. package/bin/lean/verify-settle.test.mjs +156 -0
  52. package/bin/lean/verify.mjs +98 -3
  53. package/bin/pool/agent.mjs +65 -6
  54. package/bin/pool/ci-events.mjs +183 -0
  55. package/bin/pool/ci-events.test.mjs +143 -0
  56. package/bin/pool/docker.mjs +7 -0
  57. package/bin/pool/lane-tools.mjs +32 -0
  58. package/bin/pool/router.mjs +21 -1
  59. package/bin/pool/warm.mjs +14 -3
  60. package/bin/stats/ci-awareness.mjs +66 -0
  61. package/bin/stats/index.mjs +44 -3
  62. package/bin/stats/release-ledger.test.mjs +226 -0
  63. package/bin/stats/release.mjs +365 -1
  64. package/bin/stats/stats.test.mjs +36 -0
  65. package/docs/CI.md +31 -0
  66. package/docs/CONFIG.md +235 -2
  67. package/docs/ENV-LIBRARY.md +172 -0
  68. package/docs/STATS.md +43 -0
  69. package/docs/ci-events.md +88 -0
  70. package/docs/test-engine.md +98 -0
  71. package/package.json +1 -1
  72. package/pool/README.md +1 -0
  73. package/pool/image/entrypoint.sh +15 -3
  74. package/pool/services/docker-compose.yml +53 -0
  75. package/pool/services/git-mirror.sh +22 -0
  76. package/scripts/acceptance-red-green.sh +5 -2
  77. package/scripts/acceptance-red-green.test.sh +11 -0
  78. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,147 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { classifyCiFailure, failFastDecision, failFastPolicy, DOWNSTREAM_CLASSES } from "./ci-classify.mjs";
6
+ import { signatureHash } from "./release-flakes.mjs";
7
+
8
+ const S = "deterministic-setup", G = "generated-artifact-stale", I = "infra", F = "flaky-suspect", C = "code";
9
+ const step = (want, eco, ...lines) => ({ want, eco, step: "build", lines });
10
+ const tst = (want, eco, message, ...lines) => ({ want, eco, step: "unit", lines, test: { id: "t1", message } });
11
+ /** A would-be `code` failure that is in the ledger: the entry carries the `flakes` that make it flaky-suspect. */
12
+ const flaky = (eco, c) => ({ ...c, want: "flaky-suspect", eco, flakes: [{ signature_hash: signatureHash(c.step, c.test?.id ?? null, classifyCiFailure(c).signature) }] });
13
+
14
+ /** Real-shaped excerpts: node, python, go, docker. */
15
+ export const CORPUS = [
16
+ // deterministic-setup
17
+ step(S, "node", "sh: 1: tsc: command not found", "npm ERR! code ELIFECYCLE"),
18
+ step(S, "node", "/home/runner/work/_temp/abc.sh: line 2: pnpm: command not found"),
19
+ step(S, "go", "exec: \"golangci-lint\": executable file not found in $PATH"),
20
+ step(S, "node", "npm ERR! code ERESOLVE", "npm ERR! ERESOLVE could not resolve", "npm ERR! Found: react@18.2.0"),
21
+ step(S, "node", "ERR_PNPM_OUTDATED_LOCKFILE Cannot install with \"frozen-lockfile\" because pnpm-lock.yaml is not up to date with package.json"),
22
+ step(S, "node", "npm ERR! `npm ci` can only install packages when your package.json and package-lock.json are in sync."),
23
+ step(S, "python", "ERROR: No matching distribution found for private-lib==2.0", "ERROR: Could not find a version that satisfies the requirement private-lib==2.0"),
24
+ step(S, "python", "error: poetry.lock is not up to date with pyproject.toml"),
25
+ step(S, "go", "go: updates to go.mod needed; to update it:", "\tgo mod tidy"),
26
+ step(S, "docker", "Error response from daemon: manifest for ghcr.io/org/base:v9 not found: manifest unknown: manifest unknown"),
27
+ step(S, "docker", "docker: Error response from daemon: pull access denied for acme/builder, repository does not exist or may require 'docker login'"),
28
+ step(S, "node", "npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/foo'"),
29
+ step(S, "node", "ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/@acme%2fprivate: Not Found - 404"),
30
+ step(S, "python", "bash: uv: command not found"),
31
+ // generated-artifact-stale
32
+ step(G, "node", "error: generated files are out of date", "run `pnpm codegen` and commit the result"),
33
+ step(G, "node", "The OpenAPI client is out of date. Run `make gen-client` to regenerate."),
34
+ step(G, "node", "git diff --exit-code failed: working tree is not clean after running generate", " M src/schema.ts"),
35
+ step(G, "node", "Schema drift detected between prisma/schema.prisma and the database snapshot"),
36
+ step(G, "node", "types.d.ts is stale; please run `npm run build:types` and commit"),
37
+ step(G, "python", "check-generated: FAIL files differ from committed", "requirements.txt is generated by `uv pip compile`"),
38
+ step(G, "go", "protobuf bindings out of date, run `buf generate`", "pkg/api/v1/api.pb.go"),
39
+ // infra
40
+ step(I, "node", "Error: Unable to upload artifact: storage quota"),
41
+ step(I, "node", "The runner has received a shutdown signal."),
42
+ step(I, "node", "FATAL: database system is starting up"),
43
+ step(I, "node", "npm ERR! network request failed: ETIMEDOUT"),
44
+ step(I, "python", "curl: (6) Could not resolve host: files.pythonhosted.org"),
45
+ step(I, "node", "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 503 Service Unavailable"),
46
+ tst(I, "node", "connect ECONNRESET 10.0.0.3:443"),
47
+ // code
48
+ tst(C, "node", "AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 1 !== 2", "not ok 4 - adds"),
49
+ tst(C, "node", "Error: Cannot find module './util' imported from src/app.ts"),
50
+ tst(C, "python", "E assert 3 == 4", "FAILED tests/test_calc.py::test_add - assert 3 == 4"),
51
+ tst(C, "python", "E ModuleNotFoundError: No module named 'app.helpers'"),
52
+ tst(C, "go", "--- FAIL: TestParse (0.00s)", " parse_test.go:21: got 3, want 4"),
53
+ tst(C, "node", "expect(received).toBe(expected) // Object.is equality: Expected: 5 Received: 4"),
54
+ step(C, "node", "src/index.ts(12,5): error TS2322: Type 'string' is not assignable to type 'number'."),
55
+ step(C, "node", "/src/a.js\n 3:7 error 'x' is assigned a value but never used no-unused-vars", "✖ 1 problem (1 error, 0 warnings)"),
56
+ step(C, "python", "mypy: pkg/mod.py:9: error: Incompatible return value type (got \"str\", expected \"int\")"),
57
+ step(C, "go", "./main.go:14:2: undefined: Frobnicate", "FAIL\texample.com/m [build failed]"),
58
+ step(C, "python", "ruff: F401 `os` imported but unused"),
59
+ tst(C, "go", "panic: runtime error: index out of range [3] with length 3"),
60
+ step(C, "docker", "Dockerfile:12 RUN make test failed: test_widget: expected 3 got 4"),
61
+ step(C, "node", "error[E0308]: mismatched types", " --> src/lib.rs:4:5"),
62
+ // flaky-suspect (ledger hit over a code failure)
63
+ flaky("node", tst(C, "node", "Error: timeout of 5000ms exceeded. Ensure the done() callback is being called", "not ok 9 - polls")),
64
+ flaky("python", tst(C, "python", "E assert 1 == 2 # retried twice", "FAILED tests/test_sync.py::test_poll")),
65
+ flaky("go", tst(C, "go", "--- FAIL: TestWatch (5.01s)", " watch_test.go:44: timed out waiting for event")),
66
+ flaky("docker", step(C, "docker", "Dockerfile:8 RUN make integ failed: test_ready: expected up got starting")),
67
+ flaky("node", step(C, "node", "src/e2e/login.spec.ts: error: locator.click: Target closed")),
68
+ flaky("python", step(C, "python", "pkg/worker.py:31: error: assertion failed: queue drained")),
69
+ ];
70
+
71
+ describe("classifyCiFailure corpus (#5690)", () => {
72
+ it("accuracy >= 90% overall, 100% setup precision, >= 5 per class and >= 40 excerpts", () => {
73
+ const rows = {}; const got = (c) => classifyCiFailure(c).class;
74
+ let ok = 0, setupFalse = 0;
75
+ for (const c of CORPUS) {
76
+ const got = classifyCiFailure(c).class;
77
+ const r = (rows[c.want] ??= { n: 0, ok: 0 });
78
+ r.n++;
79
+ if (got === c.want) { r.ok++; ok++; }
80
+ if (got === S && c.want !== S) setupFalse++;
81
+ }
82
+ const table = Object.entries(rows).map(([cls, r]) => ({ class: cls, total: r.n, correct: r.ok, pct: `${Math.round((100 * r.ok) / r.n)}%` }));
83
+ table.push({ class: "ALL", total: CORPUS.length, correct: ok, pct: `${Math.round((100 * ok) / CORPUS.length)}%` });
84
+ console.table(table);
85
+ assert.ok(CORPUS.length >= 40);
86
+ for (const cls of [S, G, I, F, C]) assert.ok(rows[cls].n >= 5, cls);
87
+ const ecos = (cls) => new Set(CORPUS.filter((c) => c.want === cls).map((c) => c.eco));
88
+ for (const cls of [S, G, I, F, C]) assert.ok(ecos(cls).size >= 2, `${cls} spans one ecosystem`);
89
+ assert.deepEqual([...new Set(CORPUS.map((c) => c.eco))].sort(), ["docker", "go", "node", "python"]);
90
+ assert.ok(ok / CORPUS.length >= 0.9, `accuracy ${ok}/${CORPUS.length}`);
91
+ assert.equal(setupFalse, 0, "a non-setup failure was classed as setup");
92
+ assert.equal(rows[C].ok, rows[C].n, "no code failure may be misclassed");
93
+ });
94
+
95
+ it("downstream is true for setup and stale only", () => {
96
+ assert.equal(classifyCiFailure(CORPUS[0]).downstream, true);
97
+ assert.equal(classifyCiFailure(CORPUS.find((c) => c.want === G)).downstream, true);
98
+ assert.equal(classifyCiFailure(CORPUS.find((c) => c.want === I)).downstream, false);
99
+ assert.equal(classifyCiFailure(CORPUS.find((c) => c.want === C)).downstream, false);
100
+ });
101
+
102
+ it("a test failure is never setup or stale, even with setup-looking output", () => {
103
+ assert.equal(classifyCiFailure({ step: "unit", lines: ["sh: foo: command not found"], test: { id: "t" } }).class, C);
104
+ });
105
+
106
+ it("handles empty input", () => {
107
+ assert.equal(classifyCiFailure().class, C);
108
+ assert.equal(classifyCiFailure({ lines: [] }).downstream, false);
109
+ });
110
+ });
111
+
112
+ describe("flake ledger override (#5690)", () => {
113
+ const base = { step: "unit", lines: ["boom at line 12"], test: { id: "t9", message: "Error: timed out after 5000ms" } };
114
+ const plain = classifyCiFailure(base);
115
+ it("a ledger hit turns code into flaky-suspect", () => {
116
+ assert.equal(plain.class, C);
117
+ const flakes = [{ signature_hash: signatureHash("unit", "t9", plain.signature) }];
118
+ const r = classifyCiFailure({ ...base, flakes });
119
+ assert.deepEqual([r.class, r.downstream], ["flaky-suspect", false]);
120
+ });
121
+ it("a miss stays code; the hit does not override setup or infra", () => {
122
+ assert.equal(classifyCiFailure({ ...base, flakes: [{ signature_hash: "nope" }] }).class, C);
123
+ const setup = { step: "build", lines: ["sh: tsc: command not found"] };
124
+ const sig = classifyCiFailure(setup).signature;
125
+ assert.equal(classifyCiFailure({ ...setup, flakes: [{ signature_hash: signatureHash("build", null, sig) }] }).class, S);
126
+ });
127
+ });
128
+
129
+ describe("failFastDecision (#5690)", () => {
130
+ const cases = [["deterministic-setup", true], ["generated-artifact-stale", true], ["infra", false], ["flaky-suspect", false], ["code", false]];
131
+ it("cancel only for downstream classes under policy deterministic", () => {
132
+ for (const [cls, down] of cases) {
133
+ const e = { type: "step_failed", class: cls };
134
+ assert.equal(failFastDecision(e, { fail_fast: "deterministic" }).action, down ? "cancel" : "continue", cls);
135
+ assert.equal(failFastDecision(e, { fail_fast: "off" }).action, "continue", cls);
136
+ assert.equal(failFastDecision(e, undefined).action, "continue", cls);
137
+ assert.equal(failFastDecision(e, {}).action, "continue", cls);
138
+ }
139
+ assert.deepEqual(DOWNSTREAM_CLASSES, [S, G]);
140
+ });
141
+ it("classifies an event with no class; unknown policy values are off", () => {
142
+ const e = { type: "step_failed", step: "s", lines: ["sh: x: command not found"] };
143
+ assert.equal(failFastDecision(e, "deterministic").action, "cancel");
144
+ assert.equal(failFastPolicy("always"), "off");
145
+ assert.equal(failFastDecision({ type: "job_started" }, "deterministic").action, "continue");
146
+ });
147
+ });
@@ -0,0 +1,175 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Runner-side CI event emitter (#5689, parent #5687): `forgedock ci-step --name <step> -- <cmd...>` and
5
+ * `forgedock ci-hook job-started|job-completed`. Events go to the router's POST /ci/events (#5688).
6
+ * - Delivery is best effort: a failed POST logs one warning line, stops further posts and never changes the exit code.
7
+ * - Config: FORGEDOCK_CI_EVENTS_URL (fallback FORGE_CI_EVENTS_URL, as ci-preflight.mjs) + FORGEDOCK_CI_TOKEN (bearer). Unset URL: no posts.
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ import { constants as osConstants } from "node:os";
11
+ import { StringDecoder } from "node:string_decoder";
12
+
13
+ export const POST_TIMEOUT_MS = 1000, DRAIN_MS = 1500, MAX_LINES = 40, MAX_LINE_CHARS = 500, MAX_MESSAGE_CHARS = 2000;
14
+ const ERROR_RE = /error|fail|traceback|assert/i;
15
+ // eslint-disable-next-line no-control-regex
16
+ const ANSI_RE = /\u001b\[[0-9;]*[A-Za-z]/g;
17
+ const clip = (s, n) => (s.length > n ? s.slice(0, n) : s);
18
+ const nonEmpty = (v) => (typeof v === "string" && v.trim() ? v.trim() : "");
19
+
20
+ /** Base event fields from the GitHub Actions env; the router requires repo, sha, run_id, job and ts. */
21
+ export function baseEvent(env = process.env, now = () => new Date()) {
22
+ const ev = {
23
+ repo: nonEmpty(env.GITHUB_REPOSITORY) || "unknown",
24
+ sha: nonEmpty(env.GITHUB_SHA) || "unknown",
25
+ run_id: nonEmpty(env.GITHUB_RUN_ID) || "unknown",
26
+ job: nonEmpty(env.GITHUB_JOB) || "unknown",
27
+ ts: now().toISOString(),
28
+ };
29
+ const m = /^refs\/pull\/(\d{1,9})\//.exec(nonEmpty(env.GITHUB_REF));
30
+ if (m) ev.pr = Number(m[1]);
31
+ return ev;
32
+ }
33
+
34
+ /** Fire-and-forget poster. `post` never throws; `drain` waits for in-flight posts for at most DRAIN_MS. */
35
+ export function createPoster({ env = process.env, fetchImpl = globalThis.fetch, warn = (l) => process.stderr.write(`${l}\n`), now = () => new Date() } = {}) {
36
+ const url = nonEmpty(env.FORGEDOCK_CI_EVENTS_URL) || nonEmpty(env.FORGE_CI_EVENTS_URL);
37
+ const token = nonEmpty(env.FORGEDOCK_CI_TOKEN);
38
+ const pending = new Set();
39
+ let broken = false;
40
+ const fail = (why) => {
41
+ if (broken) return;
42
+ broken = true;
43
+ warn(`forgedock ci-emit: event delivery failed (${why}); continuing without events`);
44
+ };
45
+ return {
46
+ enabled: Boolean(url) && typeof fetchImpl === "function",
47
+ post(type, fields = {}) {
48
+ if (!url || typeof fetchImpl !== "function" || broken) return;
49
+ const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
50
+ const body = JSON.stringify({ type, ...baseEvent(env, now), ...fields });
51
+ const p = Promise.resolve()
52
+ .then(() => fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.timeout(POST_TIMEOUT_MS) }))
53
+ .then((res) => { if (!res || res.status >= 300) fail(`HTTP ${res ? res.status : "no response"}`); })
54
+ .catch((err) => fail(err?.name === "TimeoutError" ? "timeout" : (err?.cause?.code ?? err?.message ?? "error")))
55
+ .finally(() => pending.delete(p));
56
+ pending.add(p);
57
+ },
58
+ async drain() {
59
+ if (!pending.size) return;
60
+ let timer;
61
+ await Promise.race([Promise.allSettled([...pending]), new Promise((r) => { timer = setTimeout(r, DRAIN_MS); })]);
62
+ clearTimeout(timer);
63
+ if (pending.size) fail("timeout");
64
+ },
65
+ };
66
+ }
67
+
68
+ /** Streaming parser for pytest (-rA) and vitest/jest default-reporter lines; `onFail({id,file,line,message})` fires as soon as a test is known. */
69
+ export function createTestParser(onFail) {
70
+ const seen = new Set();
71
+ const loc = new Map(); // pytest: file -> {line, message} from `path:line: Error` lines
72
+ let pend = null; // vitest: FAIL seen, waiting for its `❯ file:line`
73
+ const emit = (t) => {
74
+ if (seen.has(t.id)) return;
75
+ seen.add(t.id);
76
+ const test = { id: clip(t.id, 500) };
77
+ if (t.file) test.file = clip(t.file, 500);
78
+ if (Number.isInteger(t.line)) test.line = t.line;
79
+ if (t.message) test.message = clip(t.message, MAX_MESSAGE_CHARS);
80
+ onFail(test);
81
+ };
82
+ const flush = () => { if (pend) { emit(pend); pend = null; } };
83
+ return {
84
+ line(raw) {
85
+ const s = raw.replace(ANSI_RE, "").replace(/\r$/, "");
86
+ let m = /^FAILED\s+(\S+?)::(\S+)(?:\s+-\s+(.*))?$/.exec(s.trim());
87
+ if (m) {
88
+ const l = loc.get(m[1]);
89
+ emit({ id: `${m[1]}::${m[2]}`, file: m[1], line: l?.line, message: m[3] || l?.message });
90
+ return;
91
+ }
92
+ m = /^(\S+\.[A-Za-z]+):(\d+):\s+(\S*(?:Error|Exception|Failed)\S*)\s*(.*)$/.exec(s.trim());
93
+ if (m) { loc.set(m[1], { line: Number(m[2]), message: `${m[3]} ${m[4]}`.trim() }); return; }
94
+ m = /^\s*(?:FAIL|×)\s+(?:\[[^\]]*\]\s+)?(\S+)\s+>\s+(.+?)(?:\s+\d+ms)?\s*$/.exec(s);
95
+ if (m) { flush(); pend = { id: `${m[1]} > ${m[2]}`, file: m[1] }; return; }
96
+ if (!pend) return;
97
+ m = /^\s*❯\s+(\S+?):(\d+)(?::\d+)?\s*$/.exec(s);
98
+ if (m && (m[1] === pend.file || m[1].endsWith(pend.file) || pend.file.endsWith(m[1]))) { pend.line = Number(m[2]); flush(); return; }
99
+ if (!pend.message && /(Error|expected)/.test(s) && !s.includes("❯")) pend.message = s.trim();
100
+ },
101
+ end() { flush(); },
102
+ };
103
+ }
104
+
105
+ /** Keeps the first MAX_LINES error-looking lines, else the last MAX_LINES lines. */
106
+ function createLineKeeper() {
107
+ const errs = [], tail = [];
108
+ return {
109
+ add(line) {
110
+ const l = clip(line.replace(ANSI_RE, ""), MAX_LINE_CHARS);
111
+ if (errs.length < MAX_LINES && ERROR_RE.test(l)) errs.push(l);
112
+ tail.push(l);
113
+ if (tail.length > MAX_LINES) tail.shift();
114
+ },
115
+ result() { return errs.length ? errs : tail; },
116
+ };
117
+ }
118
+
119
+ function lineSplitter(onLine) {
120
+ const dec = new StringDecoder("utf8");
121
+ let buf = "";
122
+ const take = (text) => {
123
+ buf += text;
124
+ let i;
125
+ while ((i = buf.indexOf("\n")) >= 0) { onLine(buf.slice(0, i)); buf = buf.slice(i + 1); }
126
+ };
127
+ return { write: (chunk) => take(dec.write(chunk)), end() { take(dec.end()); if (buf) { onLine(buf); buf = ""; } } };
128
+ }
129
+
130
+ export const CI_STEP_USAGE = "usage: forgedock ci-step --name <step> -- <cmd...>";
131
+
132
+ /** `forgedock ci-step`; @returns the wrapped command's exit code (128+signal when killed). `deps`: {env, fetchImpl, stdout, stderr, warn, now, spawnImpl}. */
133
+ export async function ciStepFromCli(argv, deps = {}) {
134
+ const env = deps.env ?? process.env, stdout = deps.stdout ?? process.stdout, stderr = deps.stderr ?? process.stderr;
135
+ const sep = argv.indexOf("--");
136
+ const head = sep < 0 ? argv : argv.slice(0, sep), cmd = sep < 0 ? [] : argv.slice(sep + 1);
137
+ const ni = head.indexOf("--name");
138
+ const name = ni >= 0 ? nonEmpty(head[ni + 1]) : "";
139
+ if (!name || !cmd.length) { stderr.write(`${CI_STEP_USAGE}\n`); return 2; }
140
+
141
+ const poster = createPoster({ env, fetchImpl: deps.fetchImpl, warn: deps.warn ?? ((l) => stderr.write(`${l}\n`)), now: deps.now });
142
+ const keeper = createLineKeeper();
143
+ const parser = createTestParser((test) => poster.post("test_failed", { step: name, test }));
144
+ const feed = (line) => { keeper.add(line); parser.line(line); };
145
+ const split = { out: lineSplitter(feed), err: lineSplitter(feed) };
146
+
147
+ poster.post("step_started", { step: name });
148
+ const code = await new Promise((resolve) => {
149
+ let child;
150
+ try { child = (deps.spawnImpl ?? spawn)(cmd[0], cmd.slice(1), { stdio: ["inherit", "pipe", "pipe"], env }); } catch (err) { stderr.write(`ci-step: cannot run ${cmd[0]}: ${err.message}\n`); resolve(127); return; }
151
+ child.stdout.on("data", (c) => { stdout.write(c); split.out.write(c); });
152
+ child.stderr.on("data", (c) => { stderr.write(c); split.err.write(c); });
153
+ child.on("error", (err) => { stderr.write(`ci-step: cannot run ${cmd[0]}: ${err.message}\n`); resolve(err.code === "ENOENT" ? 127 : 126); });
154
+ child.on("close", (c, sig) => resolve(sig ? 128 + (osConstants.signals[sig] ?? 0) : (c ?? 1)));
155
+ });
156
+ split.out.end(); split.err.end(); parser.end();
157
+ if (code !== 0) poster.post("step_failed", { step: name, exit_code: code, lines: keeper.result() });
158
+ await poster.drain();
159
+ return code;
160
+ }
161
+
162
+ const HOOKS = { "job-started": "job_started", "job-completed": "job_finished" };
163
+ export const CI_HOOK_USAGE = "usage: forgedock ci-hook job-started|job-completed";
164
+
165
+ /** `forgedock ci-hook`; always @returns 0 (a runner hook must never fail the job) except for a usage error. */
166
+ export async function ciHookFromCli(argv, deps = {}) {
167
+ const env = deps.env ?? process.env;
168
+ const type = HOOKS[argv[0]];
169
+ if (!type) { (deps.stderr ?? process.stderr).write(`${CI_HOOK_USAGE}\n`); return 2; }
170
+ const poster = createPoster({ env, fetchImpl: deps.fetchImpl, warn: deps.warn, now: deps.now });
171
+ if (!poster.enabled) return 0;
172
+ poster.post(type);
173
+ await poster.drain();
174
+ return 0;
175
+ }
@@ -0,0 +1,177 @@
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 http from "node:http";
6
+ import { spawn } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { createTestParser, createPoster, baseEvent } from "./ci-emit.mjs";
9
+
10
+ const CLI = fileURLToPath(new URL("../forgedock.mjs", import.meta.url));
11
+ const ENV0 = { PATH: process.env.PATH, GITHUB_REPOSITORY: "o/r", GITHUB_SHA: "abc123", GITHUB_RUN_ID: "77", GITHUB_JOB: "unit", GITHUB_REF: "refs/pull/42/merge" };
12
+
13
+ /** Fake router: records {at, body, auth}; `status` controls the reply. */
14
+ async function router(status = 202) {
15
+ const got = [];
16
+ const srv = http.createServer((req, res) => {
17
+ let b = "";
18
+ req.on("data", (c) => (b += c));
19
+ req.on("end", () => { got.push({ at: Date.now(), body: JSON.parse(b), auth: req.headers.authorization }); res.statusCode = status; res.end("{}"); });
20
+ });
21
+ await new Promise((r) => srv.listen(0, "127.0.0.1", r));
22
+ return { got, url: `http://127.0.0.1:${srv.address().port}/ci/events`, close: () => new Promise((r) => srv.close(r)) };
23
+ }
24
+
25
+ /** Runs the real CLI; resolves {code, out(Buffer), err(Buffer), exitAt, wall}. */
26
+ function run(args, env) {
27
+ return new Promise((resolve) => {
28
+ const t0 = Date.now();
29
+ const p = spawn(process.execPath, [CLI, ...args], { env, stdio: ["ignore", "pipe", "pipe"] });
30
+ const out = [], err = [];
31
+ p.stdout.on("data", (c) => out.push(c));
32
+ p.stderr.on("data", (c) => err.push(c));
33
+ p.on("close", (code) => resolve({ code, out: Buffer.concat(out), err: Buffer.concat(err), exitAt: Date.now(), wall: Date.now() - t0 }));
34
+ });
35
+ }
36
+ const node = (src) => [process.execPath, "-e", src];
37
+
38
+ test("ci-step preserves exit code and stdout/stderr bytes (0, 1, 137, binary)", async () => {
39
+ for (const code of [0, 1, 137]) {
40
+ const src = `process.stdout.write(Buffer.from([0,255,254,10,128,0])); process.stderr.write(Buffer.from([1,2,200,201])); process.exit(${code})`;
41
+ const r = await run(["ci-step", "--name", "bin", "--", ...node(src)], ENV0);
42
+ assert.equal(r.code, code);
43
+ assert.deepEqual([...r.out], [0, 255, 254, 10, 128, 0]);
44
+ assert.deepEqual([...r.err], [1, 2, 200, 201]);
45
+ }
46
+ });
47
+
48
+ test("ci-step posts step_started and step_failed with exit code and error lines, with bearer token", async () => {
49
+ const rt = await router();
50
+ const lines = [...Array(60).keys()].map((i) => `noise ${i}`).concat(["Error: boom"]);
51
+ const r = await run(["ci-step", "--name", "build", "--", ...node(`console.log(${JSON.stringify(lines.join("\n"))}); process.exit(2)`)], { ...ENV0, FORGEDOCK_CI_EVENTS_URL: rt.url, FORGEDOCK_CI_TOKEN: "tok" });
52
+ await rt.close();
53
+ assert.equal(r.code, 2);
54
+ const types = rt.got.map((g) => g.body.type).sort();
55
+ assert.deepEqual(types, ["step_failed", "step_started"]);
56
+ const failed = rt.got.find((g) => g.body.type === "step_failed");
57
+ assert.equal(failed.auth, "Bearer tok");
58
+ assert.equal(failed.body.exit_code, 2);
59
+ assert.deepEqual(failed.body.lines, ["Error: boom"]);
60
+ assert.equal(failed.body.step, "build");
61
+ assert.equal(failed.body.pr, 42);
62
+ assert.equal(failed.body.repo, "o/r");
63
+ });
64
+
65
+ test("step_failed without error-looking lines carries the last 40 lines", async () => {
66
+ const rt = await router();
67
+ const src = `for (let i=0;i<100;i++) console.log("line "+i); process.exit(1)`;
68
+ await run(["ci-step", "--name", "s", "--", ...node(src)], { ...ENV0, FORGEDOCK_CI_EVENTS_URL: rt.url });
69
+ await rt.close();
70
+ const failed = rt.got.find((g) => g.body.type === "step_failed");
71
+ assert.equal(failed.body.lines.length, 40);
72
+ assert.equal(failed.body.lines[0], "line 60");
73
+ });
74
+
75
+ const PYTEST = [
76
+ "============ FAILURES ============",
77
+ "___ test_a ___",
78
+ "E assert 1 == 2",
79
+ "tests/test_a.py:12: AssertionError",
80
+ "___ test_b ___",
81
+ "tests/test_b.py:30: AssertionError",
82
+ "=========== short test summary info ===========",
83
+ "FAILED tests/test_a.py::test_a - assert 1 == 2",
84
+ "FAILED tests/test_b.py::TestK::test_b - AssertionError: nope",
85
+ ];
86
+ const VITEST = [
87
+ " FAIL src/a.test.ts > suite > adds",
88
+ "AssertionError: expected 1 to be 2",
89
+ " ❯ src/a.test.ts:9:15",
90
+ " 7| it('adds', () => {",
91
+ " FAIL src/b.test.ts > subtracts",
92
+ "Error: bad",
93
+ " ❯ src/b.test.ts:21:3",
94
+ ];
95
+
96
+ /** Streams `lines` one at a time with a delay, then lingers 600 ms before exiting. */
97
+ const streamer = (lines) => node(`const L=${JSON.stringify(lines)};let i=0;const t=setInterval(()=>{if(i<L.length)console.log(L[i++]);else{clearInterval(t);setTimeout(()=>process.exit(1),600)}},40)`);
98
+
99
+ for (const [name, log, want] of [
100
+ ["pytest", PYTEST, [
101
+ { id: "tests/test_a.py::test_a", file: "tests/test_a.py", line: 12, message: "assert 1 == 2" },
102
+ { id: "tests/test_b.py::TestK::test_b", file: "tests/test_b.py", line: 30, message: "AssertionError: nope" },
103
+ ]],
104
+ ["vitest", VITEST, [
105
+ { id: "src/a.test.ts > suite > adds", file: "src/a.test.ts", line: 9, message: "AssertionError: expected 1 to be 2" },
106
+ { id: "src/b.test.ts > subtracts", file: "src/b.test.ts", line: 21, message: "Error: bad" },
107
+ ]],
108
+ ]) {
109
+ test(`${name} log streams one test_failed per failing test before the process exits`, async () => {
110
+ const rt = await router();
111
+ const r = await run(["ci-step", "--name", name, "--", ...streamer(log)], { ...ENV0, FORGEDOCK_CI_EVENTS_URL: rt.url });
112
+ await rt.close();
113
+ assert.equal(r.code, 1);
114
+ const tf = rt.got.filter((g) => g.body.type === "test_failed");
115
+ assert.deepEqual(tf.map((g) => g.body.test), want);
116
+ for (const g of tf) assert.ok(g.at < r.exitAt - 300, `test_failed posted ${r.exitAt - g.at} ms before exit`);
117
+ });
118
+ }
119
+
120
+ test("parser dedupes repeated failures and flushes a vitest FAIL without a location at end", () => {
121
+ const got = [];
122
+ const p = createTestParser((t) => got.push(t));
123
+ for (const l of [...PYTEST, ...PYTEST, " FAIL x.test.ts > lonely", "Error: z"]) p.line(l);
124
+ p.end();
125
+ assert.equal(got.length, 3);
126
+ assert.deepEqual(got[2], { id: "x.test.ts > lonely", file: "x.test.ts", message: "Error: z" });
127
+ });
128
+
129
+ test("router unreachable or 5xx: result unchanged, one warning, under 2 s added", async () => {
130
+ const dead = await router(); const deadUrl = dead.url; await dead.close();
131
+ const bad = await router(503);
132
+ for (const url of [deadUrl, bad.url]) {
133
+ const base = await run(["ci-step", "--name", "n", "--", ...node("console.log('x'); process.exit(3)")], ENV0);
134
+ const r = await run(["ci-step", "--name", "n", "--", ...node("console.log('x'); process.exit(3)")], { ...ENV0, FORGEDOCK_CI_EVENTS_URL: url });
135
+ assert.equal(r.code, 3);
136
+ assert.equal(r.out.toString(), "x\n");
137
+ const warns = r.err.toString().split("\n").filter((l) => l.includes("event delivery failed"));
138
+ assert.equal(warns.length, 1);
139
+ assert.ok(r.wall - base.wall < 2000, `added ${r.wall - base.wall} ms`);
140
+ }
141
+ await bad.close();
142
+ });
143
+
144
+ test("hook with env unset exits 0 and posts nothing; with env set posts the mapped event", async () => {
145
+ const rt = await router();
146
+ const off = await run(["ci-hook", "job-started"], ENV0);
147
+ assert.equal(off.code, 0);
148
+ assert.equal(off.out.length, 0);
149
+ assert.equal(rt.got.length, 0);
150
+ const env = { ...ENV0, FORGEDOCK_CI_EVENTS_URL: rt.url };
151
+ assert.equal((await run(["ci-hook", "job-started"], env)).code, 0);
152
+ assert.equal((await run(["ci-hook", "job-completed"], env)).code, 0);
153
+ await rt.close();
154
+ assert.deepEqual(rt.got.map((g) => g.body.type), ["job_started", "job_finished"]);
155
+ assert.equal(rt.got[0].body.job, "unit");
156
+ assert.equal(rt.got[0].body.pr, 42);
157
+ });
158
+
159
+ test("poster is a no-op without a URL and baseEvent parses the PR from GITHUB_REF", () => {
160
+ assert.equal(createPoster({ env: {} }).enabled, false);
161
+ assert.equal(baseEvent({ GITHUB_REF: "refs/heads/main" }).pr, undefined);
162
+ assert.equal(baseEvent({ GITHUB_REF: "refs/pull/9/merge" }).pr, 9);
163
+ });
164
+
165
+ test("step_failed reaches the router within 2 s of the failure (fixture step fails at t=5 s)", async () => {
166
+ const rt = await router();
167
+ // Nominal 120 s sequence; only the failing step at t=5 s matters, so it is the one executed.
168
+ const t0 = Date.now();
169
+ const r = await run(["ci-step", "--name", "slow", "--", ...node("setTimeout(()=>{console.error('Error: late');process.exit(1)},5000)")], { ...ENV0, FORGEDOCK_CI_EVENTS_URL: rt.url });
170
+ await rt.close();
171
+ const failed = rt.got.find((g) => g.body.type === "step_failed");
172
+ const latency = failed.at - (t0 + 5000);
173
+ console.log(`# measured step_failed latency after t=5 s failure: ${latency} ms`);
174
+ assert.ok(failed, "step_failed delivered");
175
+ assert.ok(latency <= 2000, `latency ${latency} ms`);
176
+ assert.equal(r.code, 1);
177
+ });