forgedock 1.55.1 → 1.57.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 +1 -1
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +58 -10
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +3 -1
- package/bin/lean/batch-health.mjs +5 -1
- package/bin/lean/batch-health.test.mjs +7 -1
- package/bin/lean/batch.mjs +7 -2
- package/bin/lean/batch.test.mjs +45 -0
- package/bin/lean/conformance.e2e.test.mjs +3 -2
- package/bin/lean/conformance.mjs +88 -17
- package/bin/lean/conformance.test.mjs +98 -3
- package/bin/lean/decisions.mjs +86 -1
- package/bin/lean/decisions.test.mjs +21 -1
- package/bin/lean/depcache.mjs +124 -13
- package/bin/lean/depcache.test.mjs +121 -3
- package/bin/lean/design-gate.mjs +144 -0
- package/bin/lean/design-gate.test.mjs +169 -0
- package/bin/lean/effects-cap.test.mjs +17 -0
- package/bin/lean/effects.mjs +58 -13
- package/bin/lean/heavy.mjs +25 -8
- package/bin/lean/hostload.test.mjs +28 -0
- package/bin/lean/intake.mjs +97 -0
- package/bin/lean/intake.test.mjs +105 -0
- package/bin/lean/interfaces.mjs +181 -0
- package/bin/lean/interfaces.test.mjs +192 -0
- package/bin/lean/issuewatch-install.mjs +52 -12
- package/bin/lean/issuewatch-install.test.mjs +50 -0
- package/bin/lean/issuewatch-parity.mjs +12 -2
- package/bin/lean/issuewatch-parity.test.mjs +26 -0
- package/bin/lean/issuewatch-reconcile.mjs +29 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
- package/bin/lean/issuewatch.mjs +34 -3
- package/bin/lean/issuewatch.test.mjs +49 -1
- package/bin/lean/lanecheck.test.mjs +15 -4
- package/bin/lean/lean.mjs +80 -25
- package/bin/lean/lean.test.mjs +149 -3
- package/bin/lean/orchestrate-blocked.test.mjs +18 -2
- package/bin/lean/orchestrate-owned.test.mjs +14 -5
- package/bin/lean/orchestrate.mjs +26 -4
- package/bin/lean/orphan-pr.mjs +125 -0
- package/bin/lean/orphan-pr.test.mjs +145 -0
- package/bin/lean/pagegate.mjs +35 -12
- package/bin/lean/pagegate.test.mjs +39 -1
- package/bin/lean/preflight.mjs +35 -1
- package/bin/lean/preflight.test.mjs +27 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/reap.test.mjs +39 -0
- package/bin/lean/recovery.test.mjs +25 -0
- package/bin/lean/release-config.mjs +158 -0
- package/bin/lean/release-config.test.mjs +109 -0
- package/bin/lean/release-control.mjs +148 -0
- package/bin/lean/release-control.test.mjs +143 -0
- package/bin/lean/release-fence.mjs +50 -0
- package/bin/lean/release-fence.test.mjs +105 -0
- package/bin/lean/release-flakes.mjs +139 -0
- package/bin/lean/release-flakes.test.mjs +116 -0
- package/bin/lean/release-ledger.mjs +160 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +92 -0
- package/bin/lean/release-minutes.test.mjs +99 -0
- package/bin/lean/release-nightly.mjs +75 -0
- package/bin/lean/release-nightly.test.mjs +48 -0
- package/bin/lean/release-postmerge.mjs +45 -21
- package/bin/lean/release-review.e2e.test.mjs +1 -0
- package/bin/lean/release-review.mjs +54 -7
- package/bin/lean/release-review.test.mjs +76 -7
- package/bin/lean/release-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release.mjs +177 -19
- package/bin/lean/release.test.mjs +80 -16
- package/bin/lean/render.mjs +3 -1
- package/bin/lean/run-issue-placement.test.mjs +82 -0
- package/bin/lean/sandbox-remote.mjs +16 -0
- package/bin/lean/schedd.mjs +1 -1
- package/bin/lean/seam.mjs +115 -0
- package/bin/lean/seam.test.mjs +118 -0
- package/bin/lean/selftest-journey.mjs +40 -2
- package/bin/lean/selftest-journey.test.mjs +43 -3
- package/bin/lean/statuscomment.mjs +168 -0
- package/bin/lean/statuscomment.test.mjs +133 -0
- package/bin/lean/ui-quality.mjs +57 -0
- package/bin/lean/ui-quality.test.mjs +55 -0
- package/bin/lean/visual-gate.test.mjs +63 -0
- package/bin/pool/agent.mjs +16 -2
- package/bin/pool/router.mjs +5 -1
- package/bin/review-staging.mjs +8 -5
- package/bin/stats/card.mjs +117 -0
- package/bin/stats/card.test.mjs +109 -0
- package/bin/stats/conformance-outcomes.test.mjs +2 -1
- package/bin/stats/depth.mjs +1 -1
- package/bin/stats/gh-retry.test.mjs +152 -0
- package/bin/stats/github-source.mjs +147 -14
- package/bin/stats/index.mjs +35 -2
- package/bin/stats/stats.test.mjs +31 -3
- package/bin/vendor/js-yaml/LICENSE +21 -0
- package/bin/vendor/js-yaml/PIN.md +7 -0
- package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
- package/commands/design-render-critique-loop.md +2 -0
- package/commands/design.md +2 -0
- package/commands/incident-response.md +4 -0
- package/commands/issue.md +1 -1
- package/commands/milestone.md +1 -1
- package/commands/pipeline-status.md +13 -0
- package/commands/review-pr-agents/frontend.md +1 -0
- package/commands/review-pr-staging.md +5 -0
- package/docs/CONFIG.md +75 -1
- package/docs/ISSUE-WATCH.md +7 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +10 -0
- package/docs/design/visual-gate.md +25 -0
- package/docs/eval/adversarial-bench.md +2 -2
- package/docs/eval/corpus/adversarial-v1.json +3 -3
- package/docs/site/start-a-new-project.md +7 -0
- package/docs/spec/forge-protocol-v1.md +31 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +15 -1
- package/scripts/acceptance-red-green.test.sh +12 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +4 -1
- package/scripts/bootstrap-create.mjs +8 -2
- package/scripts/ci-local.test.sh +3 -3
- package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
- package/scripts/plan-validate-live.mjs +9 -6
- package/scripts/review-prepare.sh +7 -1
- package/scripts/review-roster.sh +5 -2
- package/scripts/review-roster.test.sh +9 -0
- package/scripts/visual-gate.mjs +64 -0
- package/templates/bootstrap/technical-spike.md +17 -0
- package/templates/contracts/seam-check.mjs +236 -0
|
@@ -0,0 +1,109 @@
|
|
|
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 { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { parsePolicy, validatePolicy, readPolicy, INIT_PROFILE, checkConfigFromCli, initFromCli, POLICY_PATH } from "./release-config.mjs";
|
|
9
|
+
import { releaseFromCli } from "./release.mjs";
|
|
10
|
+
|
|
11
|
+
const OK = `schema: 1
|
|
12
|
+
branches: {default: main, integration: staging}
|
|
13
|
+
units:
|
|
14
|
+
api: {paths: ["services/api/**"], criticality: high}
|
|
15
|
+
web: {paths: ["web/**"]}
|
|
16
|
+
couplings:
|
|
17
|
+
- {paths: ["shared/**"], affects: [api, web]}
|
|
18
|
+
lanes:
|
|
19
|
+
release: {pipeline: full, ci_tier: T3, base: integration}
|
|
20
|
+
deploy:
|
|
21
|
+
pipelines:
|
|
22
|
+
full: {workflow: deploy.yml, trigger: push, wait: true}
|
|
23
|
+
ci:
|
|
24
|
+
tiers: {T3: {jobs: [e2e]}}
|
|
25
|
+
`;
|
|
26
|
+
const check = (text) => { const r = parsePolicy(text); return r.error ? [`parse: ${r.error}`] : validatePolicy(r.policy); };
|
|
27
|
+
const ioFor = (files, calls = []) => ({ calls, printed: [], print(l) { this.printed.push(l); }, git: (a) => { calls.push(a); const t = files[a[1]]; if (t === undefined) throw new Error("missing"); return t; } });
|
|
28
|
+
|
|
29
|
+
describe("validate", () => {
|
|
30
|
+
it("accepts a full policy and the init profile", () => {
|
|
31
|
+
assert.deepEqual(check(OK), []);
|
|
32
|
+
assert.deepEqual(check(INIT_PROFILE), []);
|
|
33
|
+
});
|
|
34
|
+
it("fails closed: unknown key, wrong type, duplicate key, bad schema", () => {
|
|
35
|
+
assert.match(check(OK + "bogus: 1\n").join(), /bogus: unknown key/);
|
|
36
|
+
assert.match(check(OK.replace("criticality: high", "criticality: extreme")).join(), /criticality/);
|
|
37
|
+
assert.match(check(OK.replace("paths: [\"web/**\"]", "paths: web")).join(), /expected a list/);
|
|
38
|
+
assert.match(check(OK + "plan: {approval: wait}\nplan: {approval: auto}\n").join(), /parse: .*duplicated mapping key/);
|
|
39
|
+
assert.match(check("branches: {default: main}\n").join(), /schema/);
|
|
40
|
+
assert.match(check("schema: 2\n").join(), /not one of 1/);
|
|
41
|
+
});
|
|
42
|
+
it("unreachable lanes fail", () => {
|
|
43
|
+
assert.match(check(OK.replace("pipeline: full, ci_tier", "pipeline: nope, ci_tier")).join(), /pipeline nope is not in deploy.pipelines/);
|
|
44
|
+
assert.match(check(OK.replace("ci_tier: T3", "ci_tier: T9")).join(), /ci_tier T9/);
|
|
45
|
+
assert.match(check(OK.replace(", integration: staging", "")).join(), /branches.integration is not set/);
|
|
46
|
+
assert.match(check(OK.replace("affects: [api, web]", "affects: [api, ghost]")).join(), /unit ghost/);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe("I23 deferred keys are rejected", () => {
|
|
51
|
+
const cases = {
|
|
52
|
+
"plan.auto_if": "plan: {auto_if: x}\n", "retention_days": "retention_days: 30\n", "ci.forbid_per_issue_steps": "ci: {forbid_per_issue_steps: true}\n",
|
|
53
|
+
"couplings[].refine": "couplings:\n - {paths: [a], affects: [api], refine: x}\n", "ci.provider: command": "ci: {provider: command}\n", "risk.weights": "risk: {weights: {a: 1}}\n",
|
|
54
|
+
};
|
|
55
|
+
for (const [name, extra] of Object.entries(cases)) it(name, () => {
|
|
56
|
+
const out = check(`schema: 1\nunits:\n api: {paths: [a]}\n${extra}`);
|
|
57
|
+
assert.ok(out.some((l) => l.startsWith(name) && /deferred/.test(l)), `${name}: ${out.join(" | ")}`);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("readPolicy (I13)", () => {
|
|
62
|
+
it("reads origin/<default>:.forge/release.yaml via git show only; a head-modified worktree copy has no effect", () => {
|
|
63
|
+
const cwd = tmpDir("relcfg-");
|
|
64
|
+
mkdirSync(join(cwd, ".forge"));
|
|
65
|
+
writeFileSync(join(cwd, POLICY_PATH), "schema: 1\nplan: {approval: auto}\n"); // PR head weakens the gate
|
|
66
|
+
const calls = [];
|
|
67
|
+
const r = readPolicy({ io: ioFor({ "origin/main:.forge/release.yaml": INIT_PROFILE }, calls), defaultBranch: "main", cwd });
|
|
68
|
+
assert.deepEqual(calls, [["show", "origin/main:.forge/release.yaml"]]);
|
|
69
|
+
assert.equal(r.source, "file");
|
|
70
|
+
assert.equal(r.policy.plan.approval, "wait");
|
|
71
|
+
assert.match(r.sha, /^[0-9a-f]{64}$/);
|
|
72
|
+
});
|
|
73
|
+
it("an invalid committed file yields findings and no policy", () => {
|
|
74
|
+
const r = readPolicy({ io: ioFor({ "origin/main:.forge/release.yaml": "schema: 1\nx: 1\n" }), defaultBranch: "main" });
|
|
75
|
+
assert.equal(r.policy, null); assert.match(r.findings.join(), /x: unknown key/);
|
|
76
|
+
});
|
|
77
|
+
it("absent file falls back to the flat forge.yaml release.* keys", () => {
|
|
78
|
+
const cwd = tmpDir("relcfg-");
|
|
79
|
+
writeFileSync(join(cwd, "forge.yaml"), "release:\n auto_merge: true\n publish_workflow: p.yml\n");
|
|
80
|
+
const r = readPolicy({ io: ioFor({}), defaultBranch: "main", cwd });
|
|
81
|
+
assert.equal(r.source, "forge.yaml"); assert.equal(r.flat.autoMerge, true); assert.equal(r.flat.publishWorkflow, "p.yml");
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe("CLI", () => {
|
|
86
|
+
it("check-config exits 1 on findings, 0 when valid or absent", async () => {
|
|
87
|
+
const cwd = tmpDir("relcfg-");
|
|
88
|
+
const run = (files) => { const io = ioFor(files); return releaseFromCli(["check-config"], { io, cwd }).then((c) => [c, io.printed.join("\n")]); };
|
|
89
|
+
assert.equal((await run({ "origin/main:.forge/release.yaml": OK }))[0], 0);
|
|
90
|
+
const bad = await run({ "origin/main:.forge/release.yaml": OK + "zzz: 1\n" });
|
|
91
|
+
assert.equal(bad[0], 1); assert.match(bad[1], /zzz: unknown key/);
|
|
92
|
+
assert.equal((await run({}))[0], 0);
|
|
93
|
+
});
|
|
94
|
+
it("init writes the 7.4 profile and nothing else, and never overwrites", async () => {
|
|
95
|
+
const cwd = tmpDir("relcfg-");
|
|
96
|
+
const io = ioFor({});
|
|
97
|
+
assert.equal(await releaseFromCli(["init"], { io, cwd }), 0);
|
|
98
|
+
assert.equal(readFileSync(join(cwd, POLICY_PATH), "utf8"), INIT_PROFILE);
|
|
99
|
+
assert.deepEqual(readdirSync(cwd), [".forge"]); assert.deepEqual(readdirSync(join(cwd, ".forge")), ["release.yaml"]);
|
|
100
|
+
assert.deepEqual(check(INIT_PROFILE), []);
|
|
101
|
+
assert.equal(initFromCli([], { io, cwd }), 1);
|
|
102
|
+
assert.equal(existsSync(join(cwd, "forge.yaml")), false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("accepts the flake and quarantine policy keys (#5568)", () => {
|
|
106
|
+
assert.deepEqual(check(`${OK} flake: {quarantine_after: 3, window_days: 14}\nquarantine: {days: 14, max: 15}\n`.replace("ci:\n tiers: {T3: {jobs: [e2e]}}\n flake", "ci:\n tiers: {T3: {jobs: [e2e]}}\n flake")), []);
|
|
107
|
+
assert.notDeepEqual(check(`${OK}quarantine: {max: x}\n`), []);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* One audited control verb set (#5556, epic #5549 Phase 0, invariants I15/I20/I24/I26): `forgedock release control <verb>`
|
|
5
|
+
* (hold, resume, cancel, lane, exempt, freeze, unfreeze); `forgedock release <verb>` is an alias of the same `runControl`.
|
|
6
|
+
* Every mutation needs `--reason`, is one key-scoped `updateActive` commit (state in `_active.json`, one `controls.jsonl`
|
|
7
|
+
* line {at, actor, host, verb, reason, before, after, epoch}) and posts a `FORGE:CONTROL` comment on the tracker (the lease's
|
|
8
|
+
* issue). `holdCheck` is read by `fenced()` before every irreversible action, so every driver obeys a hold (I24).
|
|
9
|
+
* `buildDispatchArgs` is the only workflow-dispatch builder: it never carries a human break-glass input (I26).
|
|
10
|
+
*/
|
|
11
|
+
import { hostname } from "node:os";
|
|
12
|
+
import { readActive, readLedger, updateActive } from "./release-ledger.mjs";
|
|
13
|
+
import { UNSKIPPABLE_CLASSES, isUnskippable, parseFlakeConfig, canQuarantine } from "./release-flakes.mjs";
|
|
14
|
+
|
|
15
|
+
export const CONTROL_SCHEMA = "forgedock.release.control/v1";
|
|
16
|
+
export const CONTROL_MARKER = "FORGE:CONTROL";
|
|
17
|
+
export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze"];
|
|
18
|
+
export { UNSKIPPABLE_CLASSES as UNSKIPPABLE };
|
|
19
|
+
export const EXEMPT_MAX_H = { skip: 24, quarantine: 14 * 24 };
|
|
20
|
+
export const LANES = ["train", "release", "p0", "exclude"];
|
|
21
|
+
const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze"];
|
|
22
|
+
const BREAK_GLASS = /^(override_freeze|acknowledge_hotfix_revert|override_.*|acknowledge_.*)$/;
|
|
23
|
+
|
|
24
|
+
/** Argv of `gh workflow run`; rejects a break-glass input (I26). */
|
|
25
|
+
export function buildDispatchArgs({ workflow, repo, ref, inputs = {} }) {
|
|
26
|
+
for (const k of Object.keys(inputs)) if (BREAK_GLASS.test(k)) throw new Error(`dispatch input ${k} is a human break-glass input; the engine never sets it (I26)`);
|
|
27
|
+
return ["workflow", "run", workflow, "--repo", repo, "--ref", ref, ...Object.entries(inputs).flatMap(([k, v]) => ["-f", `${k}=${v}`])];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The release-PR-body section listing live exemptions (I20: a demoted check appears in the PR body); "" when none. */
|
|
31
|
+
export function exemptionsSection(exemptions, now = Date.now()) {
|
|
32
|
+
const live = Object.entries(exemptions ?? {}).filter(([, e]) => e?.until && Date.parse(e.until) > now);
|
|
33
|
+
if (!live.length) return "";
|
|
34
|
+
return `\n\n<!-- FORGE:EXEMPT -->\n### Exempted checks\n${live.map(([c, e]) => `- \`${c}\` (${e.mode}) until ${e.until}, issue #${e.issue}, by ${e.actor}: ${e.reason}`).join("\n")}\n`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Why release `id` must not act (held or cancelled), else null. Throws when `_active` cannot be read (callers refuse, I5). */
|
|
38
|
+
export async function holdCheck(lctx, id) {
|
|
39
|
+
const a = await readActive(lctx);
|
|
40
|
+
const h = a.holds?.[id] ?? a.holds?.["*"];
|
|
41
|
+
if (h) return `held (${h.reason ?? "no reason"})`;
|
|
42
|
+
if (a.cancelled?.[id]) return `cancelled (${a.cancelled[id].reason ?? "no reason"})`;
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
47
|
+
const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force"];
|
|
48
|
+
const positionals = (argv) => argv.filter((a, i) => !a.startsWith("--") && !FLAGS.includes(argv[i - 1]));
|
|
49
|
+
const ttlHours = (s) => { const m = /^(\d+)([hd])$/.exec(String(s ?? "")); return m ? Number(m[1]) * (m[2] === "d" ? 24 : 1) : null; };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Run one control verb. `argv` is what follows the verb. `ctx`: {io, repo, policy, actor, host, now}.
|
|
53
|
+
* @returns {{schema, ok: boolean, verb, error?, ...}}; never throws for a refusal.
|
|
54
|
+
*/
|
|
55
|
+
export async function runControl(verb, argv, ctx) {
|
|
56
|
+
const { io, repo, policy = null } = ctx;
|
|
57
|
+
const fail = (error) => ({ schema: CONTROL_SCHEMA, ok: false, verb, error });
|
|
58
|
+
if (!VERBS.includes(verb)) return fail(`unknown control verb ${verb}; one of ${VERBS.join("|")}`);
|
|
59
|
+
const reason = flagOf(argv, "--reason");
|
|
60
|
+
if (!reason || !reason.trim() || reason.startsWith("--")) return fail(`${verb}: --reason is required`);
|
|
61
|
+
const actor = ctx.actor ?? process.env.GITHUB_ACTOR ?? process.env.USER ?? "unknown", host = ctx.host ?? hostname();
|
|
62
|
+
const pos = positionals(argv);
|
|
63
|
+
const lctx = { io, repo, credential: "driver" };
|
|
64
|
+
const at = new Date(ctx.now ?? Date.now()).toISOString();
|
|
65
|
+
let apply; // (active) => {patch, before, after} | {refuse}
|
|
66
|
+
let after = null;
|
|
67
|
+
if (verb === "hold" || verb === "resume" || verb === "cancel") {
|
|
68
|
+
const id = pos[0];
|
|
69
|
+
if (!id) return fail(`${verb}: release id required`);
|
|
70
|
+
if (verb === "cancel") {
|
|
71
|
+
const led = await readLedger(lctx, id).catch(() => null);
|
|
72
|
+
const s = led?.state;
|
|
73
|
+
if (!s) return fail(`cancel: no ledger for release ${id}`);
|
|
74
|
+
if (s.steps?.promotion?.result?.merged || s.steps?.["post-merge"]?.done || s.status === "MERGED") return fail(`cancel: release ${id} is already MERGED; the only exits are LIVE or rollback`);
|
|
75
|
+
}
|
|
76
|
+
const key = verb === "cancel" ? "cancelled" : "holds";
|
|
77
|
+
apply = (a) => {
|
|
78
|
+
const before = a[key]?.[id] ?? null, next = { ...(a[key] ?? {}) };
|
|
79
|
+
if (verb === "resume") delete next[id]; else next[id] = { reason, actor, at };
|
|
80
|
+
return { patch: { [key]: next }, before, after: next[id] ?? null };
|
|
81
|
+
};
|
|
82
|
+
} else if (verb === "lane") {
|
|
83
|
+
const force = flagOf(argv, "--force");
|
|
84
|
+
if (!LANES.includes(force)) return fail(`lane: --force must be one of ${LANES.join("|")}`);
|
|
85
|
+
const issues = pos.map((p) => p.replace(/^#/, "")).filter((p) => /^\d+$/.test(p));
|
|
86
|
+
if (!issues.length) return fail("lane: at least one #issue required");
|
|
87
|
+
apply = (a) => {
|
|
88
|
+
const next = { ...(a.lanes ?? {}) }, before = {};
|
|
89
|
+
for (const n of issues) { before[n] = next[n] ?? null; next[n] = { force, reason, actor, at }; }
|
|
90
|
+
return { patch: { lanes: next }, before, after: Object.fromEntries(issues.map((n) => [n, force])) };
|
|
91
|
+
};
|
|
92
|
+
} else if (verb === "exempt") {
|
|
93
|
+
const check = pos[0], mode = flagOf(argv, "--mode"), issue = flagOf(argv, "--issue"), hours = ttlHours(flagOf(argv, "--until"));
|
|
94
|
+
if (!check) return fail("exempt: check or test name required");
|
|
95
|
+
if (!(mode in EXEMPT_MAX_H)) return fail("exempt: --mode must be skip or quarantine");
|
|
96
|
+
if (!/^#?\d+$/.test(issue ?? "")) return fail("exempt: --issue N is required");
|
|
97
|
+
if (hours == null) return fail("exempt: --until <Nh|Nd> is required");
|
|
98
|
+
if (hours > EXEMPT_MAX_H[mode]) return fail(`exempt: ${mode} expires in at most ${EXEMPT_MAX_H[mode]}h (got ${hours}h)`);
|
|
99
|
+
const cfg = parseFlakeConfig(policy);
|
|
100
|
+
if (isUnskippable(check, cfg.unskippable)) return fail(`exempt: ${check} is an unskippable class (${cfg.unskippable.join(", ")}) (I20)`);
|
|
101
|
+
const trusted = policy?.trust?.actors ?? [];
|
|
102
|
+
if (trusted.length && !trusted.includes(actor)) return fail(`exempt: actor ${actor} is not trusted (policy trust.actors)`);
|
|
103
|
+
const num = String(issue).replace("#", "");
|
|
104
|
+
let iv = null;
|
|
105
|
+
try { iv = JSON.parse(String(await io.gh(["issue", "view", num, "--repo", repo, "--json", "number,state,labels"]))); } catch { /* unreadable: refused below */ }
|
|
106
|
+
if (!iv || String(iv.number) !== num) return fail(`exempt: issue #${num} does not exist or is unreadable`);
|
|
107
|
+
const nowMs = ctx.now ?? Date.now(), labels = (iv.labels ?? []).map((l) => l.name ?? l);
|
|
108
|
+
const entry = { mode, issue: num, reason, actor, at, until: new Date(nowMs + hours * 3_600_000).toISOString() };
|
|
109
|
+
apply = (a) => {
|
|
110
|
+
if (mode === "quarantine") {
|
|
111
|
+
const q = canQuarantine({ target: check, exemptions: a.exemptions, issueLabels: labels, issueOpen: String(iv.state).toUpperCase() === "OPEN", cfg, now: nowMs });
|
|
112
|
+
if (!q.ok) return { refuse: `exempt: ${q.why}` };
|
|
113
|
+
}
|
|
114
|
+
return { patch: { exemptions: { ...(a.exemptions ?? {}), [check]: entry } }, before: a.exemptions?.[check] ?? null, after: entry };
|
|
115
|
+
};
|
|
116
|
+
} else { // freeze | unfreeze: the repo's own deploy variable (6.4), not a second mechanism
|
|
117
|
+
const name = policy?.deploy?.freeze_variable;
|
|
118
|
+
if (!name) return fail(`${verb}: policy deploy.freeze_variable is not set`);
|
|
119
|
+
apply = (a) => ({ patch: { freeze: verb === "freeze" ? { variable: name, reason, actor, at } : null }, before: a.freeze ?? null, after: verb === "freeze" ? { variable: name } : null });
|
|
120
|
+
ctx.afterCommit = async () => { await io.gh(verb === "freeze" ? ["variable", "set", name, "--repo", repo, "--body", "1"] : ["variable", "delete", name, "--repo", repo]); };
|
|
121
|
+
}
|
|
122
|
+
let line;
|
|
123
|
+
const r = await updateActive(lctx, OWNED, (a) => {
|
|
124
|
+
const o = apply(a);
|
|
125
|
+
if (o.refuse) return { refuse: o.refuse };
|
|
126
|
+
after = o.after;
|
|
127
|
+
line = { at, actor, host, verb, reason, before: o.before ?? null, after: o.after ?? null, epoch: a.epoch ?? null };
|
|
128
|
+
return { patch: o.patch, control: line };
|
|
129
|
+
});
|
|
130
|
+
if (!r.ok) return fail(r.refused ?? `could not commit the control (lost the race after ${r.attempts} attempts)`);
|
|
131
|
+
if (ctx.afterCommit) await ctx.afterCommit();
|
|
132
|
+
const issue = r.active.lease?.issue;
|
|
133
|
+
let comment = null;
|
|
134
|
+
if (issue) {
|
|
135
|
+
const body = `<!-- ${CONTROL_MARKER} -->\n**${verb}** by ${actor}@${host} at ${at} (epoch ${line.epoch ?? "none"})\nreason: ${reason}\n\n<!-- ${CONTROL_MARKER} ${JSON.stringify(line)} -->`;
|
|
136
|
+
comment = (await io.api("POST", `repos/${repo}/issues/${issue}/comments`, { body }))?.id ?? null;
|
|
137
|
+
}
|
|
138
|
+
return { schema: CONTROL_SCHEMA, ok: true, verb, entry: line, comment };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** CLI: `[--repo R] [--json]` plus the verb's flags; prints one line or the JSON result; @returns the exit code. */
|
|
142
|
+
export async function controlFromCli(verb, argv, { io, policy, actor, host }) {
|
|
143
|
+
const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
|
|
144
|
+
const r = await runControl(verb, argv.filter((a) => a !== "--json"), { io, repo, policy, actor, host, now: io.now?.() });
|
|
145
|
+
if (argv.includes("--json")) io.print(JSON.stringify(r));
|
|
146
|
+
else io.print(r.ok ? `release ${verb}: recorded (${r.entry.at})` : `release ${verb}: refused: ${r.error}`);
|
|
147
|
+
return r.ok ? 0 : 1;
|
|
148
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
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 { runControl, controlFromCli, buildDispatchArgs, holdCheck, exemptionsSection, CONTROL_SCHEMA } from "./release-control.mjs";
|
|
6
|
+
import { fenced } from "./release-fence.mjs";
|
|
7
|
+
|
|
8
|
+
// A tiny in-memory GitHub: _active branch (active.json + controls.jsonl) and one release ledger.
|
|
9
|
+
function world({ active = { epoch: 1, lease: { holder: "A", epoch: 1, release: "r20260101-000000-1", issue: 9 } }, state = null } = {}) {
|
|
10
|
+
const w = { active, controls: "", comments: [], vars: [], gh: [], files: {}, sha: 0 };
|
|
11
|
+
w.io = {
|
|
12
|
+
now: () => 1_700_000_000_000, print: (l) => (w.out ??= []).push(l),
|
|
13
|
+
gh: async (a) => { w.gh.push(a); if (a[0] === "repo") return JSON.stringify({ nameWithOwner: "o/r" }); if (a[0] === "variable") w.vars.push(a); if (a[0] === "issue" && a[1] === "view") return a[2] === "404" ? "" : JSON.stringify({ number: Number(a[2]), state: "OPEN", labels: [{ name: "flake" }] }); return ""; },
|
|
14
|
+
api: async (method, path, body) => {
|
|
15
|
+
if (method === "GET" && /git\/ref\/heads\/_active$/.test(path)) return { object: { sha: "h0" } };
|
|
16
|
+
if (method === "GET" && /contents\/active\.json/.test(path)) return { content: Buffer.from(JSON.stringify(w.active)).toString("base64") };
|
|
17
|
+
if (method === "GET" && /contents\/controls\.jsonl/.test(path)) return { content: Buffer.from(w.controls).toString("base64") };
|
|
18
|
+
if (method === "GET" && /git\/commits\//.test(path)) return { tree: { sha: "t0" } };
|
|
19
|
+
if (method === "POST" && /git\/trees/.test(path)) { for (const t of body.tree) w.files[t.path] = t.content; return { sha: "t1" }; }
|
|
20
|
+
if (method === "POST" && /git\/commits/.test(path)) return { sha: `c${++w.sha}` };
|
|
21
|
+
if (method === "PATCH" && /git\/refs/.test(path)) { w.active = JSON.parse(w.files["active.json"]); w.controls = w.files["controls.jsonl"] ?? w.controls; return {}; }
|
|
22
|
+
if (method === "POST" && /issues\/\d+\/comments/.test(path)) { w.comments.push(body.body); return { id: w.comments.length }; }
|
|
23
|
+
throw new Error(`unrouted ${method} ${path}`);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
return w;
|
|
27
|
+
}
|
|
28
|
+
const RID = "r20260101-000000-1";
|
|
29
|
+
const base = (w, extra = {}) => ({ io: w.io, repo: "o/r", actor: "op", host: "h1", now: 1_700_000_000_000, ...extra });
|
|
30
|
+
|
|
31
|
+
describe("release control (#5556)", () => {
|
|
32
|
+
it("every mutation needs --reason (I15)", async () => {
|
|
33
|
+
const w = world();
|
|
34
|
+
for (const [v, a] of [["hold", [RID]], ["resume", [RID]], ["cancel", [RID]], ["lane", ["#1", "--force", "p0"]], ["exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "2h"]], ["freeze", []], ["unfreeze", []]]) {
|
|
35
|
+
const r = await runControl(v, a, base(w, { policy: { deploy: { freeze_variable: "DEPLOY_FREEZE" } } }));
|
|
36
|
+
assert.equal(r.ok, false, v); assert.match(r.error, /--reason is required/);
|
|
37
|
+
}
|
|
38
|
+
assert.equal(w.comments.length, 0);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("exempt of an unskippable class (migration) is rejected; so is a policy-added one", async () => {
|
|
42
|
+
const w = world();
|
|
43
|
+
const a = ["--mode", "skip", "--issue", "3", "--until", "2h", "--reason", "x"];
|
|
44
|
+
assert.match((await runControl("exempt", ["migration", ...a], base(w))).error, /unskippable/);
|
|
45
|
+
for (const c of ["security", "rollback", "backup-restore", "secrets"]) assert.equal((await runControl("exempt", [c, ...a], base(w))).ok, false);
|
|
46
|
+
assert.equal((await runControl("exempt", ["custom", ...a], base(w, { policy: { ci: { unskippable: ["custom"] } } }))).ok, false);
|
|
47
|
+
assert.equal(w.controls, "");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("exempt: mode ttl caps, required issue, trusted actor", async () => {
|
|
51
|
+
const w = world();
|
|
52
|
+
const ok = ["lint", "--mode", "skip", "--issue", "3", "--until", "24h", "--reason", "flaky"];
|
|
53
|
+
assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "25h", "--reason", "r"], base(w))).error, /at most 24h/);
|
|
54
|
+
assert.match((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "15d", "--reason", "r"], base(w))).error, /at most 336h/);
|
|
55
|
+
assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--until", "1h", "--reason", "r"], base(w))).error, /--issue/);
|
|
56
|
+
assert.match((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["boss"] } } }))).error, /not trusted/);
|
|
57
|
+
assert.equal((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "14d", "--reason", "r"], base(w))).ok, true);
|
|
58
|
+
assert.equal((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["op"] } } }))).ok, true);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("exempt without an existing issue is refused (#5568)", async () => {
|
|
62
|
+
const w = world();
|
|
63
|
+
const r = await runControl("exempt", ["lint", "--mode", "skip", "--issue", "404", "--until", "2h", "--reason", "x"], base(w));
|
|
64
|
+
assert.equal(r.ok, false); assert.match(r.error, /does not exist/);
|
|
65
|
+
assert.equal(w.controls, "");
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("quarantine is refused at the cap and without a flake-labelled issue, and a live one shows in the PR body (#5568)", async () => {
|
|
69
|
+
const at = new Date(1_700_000_000_000).toISOString(), until = new Date(1_700_000_000_000 + 3_600_000).toISOString();
|
|
70
|
+
const full = Object.fromEntries(Array.from({ length: 2 }, (_, i) => [`t${i}`, { mode: "quarantine", issue: "3", at, until }]));
|
|
71
|
+
const w = world({ active: { epoch: 1, lease: { holder: "A", epoch: 1, release: RID, issue: 9 }, exemptions: full } });
|
|
72
|
+
const a = ["--mode", "quarantine", "--issue", "3", "--until", "1d", "--reason", "x"];
|
|
73
|
+
assert.match((await runControl("exempt", ["new", ...a], base(w, { policy: { quarantine: { max: 2 } } }))).error, /cap 2/);
|
|
74
|
+
const gh = w.io.gh;
|
|
75
|
+
w.io.gh = async (x) => (x[0] === "issue" ? JSON.stringify({ number: 3, state: "OPEN", labels: [] }) : gh(x));
|
|
76
|
+
assert.match((await runControl("exempt", ["new", ...a], base(w))).error, /labelled flake/);
|
|
77
|
+
w.io.gh = gh;
|
|
78
|
+
const ok = await runControl("exempt", ["new", ...a], base(w));
|
|
79
|
+
assert.equal(ok.ok, true);
|
|
80
|
+
assert.match(exemptionsSection(w.active.exemptions, 1_700_000_000_000), /FORGE:EXEMPT[\s\S]*`new` \(quarantine\)/);
|
|
81
|
+
assert.equal(exemptionsSection({}, 0), "");
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("a mutation appends the audit line and posts a FORGE:CONTROL comment", async () => {
|
|
85
|
+
const w = world();
|
|
86
|
+
const r = await runControl("hold", [RID, "--reason", "pause for incident"], base(w));
|
|
87
|
+
assert.equal(r.schema, CONTROL_SCHEMA); assert.equal(r.ok, true);
|
|
88
|
+
const line = JSON.parse(w.controls.trim().split("\n").pop());
|
|
89
|
+
assert.deepEqual({ ...line, after: undefined }, { at: "2023-11-14T22:13:20.000Z", actor: "op", host: "h1", verb: "hold", reason: "pause for incident", before: null, after: undefined, epoch: 1 });
|
|
90
|
+
assert.equal(line.after.reason, "pause for incident");
|
|
91
|
+
assert.match(w.comments[0], /FORGE:CONTROL/);
|
|
92
|
+
assert.equal(w.active.holds[RID].actor, "op");
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("hold is obeyed: fenced() refuses every irreversible action; resume lifts it", async () => {
|
|
96
|
+
const w = world();
|
|
97
|
+
const fence = { lctx: { io: w.io, repo: "o/r", credential: "driver" }, lease: w.active.lease, now: () => "t", record: async () => {} };
|
|
98
|
+
let ran = 0;
|
|
99
|
+
assert.equal((await fenced(fence, { action: "merge", key: "k" }, async () => { ran++; })).ok, true);
|
|
100
|
+
await runControl("hold", [RID, "--reason", "r"], base(w));
|
|
101
|
+
assert.match(await holdCheck(fence.lctx, RID), /held/);
|
|
102
|
+
const r = await fenced(fence, { action: "merge", key: "k2" }, async () => { ran++; });
|
|
103
|
+
assert.match(r.refused, /held/); assert.equal(ran, 1);
|
|
104
|
+
await runControl("resume", [RID, "--reason", "done"], base(w));
|
|
105
|
+
assert.equal((await fenced(fence, { action: "merge", key: "k3" }, async () => { ran++; })).ok, true);
|
|
106
|
+
assert.equal(ran, 2);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("cancel is refused once MERGED", async () => {
|
|
110
|
+
const w = world();
|
|
111
|
+
const orig = w.io.api;
|
|
112
|
+
w.io.api = async (m, p, b) => (/forge-ledger%2F|contents\/state\.json/.test(p) && m === "GET" && /state\.json/.test(p)
|
|
113
|
+
? { content: Buffer.from(JSON.stringify({ v: 1, id: RID, steps: { promotion: { done: true, result: { merged: true } } } })).toString("base64") } : orig(m, p, b));
|
|
114
|
+
const r = await runControl("cancel", [RID, "--reason", "r"], base(w));
|
|
115
|
+
assert.equal(r.ok, false); assert.match(r.error, /MERGED|no ledger/);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("lane force and freeze/unfreeze (the repo's own variable)", async () => {
|
|
119
|
+
const w = world();
|
|
120
|
+
assert.equal((await runControl("lane", ["#4", "#5", "--force", "exclude", "--reason", "r"], base(w))).ok, true);
|
|
121
|
+
assert.equal(w.active.lanes["4"].force, "exclude");
|
|
122
|
+
assert.match((await runControl("lane", ["#4", "--force", "bogus", "--reason", "r"], base(w))).error, /--force/);
|
|
123
|
+
assert.match((await runControl("freeze", ["--reason", "r"], base(w))).error, /freeze_variable/);
|
|
124
|
+
const policy = { deploy: { freeze_variable: "DEPLOY_FREEZE" } };
|
|
125
|
+
assert.equal((await runControl("freeze", ["--reason", "r"], base(w, { policy }))).ok, true);
|
|
126
|
+
assert.deepEqual(w.vars[0], ["variable", "set", "DEPLOY_FREEZE", "--repo", "o/r", "--body", "1"]);
|
|
127
|
+
assert.equal((await runControl("unfreeze", ["--reason", "r"], base(w, { policy }))).ok, true);
|
|
128
|
+
assert.equal(w.vars[1][1], "delete");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("I26: a dispatch with override_freeze or acknowledge_hotfix_revert is rejected", () => {
|
|
132
|
+
assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { override_freeze: "true" } }), /break-glass/);
|
|
133
|
+
assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { acknowledge_hotfix_revert: "1" } }), /break-glass/);
|
|
134
|
+
assert.deepEqual(buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { forge_epoch: 2 } }), ["workflow", "run", "p.yml", "--repo", "o/r", "--ref", "main", "-f", "forge_epoch=2"]);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("CLI: --json prints the stable schema; --repo is accepted; exit 1 on a refusal", async () => {
|
|
138
|
+
const w = world();
|
|
139
|
+
assert.equal(await controlFromCli("hold", [RID, "--repo", "o/r", "--reason", "r", "--json"], { io: w.io, actor: "op", host: "h" }), 0);
|
|
140
|
+
assert.equal(JSON.parse(w.out[0]).schema, CONTROL_SCHEMA);
|
|
141
|
+
assert.equal(await controlFromCli("hold", [RID, "--json"], { io: w.io }), 1);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Lease-epoch fencing (#5553, epic #5549 Phase 0, invariants I5/I7): every irreversible release action (merge, workflow
|
|
5
|
+
* dispatch, rerun, rollback, flag flip, intake release) re-reads `forge-ledger/_active`, aborts unless the lease is still this
|
|
6
|
+
* driver's epoch, records a write-ahead intent naming the epoch, re-checks immediately before acting, and hands the epoch to
|
|
7
|
+
* the effect so it travels with the action (`Forge-Epoch` merge trailer, `forge_epoch` dispatch input, comment marker).
|
|
8
|
+
* A host that cannot read `_active` performs nothing. Without a fence (unmanaged release) the effect just runs.
|
|
9
|
+
*/
|
|
10
|
+
import { readActive } from "./release-ledger.mjs";
|
|
11
|
+
import { holdCheck } from "./release-control.mjs";
|
|
12
|
+
|
|
13
|
+
export const epochTrailer = (epoch) => `Forge-Epoch: ${epoch}`;
|
|
14
|
+
export const epochMarker = (epoch) => `<!-- FORGE:EPOCH ${epoch} -->`;
|
|
15
|
+
|
|
16
|
+
/** @returns {{ok: true, epoch} | {fenced: true, current} | {unreadable: string}} */
|
|
17
|
+
export async function fenceCheck(ctx, lease) {
|
|
18
|
+
let active;
|
|
19
|
+
try { active = await readActive(ctx); } catch (e) { return { unreadable: String(e?.message ?? e) }; }
|
|
20
|
+
if (active?.lease?.holder !== lease.holder || active?.lease?.epoch !== lease.epoch) return { fenced: true, current: active?.epoch ?? null };
|
|
21
|
+
return { ok: true, epoch: lease.epoch };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** fenceCheck, then the hold flag of the lease's release (#5556, I24): `{refused}` or null. */
|
|
25
|
+
async function gate(ctx, lease) {
|
|
26
|
+
const c = await fenceCheck(ctx, lease);
|
|
27
|
+
if (!c.ok) return refusal(c, lease);
|
|
28
|
+
try { const h = await holdCheck(ctx, lease.release); return h ? `refused: ${h}` : null; } catch (e) { return refusal({ unreadable: String(e?.message ?? e) }, lease); }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const refusal = (c, lease) => (c.unreadable ? `refused: cannot read _active (${c.unreadable})` : `refused: fenced (epoch ${lease.epoch} is not current, ${c.current ?? "unknown"} is)`);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Run `effect(epoch)` only while `fence` ({lctx, lease, record, now}) is the current lease. `record` persists the intent before
|
|
35
|
+
* the effect (and its completion after). No fence: `effect(null)`.
|
|
36
|
+
* @returns {{ok: true, value} | {refused: string}} an effect error propagates
|
|
37
|
+
*/
|
|
38
|
+
export async function fenced(fence, { action, key }, effect) {
|
|
39
|
+
if (!fence) return { ok: true, value: await effect(null) };
|
|
40
|
+
const { lctx, lease } = fence;
|
|
41
|
+
let why = await gate(lctx, lease);
|
|
42
|
+
if (why) return { refused: why };
|
|
43
|
+
const intent = { key, action, epoch: lease.epoch, holder: lease.holder, at: fence.now() };
|
|
44
|
+
await fence.record(intent);
|
|
45
|
+
why = await gate(lctx, lease); // the window between the first read and the intent write is where a takeover can slip in
|
|
46
|
+
if (why) return { refused: why };
|
|
47
|
+
const value = await effect(lease.epoch);
|
|
48
|
+
await fence.record({ ...intent, done: true });
|
|
49
|
+
return { ok: true, value };
|
|
50
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
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 { readFileSync } from "node:fs";
|
|
6
|
+
import { postMergeStep } from "./release-postmerge.mjs";
|
|
7
|
+
import { fenceCheck, fenced, epochTrailer, epochMarker } from "./release-fence.mjs";
|
|
8
|
+
|
|
9
|
+
const mkCtx = (active) => ({ repo: "o/r", credential: "driver", io: { api: async (_m, path) => {
|
|
10
|
+
if (!/contents\/active\.json\?ref=_active$/.test(path)) throw new Error(`unrouted ${path}`);
|
|
11
|
+
if (active.get() instanceof Error) throw active.get();
|
|
12
|
+
return { content: Buffer.from(JSON.stringify(active.get())).toString("base64") };
|
|
13
|
+
} } });
|
|
14
|
+
const cell = (v) => ({ v, get() { return this.v; } });
|
|
15
|
+
const act = (holder, epoch) => ({ epoch, lease: { holder, epoch } });
|
|
16
|
+
const LEASE = { holder: "A", epoch: 1 };
|
|
17
|
+
const mkFence = (active, rec = []) => ({ lctx: mkCtx(active), lease: LEASE, now: () => "t", record: async (r) => { rec.push(r); } });
|
|
18
|
+
|
|
19
|
+
describe("release fence (#5553)", () => {
|
|
20
|
+
it("fenceCheck: ok for the current lease, fenced after a takeover, unreadable when _active cannot be read", async () => {
|
|
21
|
+
const a = cell(act("A", 1)), ctx = mkCtx(a);
|
|
22
|
+
assert.deepEqual(await fenceCheck(ctx, LEASE), { ok: true, epoch: 1 });
|
|
23
|
+
a.v = act("B", 2);
|
|
24
|
+
assert.deepEqual(await fenceCheck(ctx, LEASE), { fenced: true, current: 2 });
|
|
25
|
+
a.v = new Error("HTTP 503");
|
|
26
|
+
assert.match((await fenceCheck(ctx, LEASE)).unreadable, /503/);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("the intent is written before the effect, names the epoch, and the effect receives it", async () => {
|
|
30
|
+
const order = [], a = cell(act("A", 1)), f = mkFence(a);
|
|
31
|
+
f.record = async (r) => { order.push(`record:${r.action}:${r.epoch}:${!!r.done}`); };
|
|
32
|
+
const r = await fenced(f, { action: "merge", key: "k" }, async (e) => { order.push(`effect:${e}`); return "v"; });
|
|
33
|
+
assert.deepEqual(r, { ok: true, value: "v" });
|
|
34
|
+
assert.deepEqual(order, ["record:merge:1:false", "effect:1", "record:merge:1:true"]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("zombie: after a takeover the effect and the intent are never run", async () => {
|
|
38
|
+
const rec = [], a = cell(act("B", 2));
|
|
39
|
+
let ran = 0;
|
|
40
|
+
const r = await fenced(mkFence(a, rec), { action: "dispatch", key: "k" }, async () => { ran++; });
|
|
41
|
+
assert.match(r.refused, /fenced/);
|
|
42
|
+
assert.equal(ran, 0);
|
|
43
|
+
assert.equal(rec.length, 0);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("a takeover that slips in between the first read and the intent write is caught by the re-check", async () => {
|
|
47
|
+
const a = cell(act("A", 1)), f = mkFence(a);
|
|
48
|
+
f.record = async () => { a.v = act("B", 2); };
|
|
49
|
+
let ran = 0;
|
|
50
|
+
assert.match((await fenced(f, { action: "merge", key: "k" }, async () => { ran++; })).refused, /fenced/);
|
|
51
|
+
assert.equal(ran, 0);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("I5: an unreadable _active performs no irreversible action", async () => {
|
|
55
|
+
let ran = 0;
|
|
56
|
+
const r = await fenced(mkFence(cell(new Error("partition"))), { action: "rerun", key: "k" }, async () => { ran++; });
|
|
57
|
+
assert.match(r.refused, /cannot read _active/);
|
|
58
|
+
assert.equal(ran, 0);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("#5556 I24: a held release performs no irreversible action", async () => {
|
|
62
|
+
let ran = 0;
|
|
63
|
+
const a = cell({ ...act("A", 1), holds: { r1: { reason: "incident" } } });
|
|
64
|
+
const f = mkFence(a); f.lease = { holder: "A", epoch: 1, release: "r1" };
|
|
65
|
+
const r = await fenced(f, { action: "merge", key: "k" }, async () => { ran++; });
|
|
66
|
+
assert.match(r.refused, /held \(incident\)/);
|
|
67
|
+
assert.equal(ran, 0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("without a fence (unmanaged release) the effect just runs with no epoch", async () => {
|
|
71
|
+
assert.deepEqual(await fenced(null, { action: "merge", key: "k" }, async (e) => e), { ok: true, value: null });
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("the epoch carriers", () => {
|
|
75
|
+
assert.equal(epochTrailer(3), "Forge-Epoch: 3");
|
|
76
|
+
assert.equal(epochMarker(3), "<!-- FORGE:EPOCH 3 -->");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("publish.yml accepts forge_epoch and rejects a stale one as its first step", () => {
|
|
80
|
+
const y = readFileSync(new URL("../../.github/workflows/publish.yml", import.meta.url), "utf8");
|
|
81
|
+
assert.match(y, /workflow_dispatch:[^\n]*\n\s+inputs:\n\s+forge_epoch:/);
|
|
82
|
+
assert.match(y, / steps:\n - name: Reject a stale forge_epoch/);
|
|
83
|
+
assert.match(y, /ref=_active/);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("post-merge dispatch carries forge_epoch; a fenced host dispatches nothing", async () => {
|
|
87
|
+
const run = async (active) => {
|
|
88
|
+
const calls = []; let listed = 0;
|
|
89
|
+
const io = { print() {}, sleep: async () => {}, gh: async (a) => {
|
|
90
|
+
calls.push(a);
|
|
91
|
+
if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED", mergeCommit: { oid: "m".repeat(40) } });
|
|
92
|
+
if (a[0] === "run" && a[1] === "list") return JSON.stringify(++listed <= 2 ? [] : [{ databaseId: 5, status: "completed", conclusion: "success" }]);
|
|
93
|
+
return "";
|
|
94
|
+
} };
|
|
95
|
+
const ctx = { io, repo: "o/r", def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2 } }, state: { steps: { "release-pr": { result: { pr: 7 } } } }, fence: mkFence(cell(active)) };
|
|
96
|
+
return { out: await postMergeStep(ctx), calls };
|
|
97
|
+
};
|
|
98
|
+
const good = await run(act("A", 1));
|
|
99
|
+
assert.equal(good.out.published, true);
|
|
100
|
+
assert.deepEqual(good.calls.find((a) => a[0] === "workflow").slice(-2), ["-f", "forge_epoch=1"]);
|
|
101
|
+
const zombie = await run(act("B", 2));
|
|
102
|
+
assert.equal(zombie.out.blocked, true);
|
|
103
|
+
assert.equal(zombie.calls.some((a) => a[0] === "workflow"), false);
|
|
104
|
+
});
|
|
105
|
+
});
|