@intentius/chant 0.124.76 → 0.124.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
- package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
- package/dist/__fixtures__/agent-guard/plywood.js +19 -0
- package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
- package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
- package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
- package/dist/__fixtures__/gated-ledger.d.ts +10 -0
- package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
- package/dist/__fixtures__/gated-ledger.js +51 -0
- package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
- package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
- package/dist/__fixtures__/notify-messages/events.js +21 -0
- package/dist/__fixtures__/product-words.d.ts +14 -0
- package/dist/__fixtures__/product-words.d.ts.map +1 -1
- package/dist/__fixtures__/product-words.js +11 -0
- package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
- package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
- package/dist/__fixtures__/terragucci-notify.js +133 -0
- package/dist/action-pins.d.ts +8 -0
- package/dist/action-pins.d.ts.map +1 -1
- package/dist/action-pins.js +9 -0
- package/dist/agent-guard.d.ts +143 -0
- package/dist/agent-guard.d.ts.map +1 -0
- package/dist/agent-guard.js +455 -0
- package/dist/ci-commit.d.ts +120 -5
- package/dist/ci-commit.d.ts.map +1 -1
- package/dist/ci-commit.js +214 -23
- package/dist/ci-own-jobs.d.ts +81 -0
- package/dist/ci-own-jobs.d.ts.map +1 -0
- package/dist/ci-own-jobs.js +233 -0
- package/dist/ci-product-words.d.ts +18 -4
- package/dist/ci-product-words.d.ts.map +1 -1
- package/dist/ci-product-words.js +26 -6
- package/dist/ci-product.d.ts +40 -1
- package/dist/ci-product.d.ts.map +1 -1
- package/dist/ci-product.js +40 -1
- package/dist/cli/handlers/approve.d.ts +5 -1
- package/dist/cli/handlers/approve.d.ts.map +1 -1
- package/dist/cli/handlers/approve.js +17 -11
- package/dist/cli/handlers/build.d.ts +1 -1
- package/dist/cli/handlers/build.d.ts.map +1 -1
- package/dist/cli/handlers/build.js +88 -2
- package/dist/cli/handlers/commit.d.ts.map +1 -1
- package/dist/cli/handlers/commit.js +3 -1
- package/dist/cli/handlers/notify-relay.d.ts +18 -1
- package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
- package/dist/cli/handlers/notify-relay.js +90 -14
- package/dist/cli/handlers/pr.d.ts.map +1 -1
- package/dist/cli/handlers/pr.js +3 -1
- package/dist/cli/handlers/release.d.ts +5 -1
- package/dist/cli/handlers/release.d.ts.map +1 -1
- package/dist/cli/handlers/release.js +21 -9
- package/dist/cli/handlers/run-generate.d.ts.map +1 -1
- package/dist/cli/handlers/run-generate.js +2 -1
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +21 -1
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +60 -4
- package/dist/cli/registry.d.ts +16 -0
- package/dist/cli/registry.d.ts.map +1 -1
- package/dist/components/pr-env-components.d.ts +65 -0
- package/dist/components/pr-env-components.d.ts.map +1 -0
- package/dist/components/pr-env-components.js +162 -0
- package/dist/components/pr-policy.d.ts +15 -0
- package/dist/components/pr-policy.d.ts.map +1 -1
- package/dist/components/pr-policy.js +24 -1
- package/dist/components/release-compile.d.ts +15 -3
- package/dist/components/release-compile.d.ts.map +1 -1
- package/dist/components/release-compile.js +66 -15
- package/dist/config.d.ts +14 -8
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +16 -1
- package/dist/gate-policy.d.ts +14 -1
- package/dist/gate-policy.d.ts.map +1 -1
- package/dist/gate-policy.js +16 -6
- package/dist/lexicon.d.ts +25 -1
- package/dist/lexicon.d.ts.map +1 -1
- package/dist/lexicon.js +10 -0
- package/dist/lifecycle/gated-op.d.ts +95 -0
- package/dist/lifecycle/gated-op.d.ts.map +1 -0
- package/dist/lifecycle/gated-op.js +96 -0
- package/dist/lifecycle/git.d.ts.map +1 -1
- package/dist/lifecycle/git.js +83 -2
- package/dist/lifecycle/release-images.d.ts +77 -3
- package/dist/lifecycle/release-images.d.ts.map +1 -1
- package/dist/lifecycle/release-images.js +132 -6
- package/dist/notify-product.d.ts +11 -2
- package/dist/notify-product.d.ts.map +1 -1
- package/dist/notify-product.js +16 -4
- package/dist/notify-relay-repo.d.ts +131 -0
- package/dist/notify-relay-repo.d.ts.map +1 -0
- package/dist/notify-relay-repo.js +202 -0
- package/dist/notify-relay.d.ts +25 -1
- package/dist/notify-relay.d.ts.map +1 -1
- package/dist/notify-relay.js +27 -2
- package/dist/notify.d.ts +36 -4
- package/dist/notify.d.ts.map +1 -1
- package/dist/notify.js +31 -21
- package/dist/notify.schema.json +1 -0
- package/dist/op/activities/review-product.d.ts +111 -0
- package/dist/op/activities/review-product.d.ts.map +1 -0
- package/dist/op/activities/review-product.js +116 -0
- package/dist/op/op-waves-capability.js +2 -2
- package/dist/policy-engine.d.ts +95 -0
- package/dist/policy-engine.d.ts.map +1 -0
- package/dist/policy-engine.js +157 -0
- package/dist/pr-forge-reads.d.ts +124 -0
- package/dist/pr-forge-reads.d.ts.map +1 -0
- package/dist/pr-forge-reads.js +322 -0
- package/dist/pr-forge.d.ts +14 -0
- package/dist/pr-forge.d.ts.map +1 -1
- package/dist/pr-forge.js +21 -13
- package/dist/pr-plan-note.d.ts +293 -0
- package/dist/pr-plan-note.d.ts.map +1 -0
- package/dist/pr-plan-note.js +362 -0
- package/dist/release-floors.d.ts +9 -1
- package/dist/release-floors.d.ts.map +1 -1
- package/dist/release-floors.js +9 -1
- package/dist/state-export.d.ts +126 -0
- package/dist/state-export.d.ts.map +1 -0
- package/dist/state-export.js +156 -0
- package/dist/state-migration.d.ts +148 -0
- package/dist/state-migration.d.ts.map +1 -0
- package/dist/state-migration.js +146 -0
- package/dist/state-unlock.d.ts +167 -0
- package/dist/state-unlock.d.ts.map +1 -0
- package/dist/state-unlock.js +196 -0
- package/dist/wave-runtime.mjs +332 -332
- package/dist/workspace/declaration.schema.json +1 -1
- package/dist/workspace/release-workflow.d.ts +10 -0
- package/dist/workspace/release-workflow.d.ts.map +1 -1
- package/dist/workspace/release-workflow.js +10 -4
- package/package.json +1 -1
- package/src/__fixtures__/agent-guard/plywood.ts +27 -0
- package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
- package/src/__fixtures__/gated-ledger.ts +58 -0
- package/src/__fixtures__/notify-messages/events.ts +23 -0
- package/src/__fixtures__/notify-messages/messages.json +50 -0
- package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
- package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
- package/src/__fixtures__/product-words.ts +12 -0
- package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
- package/src/__fixtures__/terragucci-notify.ts +170 -0
- package/src/action-pins.test.ts +12 -1
- package/src/action-pins.ts +11 -0
- package/src/agent-guard.test.ts +319 -0
- package/src/agent-guard.ts +547 -0
- package/src/ci-commit.test.ts +213 -2
- package/src/ci-commit.ts +258 -27
- package/src/ci-own-jobs.test.ts +108 -0
- package/src/ci-own-jobs.ts +252 -0
- package/src/ci-product-words.ts +35 -7
- package/src/ci-product.ts +81 -1
- package/src/cli/handlers/approve-cwd.test.ts +112 -0
- package/src/cli/handlers/approve.ts +22 -11
- package/src/cli/handlers/build-own-jobs.test.ts +80 -0
- package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
- package/src/cli/handlers/build-run-group.test.ts +59 -0
- package/src/cli/handlers/build.ts +83 -3
- package/src/cli/handlers/commit.ts +3 -0
- package/src/cli/handlers/notify-relay.ts +99 -17
- package/src/cli/handlers/pr.ts +3 -1
- package/src/cli/handlers/release.ts +20 -10
- package/src/cli/handlers/run-generate.ts +2 -1
- package/src/cli/main.ts +21 -1
- package/src/cli/parse-args.ts +45 -3
- package/src/cli/registry.ts +16 -0
- package/src/components/pr-env-components.test.ts +137 -0
- package/src/components/pr-env-components.ts +213 -0
- package/src/components/pr-policy.test.ts +41 -1
- package/src/components/pr-policy.ts +25 -1
- package/src/components/release-compile.test.ts +47 -0
- package/src/components/release-compile.ts +70 -13
- package/src/config.ts +23 -3
- package/src/gate-policy-bundle.test.ts +14 -0
- package/src/gate-policy.test.ts +7 -0
- package/src/gate-policy.ts +22 -7
- package/src/lexicon.ts +28 -1
- package/src/lifecycle/gated-op.ts +158 -0
- package/src/lifecycle/git.test.ts +92 -0
- package/src/lifecycle/git.ts +71 -2
- package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
- package/src/lifecycle/release-images.ts +167 -8
- package/src/notify-message-words.test.ts +186 -0
- package/src/notify-product.ts +17 -4
- package/src/notify-relay-repo.test.ts +284 -0
- package/src/notify-relay-repo.ts +234 -0
- package/src/notify-relay.test.ts +12 -0
- package/src/notify-relay.ts +29 -3
- package/src/notify.schema.json +1 -0
- package/src/notify.ts +59 -19
- package/src/op/activities/review-product.test.ts +116 -0
- package/src/op/activities/review-product.ts +200 -0
- package/src/op/op-waves-capability.ts +2 -2
- package/src/op/schedule-overdue.test.ts +26 -0
- package/src/policy-engine.test.ts +162 -0
- package/src/policy-engine.ts +200 -0
- package/src/pr-forge-reads.test.ts +285 -0
- package/src/pr-forge-reads.ts +424 -0
- package/src/pr-forge.ts +30 -16
- package/src/pr-plan-note.test.ts +105 -0
- package/src/pr-plan-note.ts +521 -0
- package/src/release-floors.ts +13 -1
- package/src/state-export.test.ts +124 -0
- package/src/state-export.ts +227 -0
- package/src/state-migration.test.ts +133 -0
- package/src/state-migration.ts +236 -0
- package/src/state-unlock.test.ts +165 -0
- package/src/state-unlock.ts +293 -0
- package/src/workspace/declaration.schema.json +1 -1
- package/src/workspace/release-workflow.test.ts +34 -0
- package/src/workspace/release-workflow.ts +19 -4
|
@@ -7,6 +7,8 @@ import { describe, test, expect } from "vitest";
|
|
|
7
7
|
import { withTestDir } from "@intentius/chant-test-utils";
|
|
8
8
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { join } from "node:path";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
11
|
+
import { REPO } from "../workspace/__fixtures__/contract-repo";
|
|
10
12
|
import { CapabilityRegistry, type DeployContext } from "./capability";
|
|
11
13
|
import type { DriverComponent } from "./driver";
|
|
12
14
|
import {
|
|
@@ -15,6 +17,7 @@ import {
|
|
|
15
17
|
compileEnvironment,
|
|
16
18
|
recordedInputRefs,
|
|
17
19
|
ReleaseCompileError,
|
|
20
|
+
spawnTargetCompiler,
|
|
18
21
|
templateRefs,
|
|
19
22
|
withOnlyArchiveSteps,
|
|
20
23
|
} from "./release-compile";
|
|
@@ -179,3 +182,47 @@ describe("buildReleaseArtifacts", () => {
|
|
|
179
182
|
});
|
|
180
183
|
});
|
|
181
184
|
});
|
|
185
|
+
|
|
186
|
+
describe("spawnTargetCompiler (#4764)", () => {
|
|
187
|
+
const CHANT = [process.execPath, "--import", pathToFileURL(join(REPO, "node_modules", "tsx", "dist", "loader.mjs")).href, join(REPO, "packages", "core", "src", "cli", "main.ts")];
|
|
188
|
+
|
|
189
|
+
/** A component file that, with `--json` on the command line, prints a JSON document of its own on load; with `exit`, it then exits 0, as terragucci's scripts/coverage-gaps.ts did. */
|
|
190
|
+
function printingProject(dir: string, exit: boolean): void {
|
|
191
|
+
writeFileSync(
|
|
192
|
+
join(dir, "api.component.ts"),
|
|
193
|
+
`if (process.argv.includes("--json")) {
|
|
194
|
+
console.log(JSON.stringify({ gaps: [], total: 0 }));
|
|
195
|
+
${exit ? "process.exit(0);" : ""}
|
|
196
|
+
}
|
|
197
|
+
export const api = { name: "api", dependsOn: [], deploy: [{ phase: "Apply", steps: [{ kind: "cfn-deploy", template: "api.template.json" }] }] };
|
|
198
|
+
`,
|
|
199
|
+
);
|
|
200
|
+
writeFileSync(join(dir, "api.template.json"), `{"Resources":{}}`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
test("refuses by environment when a module the project loads prints JSON and exits, in place of the target", async () => {
|
|
204
|
+
await withTestDir(async (dir) => {
|
|
205
|
+
printingProject(dir, true);
|
|
206
|
+
const err = await spawnTargetCompiler({ projectDir: dir }, CHANT).compile("staging").catch((e: unknown) => e);
|
|
207
|
+
expect(err).toBeInstanceOf(ReleaseCompileError);
|
|
208
|
+
expect((err as Error).message).toMatch(/compiling "staging" printed something that is not a target/);
|
|
209
|
+
});
|
|
210
|
+
}, 60_000);
|
|
211
|
+
|
|
212
|
+
test("refuses by environment when the file the child writes is not a target", async () => {
|
|
213
|
+
await withTestDir(async (dir) => {
|
|
214
|
+
const child = [process.execPath, "-e", `require("node:fs").writeFileSync(process.env.CHANT_RELEASE_COMPILE_RESULT, JSON.stringify({ gaps: [] }))`];
|
|
215
|
+
await expect(spawnTargetCompiler({ projectDir: dir }, child).compile("prod")).rejects.toThrow(/compiling "prod" printed something that is not a target: its env is undefined/);
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("compiles the target when a module the project loads prints JSON and goes on", async () => {
|
|
220
|
+
await withTestDir(async (dir) => {
|
|
221
|
+
printingProject(dir, false);
|
|
222
|
+
const target = await spawnTargetCompiler({ projectDir: dir }, CHANT).compile("staging");
|
|
223
|
+
expect(target.env).toBe("staging");
|
|
224
|
+
expect(target.components).toEqual(["api"]);
|
|
225
|
+
expect(target.templates).toEqual([{ component: "api", path: "api.template.json", content: `{"Resources":{}}` }]);
|
|
226
|
+
});
|
|
227
|
+
}, 60_000);
|
|
228
|
+
});
|
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
* imported with a plain `import()`, which caches the module. So each
|
|
8
8
|
* environment is compiled in a child process of its own
|
|
9
9
|
* ({@link spawnTargetCompiler}), running `chant release compile --env <env>`,
|
|
10
|
-
* which calls {@link compileEnvironment} in that process and
|
|
11
|
-
* result as JSON
|
|
10
|
+
* which calls {@link compileEnvironment} in that process and writes the
|
|
11
|
+
* result as JSON to the file the parent names in
|
|
12
|
+
* {@link RELEASE_COMPILE_RESULT_ENV} (#4764), so a module the project loads
|
|
13
|
+
* that prints to stdout can't stand in for it. The artifacts are built in one more child, for the first
|
|
12
14
|
* environment in which each component is enabled ({@link buildReleaseArtifacts}).
|
|
13
15
|
*
|
|
14
16
|
* What counts as a template is data, as the build and publish kinds are in
|
|
@@ -39,8 +41,9 @@
|
|
|
39
41
|
|
|
40
42
|
import { spawn, spawnSync } from "node:child_process";
|
|
41
43
|
import { isUtf8 } from "node:buffer";
|
|
42
|
-
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
43
|
-
import {
|
|
44
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
45
|
+
import { tmpdir } from "node:os";
|
|
46
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
44
47
|
import { loadChantConfig, type ChantConfig } from "../config";
|
|
45
48
|
import { resolveFlaggedBuildParams } from "../flag-params";
|
|
46
49
|
import { discoverComponents } from "./discover";
|
|
@@ -562,6 +565,25 @@ export async function buildReleaseArtifacts(
|
|
|
562
565
|
return artifacts;
|
|
563
566
|
}
|
|
564
567
|
|
|
568
|
+
/**
|
|
569
|
+
* The variable that names the file `chant release compile` writes its result
|
|
570
|
+
* to (#4764). Without it the result goes to stdout, as it did before.
|
|
571
|
+
*/
|
|
572
|
+
export const RELEASE_COMPILE_RESULT_ENV = "CHANT_RELEASE_COMPILE_RESULT";
|
|
573
|
+
|
|
574
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
575
|
+
|
|
576
|
+
/** Why `value` is not the target `chant release compile --env <env>` writes, or undefined when it is one. */
|
|
577
|
+
export function notATarget(value: unknown, env: string): string | undefined {
|
|
578
|
+
if (!isRecord(value)) return "it is not an object";
|
|
579
|
+
if (value.env !== env) return `its env is ${JSON.stringify(value.env)}`;
|
|
580
|
+
if (!Array.isArray(value.components) || !value.components.every((c) => typeof c === "string")) return "it has no components list";
|
|
581
|
+
if (!Array.isArray(value.params)) return "it has no params list";
|
|
582
|
+
if (!Array.isArray(value.templates)) return "it has no templates list";
|
|
583
|
+
for (const field of ["buildSteps", "buildInputs", "componentFiles"]) if (!isRecord(value[field])) return `it has no ${field}`;
|
|
584
|
+
return undefined;
|
|
585
|
+
}
|
|
586
|
+
|
|
565
587
|
/** How {@link spawnTargetCompiler} starts this chant. */
|
|
566
588
|
export function ownChantCommand(): string[] {
|
|
567
589
|
const main = process.argv[1] ?? "";
|
|
@@ -575,6 +597,7 @@ function runChild(
|
|
|
575
597
|
env: string,
|
|
576
598
|
releaseLabel?: string,
|
|
577
599
|
releaseDigests?: string,
|
|
600
|
+
resultFile?: string,
|
|
578
601
|
): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
579
602
|
return new Promise((resolvePromise, reject) => {
|
|
580
603
|
const [bin, ...lead] = command;
|
|
@@ -584,6 +607,8 @@ function runChild(
|
|
|
584
607
|
delete childEnv[RELEASE_DIGESTS_ENV];
|
|
585
608
|
if (releaseLabel !== undefined) childEnv[RELEASE_LABEL_ENV] = releaseLabel;
|
|
586
609
|
if (releaseDigests !== undefined) childEnv[RELEASE_DIGESTS_ENV] = releaseDigests;
|
|
610
|
+
delete childEnv[RELEASE_COMPILE_RESULT_ENV];
|
|
611
|
+
if (resultFile !== undefined) childEnv[RELEASE_COMPILE_RESULT_ENV] = resultFile;
|
|
587
612
|
const child = spawn(bin, [...lead, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"], env: childEnv });
|
|
588
613
|
const out: Buffer[] = [];
|
|
589
614
|
const err: Buffer[] = [];
|
|
@@ -600,7 +625,10 @@ function runChild(
|
|
|
600
625
|
/**
|
|
601
626
|
* The compiler the CLI uses: each environment in a child process of this same
|
|
602
627
|
* chant (`chant release compile --env <env> --json`), with `CHANT_ENV` set to
|
|
603
|
-
* that environment before anything imports the project.
|
|
628
|
+
* that environment before anything imports the project. The child writes its
|
|
629
|
+
* result to a file this process names (#4764), and the result is checked for
|
|
630
|
+
* the target's shape, so a project module that prints JSON on load, or prints
|
|
631
|
+
* it and exits, is refused by the environment's name.
|
|
604
632
|
*/
|
|
605
633
|
export function spawnTargetCompiler(inputs: CompileInputs, command: readonly string[] = ownChantCommand()): TargetCompiler {
|
|
606
634
|
const common = (): string[] => {
|
|
@@ -612,21 +640,50 @@ export function spawnTargetCompiler(inputs: CompileInputs, command: readonly str
|
|
|
612
640
|
if (inputs.paramsFile) args.push("--params-file", inputs.paramsFile);
|
|
613
641
|
return args;
|
|
614
642
|
};
|
|
615
|
-
const call = async (env: string, extra: string[]): Promise<unknown> => {
|
|
616
|
-
const
|
|
617
|
-
|
|
643
|
+
const call = async (env: string, extra: string[], what: string, check: (value: unknown) => string | undefined): Promise<unknown> => {
|
|
644
|
+
const dir = mkdtempSync(join(tmpdir(), "chant-release-compile-"));
|
|
645
|
+
const resultFile = join(dir, "result.json");
|
|
618
646
|
try {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
647
|
+
const run = await runChild(
|
|
648
|
+
command,
|
|
649
|
+
["release", "compile", "--env", env, ...common(), ...extra, "--json"],
|
|
650
|
+
inputs.projectDir,
|
|
651
|
+
env,
|
|
652
|
+
inputs.releaseLabel,
|
|
653
|
+
inputs.releaseDigests,
|
|
654
|
+
resultFile,
|
|
655
|
+
);
|
|
656
|
+
if (run.code !== 0) throw new ReleaseCompileError(`compiling "${env}" failed (exit ${run.code})`);
|
|
657
|
+
const printed = run.stdout.trim();
|
|
658
|
+
const stdoutNote = printed === "" ? "" : `; its stdout began: ${printed.length > 200 ? `${printed.slice(0, 200)}...` : printed}`;
|
|
659
|
+
if (!existsSync(resultFile)) {
|
|
660
|
+
throw new ReleaseCompileError(
|
|
661
|
+
`compiling "${env}" ${printed === "" ? `exited 0 without writing ${what}` : `printed something that is not ${what} and exited 0 without writing one`}; ` +
|
|
662
|
+
`a module the project loads may have exited on load (for a project with no components, set sourceDir or --src to the build root)${stdoutNote}`,
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
let value: unknown;
|
|
666
|
+
try {
|
|
667
|
+
value = JSON.parse(readFileSync(resultFile, "utf-8"));
|
|
668
|
+
} catch {
|
|
669
|
+
throw new ReleaseCompileError(`compiling "${env}" wrote something that is not JSON`);
|
|
670
|
+
}
|
|
671
|
+
const why = check(value);
|
|
672
|
+
if (why !== undefined) throw new ReleaseCompileError(`compiling "${env}" printed something that is not ${what}: ${why}${stdoutNote}`);
|
|
673
|
+
return value;
|
|
674
|
+
} finally {
|
|
675
|
+
rmSync(dir, { recursive: true, force: true });
|
|
622
676
|
}
|
|
623
677
|
};
|
|
624
678
|
return {
|
|
625
679
|
async compile(env) {
|
|
626
|
-
return (await call(env, inputs.buildCommand ? ["--build", inputs.buildCommand] : [])) as CompiledTarget;
|
|
680
|
+
return (await call(env, inputs.buildCommand ? ["--build", inputs.buildCommand] : [], "a target", (v) => notATarget(v, env))) as CompiledTarget;
|
|
627
681
|
},
|
|
628
682
|
async buildArtifacts(env, components) {
|
|
629
|
-
|
|
683
|
+
const result = await call(env, ["--artifacts", "--component", components.join(",")], "a list of artifacts", (v) =>
|
|
684
|
+
isRecord(v) && Array.isArray(v.artifacts) ? undefined : "it has no artifacts list",
|
|
685
|
+
);
|
|
686
|
+
return (result as { artifacts: ReleaseArtifact[] }).artifacts;
|
|
630
687
|
},
|
|
631
688
|
};
|
|
632
689
|
}
|
package/src/config.ts
CHANGED
|
@@ -109,7 +109,24 @@ export const ChantConfigSchema = z.object({
|
|
|
109
109
|
release: z.object({
|
|
110
110
|
autoRecord: z.boolean().optional(),
|
|
111
111
|
publish: z.array(PublishDeclarationSchema).optional(),
|
|
112
|
-
images: z
|
|
112
|
+
images: z
|
|
113
|
+
.array(
|
|
114
|
+
z.union([
|
|
115
|
+
z.object({ name: z.string().min(1), build: z.string().min(1), archive: z.string().min(1) }).strict(),
|
|
116
|
+
// #4819: chant builds the Dockerfile as the reproducible OCI archive itself.
|
|
117
|
+
z
|
|
118
|
+
.object({
|
|
119
|
+
name: z.string().min(1),
|
|
120
|
+
dockerfile: z.string().min(1),
|
|
121
|
+
context: z.string().min(1).optional(),
|
|
122
|
+
platforms: z.array(z.string().min(1)).min(1).optional(),
|
|
123
|
+
archive: z.string().min(1).optional(),
|
|
124
|
+
prepare: z.string().min(1).optional(),
|
|
125
|
+
})
|
|
126
|
+
.strict(),
|
|
127
|
+
]),
|
|
128
|
+
)
|
|
129
|
+
.optional(),
|
|
113
130
|
lane: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, "a ci.green lane name: lowercase letters, digits and dashes").optional(),
|
|
114
131
|
workflow: z.object({
|
|
115
132
|
trigger: z.enum(["tag", "dispatch"]).optional(),
|
|
@@ -393,9 +410,12 @@ export interface ChantConfig {
|
|
|
393
410
|
* `build` writes the OCI archive at `archive`, and the cut records its
|
|
394
411
|
* digest and hands every digest to the build through `CHANT_RELEASE_DIGESTS`,
|
|
395
412
|
* so a package can pin the images it ships with. An `oci` target pushes
|
|
396
|
-
* the archive.
|
|
413
|
+
* the archive. An entry may name a `dockerfile` (with `context`,
|
|
414
|
+
* `platforms`, `archive` and `prepare`) in place of `build`, and chant
|
|
415
|
+
* runs the reproducible build itself (#4819). See
|
|
416
|
+
* ./lifecycle/release-images.ts.
|
|
397
417
|
*/
|
|
398
|
-
images?:
|
|
418
|
+
images?: import("./lifecycle/release-images").ReleaseImageDeclaration[];
|
|
399
419
|
/**
|
|
400
420
|
* The green lane `chant release cut` and `chant release candidates` check
|
|
401
421
|
* when `--lane` is not given (#4692): one `ci.green.lanes` declares in
|
|
@@ -25,4 +25,18 @@ describe("the gate-policy bundle", () => {
|
|
|
25
25
|
expect(Object.keys(result.metafile.inputs).map((i) => i.replace(/^.*?packages\//, "packages/"))).toEqual(["packages/core/src/gate-policy.ts"]);
|
|
26
26
|
expect(result.outputFiles.reduce((n, f) => n + f.contents.byteLength, 0)).toBeLessThan(16 * 1024);
|
|
27
27
|
});
|
|
28
|
+
|
|
29
|
+
test("the policy engine install (#4774) bundles with only the release floor beside it", async () => {
|
|
30
|
+
const result = await build({
|
|
31
|
+
entryPoints: [join(REPO, "packages", "core", "src", "policy-engine.ts")],
|
|
32
|
+
bundle: true,
|
|
33
|
+
platform: "node",
|
|
34
|
+
format: "esm",
|
|
35
|
+
write: false,
|
|
36
|
+
metafile: true,
|
|
37
|
+
outdir: "out",
|
|
38
|
+
logLevel: "silent",
|
|
39
|
+
});
|
|
40
|
+
expect(Object.keys(result.metafile.inputs).map((i) => i.replace(/^.*?packages\//, "packages/")).sort()).toEqual(["packages/core/src/policy-engine.ts"]);
|
|
41
|
+
});
|
|
28
42
|
});
|
package/src/gate-policy.test.ts
CHANGED
|
@@ -91,6 +91,10 @@ describe("running the engine (#4294)", () => {
|
|
|
91
91
|
expect(gatePolicyArgv({ engine: "conftest", namespace: "infra" }, { policy: "/p", input: "/i.json" })).toContain("--namespace");
|
|
92
92
|
expect(gatePolicyArgv({ engine: "opa" }, { policy: "/p", input: "/i.json" })).toEqual(["opa", "eval", "--format", "json", "--data", "/p", "--input", "/i.json", "data.main"]);
|
|
93
93
|
expect(gatePolicyArgv({ engine: "opa", command: ["./bin/check", "--rules={policy}", "{input}"] }, { policy: "/p", input: "/i.json" })).toEqual(["./bin/check", "--rules=/p", "/i.json"]);
|
|
94
|
+
// #4774: an installed engine runs from where it was installed; a command ignores it.
|
|
95
|
+
expect(gatePolicyArgv({ engine: "opa" }, { policy: "/p", input: "/i.json", binary: "/cache/opa-1.21.4-linux-x64/opa" })[0]).toBe("/cache/opa-1.21.4-linux-x64/opa");
|
|
96
|
+
expect(gatePolicyArgv({}, { policy: "/p", input: "/i.json", binary: "/cache/conftest" })[0]).toBe("/cache/conftest");
|
|
97
|
+
expect(gatePolicyArgv({ command: ["./bin/check", "{input}"] }, { policy: "/p", input: "/i.json", binary: "/cache/conftest" })[0]).toBe("./bin/check");
|
|
94
98
|
});
|
|
95
99
|
|
|
96
100
|
test("the input is written to the file the engine reads, and a denial is a verdict with its sorted rules", () => {
|
|
@@ -157,6 +161,9 @@ describe("ci.policy settings (#4294)", () => {
|
|
|
157
161
|
expect(() => assertGatePolicySettings("ci.policy", { outcomes: ["deny", "allow_unattended"] })).toThrow(/no unattended outcome/);
|
|
158
162
|
expect(() => assertGatePolicySettings("ci.policy", { allow_unattended: true })).toThrow(/no unattended outcome/);
|
|
159
163
|
expect(() => assertGatePolicySettings("ci.policy", { rules: [] })).toThrow(/not a setting/);
|
|
164
|
+
expect(() => assertGatePolicySettings("ci.policy", { engine: "opa", install: true })).not.toThrow();
|
|
165
|
+
expect(() => assertGatePolicySettings("ci.policy", { install: "yes" })).toThrow(/install must be true or false/);
|
|
166
|
+
expect(() => assertGatePolicySettings("ci.policy", { install: true, command: ["./check", "{input}"] })).toThrow(/install and ci.policy.command cannot both be set/);
|
|
160
167
|
expect(() => assertGatePolicySettings("ci.policy", [])).toThrow(/must be/);
|
|
161
168
|
});
|
|
162
169
|
});
|
package/src/gate-policy.ts
CHANGED
|
@@ -120,6 +120,12 @@ export interface GatePolicySettings {
|
|
|
120
120
|
* prints the result shape `engine` names.
|
|
121
121
|
*/
|
|
122
122
|
command?: string[];
|
|
123
|
+
/**
|
|
124
|
+
* Fetch the engine when it is not on PATH (#4774): conftest or OPA at the
|
|
125
|
+
* release chant pins, checked against its recorded sha256
|
|
126
|
+
* (`./policy-engine.ts`). Refused beside `command`, which names its own.
|
|
127
|
+
*/
|
|
128
|
+
install?: boolean;
|
|
123
129
|
}
|
|
124
130
|
|
|
125
131
|
/** One CrossGuard pack named by `ci.policy.packs`. */
|
|
@@ -251,13 +257,17 @@ export function gatePolicyVerdict(engine: GatePolicyEngine, found: GatePolicyFin
|
|
|
251
257
|
|
|
252
258
|
const errorVerdict = (engine: GatePolicyEngine, error: string): GatePolicyVerdict => ({ result: "error", engine, denials: [], rules: [], holds: [], warnings: [], error });
|
|
253
259
|
|
|
254
|
-
/**
|
|
255
|
-
|
|
260
|
+
/**
|
|
261
|
+
* The argv one check runs: the settings' `command` with its placeholders
|
|
262
|
+
* filled, or the engine's own. `binary` is the engine's executable when it
|
|
263
|
+
* is not the one on PATH, such as one `./policy-engine.ts` installed.
|
|
264
|
+
*/
|
|
265
|
+
export function gatePolicyArgv(settings: GatePolicySettings, at: { policy: string; input: string; binary?: string }): string[] {
|
|
256
266
|
if (settings.command) return settings.command.map((a) => a.replaceAll("{policy}", at.policy).replaceAll("{input}", at.input));
|
|
257
267
|
if ((settings.engine ?? "conftest") === "opa") {
|
|
258
|
-
return ["opa", "eval", "--format", "json", "--data", at.policy, "--input", at.input, `data.${settings.namespace ?? "main"}`];
|
|
268
|
+
return [at.binary ?? "opa", "eval", "--format", "json", "--data", at.policy, "--input", at.input, `data.${settings.namespace ?? "main"}`];
|
|
259
269
|
}
|
|
260
|
-
return ["conftest", "test", "--no-color", "--output", "json", "--policy", at.policy, ...(settings.namespace ? ["--namespace", settings.namespace] : ["--all-namespaces"]), at.input];
|
|
270
|
+
return [at.binary ?? "conftest", "test", "--no-color", "--output", "json", "--policy", at.policy, ...(settings.namespace ? ["--namespace", settings.namespace] : ["--all-namespaces"]), at.input];
|
|
261
271
|
}
|
|
262
272
|
|
|
263
273
|
/** What one run of the engine printed and how it exited. `status` is null when it did not start. */
|
|
@@ -284,6 +294,8 @@ export interface CheckGatePolicyOptions {
|
|
|
284
294
|
/** Where the engine runs. Default the policy directory. */
|
|
285
295
|
cwd?: string;
|
|
286
296
|
exec?: GatePolicyExec;
|
|
297
|
+
/** The engine's executable, when it is not the one on PATH. Not used with `command`. */
|
|
298
|
+
binary?: string;
|
|
287
299
|
}
|
|
288
300
|
|
|
289
301
|
const tail = (text: string): string => text.trim().split("\n").slice(-3).join(" ");
|
|
@@ -296,7 +308,7 @@ export function checkGatePolicy(options: CheckGatePolicyOptions): GatePolicyVerd
|
|
|
296
308
|
try {
|
|
297
309
|
const file = join(work, "input.json");
|
|
298
310
|
writeFileSync(file, typeof options.input === "string" ? options.input : JSON.stringify(options.input));
|
|
299
|
-
const argv = gatePolicyArgv(settings, { policy: options.policyDir, input: file });
|
|
311
|
+
const argv = gatePolicyArgv(settings, { policy: options.policyDir, input: file, ...(options.binary ? { binary: options.binary } : {}) });
|
|
300
312
|
const r = (options.exec ?? defaultGatePolicyExec)(argv, options.cwd ?? options.policyDir);
|
|
301
313
|
if (r.status === null) return errorVerdict(engine, `${argv[0]} did not run: ${tail(r.stderr) || "no such command"}`);
|
|
302
314
|
const found = engine === "opa" ? opaFindings(r.stdout, settings.namespace ?? "main") : conftestFindings(r.stdout);
|
|
@@ -353,7 +365,8 @@ export function exportGatePolicy(tree: GatePolicyTree, path: string): { dir: str
|
|
|
353
365
|
|
|
354
366
|
/** The settings, checked. Throws with what is wrong. `where` names them, such as `ci.policy`. */
|
|
355
367
|
export function assertGatePolicySettings(where: string, raw: unknown): asserts raw is GatePolicySettings {
|
|
356
|
-
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${where} must be { engine?, path?, source?, namespace?, command?, packs? }`);
|
|
368
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${where} must be { engine?, path?, source?, namespace?, command?, packs?, install? }`);
|
|
369
|
+
if ("install" in raw && "command" in raw) throw new Error(`${where}.install and ${where}.command cannot both be set; install fetches conftest or opa, and the command names its own executable`);
|
|
357
370
|
if ("path" in raw && "source" in raw) throw new Error(`${where}.path and ${where}.source cannot both be set; with a source, ${where}.source.path names the directory inside it`);
|
|
358
371
|
for (const [key, value] of Object.entries(raw)) {
|
|
359
372
|
if (key === "engine") {
|
|
@@ -378,10 +391,12 @@ export function assertGatePolicySettings(where: string, raw: unknown): asserts r
|
|
|
378
391
|
} else if (key === "command") {
|
|
379
392
|
if (!Array.isArray(value) || value.length === 0 || !value.every((a) => typeof a === "string" && a !== "")) throw new Error(`${where}.command must be argv, a non-empty list of strings`);
|
|
380
393
|
if (!value.some((a: string) => a.includes("{input}"))) throw new Error(`${where}.command must pass the input file as {input}`);
|
|
394
|
+
} else if (key === "install") {
|
|
395
|
+
if (typeof value !== "boolean") throw new Error(`${where}.install must be true or false`);
|
|
381
396
|
} else if (key === "outcomes" || key === "allow_unattended" || key === "allowUnattended") {
|
|
382
397
|
throw new Error(`${where}.${key}: chant's policy step denies and holds only; a non-empty plan always waits for a person (ws-104), so there is no unattended outcome`);
|
|
383
398
|
} else {
|
|
384
|
-
throw new Error(`${where}.${key} is not a setting; the settings are engine, path, source, namespace, command and
|
|
399
|
+
throw new Error(`${where}.${key} is not a setting; the settings are engine, path, source, namespace, command, packs and install`);
|
|
385
400
|
}
|
|
386
401
|
}
|
|
387
402
|
}
|
package/src/lexicon.ts
CHANGED
|
@@ -47,6 +47,7 @@ import type { DisruptionQuery, DisruptionVerdict } from "./lifecycle/disruption"
|
|
|
47
47
|
import type { OwnerChainVerdict } from "./owner-chain";
|
|
48
48
|
import type { CommandGroup } from "./cli/command-group";
|
|
49
49
|
import type { Archetype } from "./components/component";
|
|
50
|
+
import { NEXT_RELEASE } from "./release-floors";
|
|
50
51
|
|
|
51
52
|
// Re-exported so a lexicon that hosts Op runs (#2121) can type its
|
|
52
53
|
// `opRuntime` from the same entry it imports the plugin contract from.
|
|
@@ -547,8 +548,25 @@ export interface ComponentPipelineJob {
|
|
|
547
548
|
needs: string[];
|
|
548
549
|
}
|
|
549
550
|
|
|
551
|
+
/**
|
|
552
|
+
* What a Forgejo workflow's run group is keyed on (#4771): `commit`, one
|
|
553
|
+
* group per event and commit, so a merge's run is never cancelled by another
|
|
554
|
+
* commit's; `pull-request`, one group per run except that a pull request's
|
|
555
|
+
* runs share one and cancel each other.
|
|
556
|
+
*/
|
|
557
|
+
export type RunGroupKey = "commit" | "pull-request";
|
|
558
|
+
export const RUN_GROUP_KEYS: readonly RunGroupKey[] = ["commit", "pull-request"];
|
|
559
|
+
|
|
550
560
|
/** Generic knobs for generate mode, applied once across every generated job (never per component). */
|
|
551
561
|
export interface ComponentPipelineOptions {
|
|
562
|
+
/**
|
|
563
|
+
* A workflow-level run group (#4771), written on Forgejo only. Forgejo
|
|
564
|
+
* gives a workflow with no workflow-level `concurrency:` a group per ref,
|
|
565
|
+
* workflow and event, and cancels the run in progress when a push starts
|
|
566
|
+
* another. GitHub cancels nothing without a group and GitLab's jobs are not
|
|
567
|
+
* `interruptible`, so their files are unchanged. Unset, no group.
|
|
568
|
+
*/
|
|
569
|
+
runGroup?: RunGroupKey;
|
|
552
570
|
/** Target environment threaded into the trigger command. */
|
|
553
571
|
env?: string;
|
|
554
572
|
/** The trigger command per component, argv with `{name}` substituted. */
|
|
@@ -1105,7 +1123,7 @@ export interface OpPipelineResult {
|
|
|
1105
1123
|
* of the spec file the jobs read.
|
|
1106
1124
|
*/
|
|
1107
1125
|
export interface OpWavesPipelineOptions
|
|
1108
|
-
extends Pick<ComponentPipelineOptions, "image" | "beforeScript" | "extraScript" | "variables" | "opsStage" | "opsFileName"> {
|
|
1126
|
+
extends Pick<ComponentPipelineOptions, "image" | "beforeScript" | "extraScript" | "variables" | "opsStage" | "opsFileName" | "runGroup"> {
|
|
1109
1127
|
/** The spec's path from the repository root. Every job runs `chant run wave --spec <specFile>`. */
|
|
1110
1128
|
specFile: string;
|
|
1111
1129
|
/**
|
|
@@ -1297,6 +1315,15 @@ export interface CompositeEntry {
|
|
|
1297
1315
|
archetype?: Archetype;
|
|
1298
1316
|
}
|
|
1299
1317
|
|
|
1318
|
+
/**
|
|
1319
|
+
* The first chant whose Pulumi lexicon's ci-setup installs a release without
|
|
1320
|
+
* linking it onto PATH (`link: false`) and exports the fetch-and-check script
|
|
1321
|
+
* for image builds (`ciFetchScript`, #4814). It lives here, beside
|
|
1322
|
+
* {@link LexiconPlugin.ciSetup}, so it freezes with chant's release; the
|
|
1323
|
+
* lexicon re-exports it as `PULUMI_CI_SETUP_FLOOR`.
|
|
1324
|
+
*/
|
|
1325
|
+
export const CI_SETUP_UNLINKED_FLOOR = NEXT_RELEASE;
|
|
1326
|
+
|
|
1300
1327
|
export interface LexiconPlugin {
|
|
1301
1328
|
// ── Required ──────────────────────────────────────────────
|
|
1302
1329
|
/** Human-readable name (e.g. "aws", "gcp") */
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One gated operation outside op waves (#4762): ask for a gated request
|
|
3
|
+
* (#4551), spend its approval, act, and record how it ended. The walk every
|
|
4
|
+
* engine's state operation shares: a Terraform root's export or lock
|
|
5
|
+
* release, a Pulumi stack's, a migration whose request carries its proof.
|
|
6
|
+
*
|
|
7
|
+
* It came from the terraform lexicon's `state-ops.ts` (#4618), which still
|
|
8
|
+
* exports it as `gatedStateOp`, so a product written against the lexicon
|
|
9
|
+
* keeps working.
|
|
10
|
+
*
|
|
11
|
+
* A request asked again binds the same digest: chant's digest covers the
|
|
12
|
+
* request's `at`, so {@link requestedAt} reuses the `at` of the newest
|
|
13
|
+
* standing, unspent request with the same kind, subject, requester and
|
|
14
|
+
* fields. The spend is pushed before `act` runs, so no approval acts twice.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import {
|
|
18
|
+
finishGatedRequest,
|
|
19
|
+
readGatedRequests,
|
|
20
|
+
requestGate,
|
|
21
|
+
spendGatedRequest,
|
|
22
|
+
type GatedRequest,
|
|
23
|
+
type GatedRequestRules,
|
|
24
|
+
type RequestGateInput,
|
|
25
|
+
type RequestGateResult,
|
|
26
|
+
} from "./gated-request";
|
|
27
|
+
|
|
28
|
+
/** The gated-request ledger, injectable for tests. Default chant's on `chant/lifecycle`. */
|
|
29
|
+
export interface GatedRequestLedger {
|
|
30
|
+
requestGate: typeof requestGate;
|
|
31
|
+
spendGatedRequest: typeof spendGatedRequest;
|
|
32
|
+
finishGatedRequest: typeof finishGatedRequest;
|
|
33
|
+
readGatedRequests: typeof readGatedRequests;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** chant's ledger on `chant/lifecycle`. */
|
|
37
|
+
export const chantGatedLedger: GatedRequestLedger = { requestGate, spendGatedRequest, finishGatedRequest, readGatedRequests };
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The time a request was first asked, so asking again binds the same
|
|
41
|
+
* digest. The newest standing, unspent request with the same kind, subject,
|
|
42
|
+
* requester and fields gives its `at`; with none, `now`.
|
|
43
|
+
*/
|
|
44
|
+
export async function requestedAt(
|
|
45
|
+
op: string,
|
|
46
|
+
request: Omit<GatedRequest, "at">,
|
|
47
|
+
options: { now?: string; cwd?: string; ledger?: Pick<GatedRequestLedger, "readGatedRequests"> } = {},
|
|
48
|
+
): Promise<string> {
|
|
49
|
+
const now = options.now ?? new Date().toISOString();
|
|
50
|
+
const read = await (options.ledger ?? chantGatedLedger).readGatedRequests(op, options.cwd ? { cwd: options.cwd } : undefined).catch(() => []);
|
|
51
|
+
const same = JSON.stringify(Object.entries(request.fields).sort());
|
|
52
|
+
const standing = read
|
|
53
|
+
.filter((g) => !g.applied && g.request.kind === request.kind && g.request.subject === request.subject && g.request.by === request.by)
|
|
54
|
+
.filter((g) => JSON.stringify(Object.entries(g.request.fields).sort()) === same)
|
|
55
|
+
.filter((g) => !g.pending.expiresAt || g.pending.expiresAt > now)
|
|
56
|
+
.at(-1);
|
|
57
|
+
return standing?.request.at ?? now;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The digest `requestGate` puts in `fields.proof` for an attachment. */
|
|
61
|
+
export const attachmentDigest = (attachment: string): string => `sha256:${createHash("sha256").update(attachment).digest("hex")}`;
|
|
62
|
+
|
|
63
|
+
export interface GatedOpInput {
|
|
64
|
+
op: string;
|
|
65
|
+
/** The request, less `at`, which {@link requestedAt} fills. */
|
|
66
|
+
request: Omit<GatedRequest, "at"> & { at?: string };
|
|
67
|
+
rules: GatedRequestRules;
|
|
68
|
+
description?: string;
|
|
69
|
+
expiry?: string;
|
|
70
|
+
base?: string;
|
|
71
|
+
/** A document the request carries, such as a migration's proof; its digest joins the request. */
|
|
72
|
+
attachment?: string;
|
|
73
|
+
cwd?: string;
|
|
74
|
+
now?: string;
|
|
75
|
+
runId?: string;
|
|
76
|
+
commit?: string;
|
|
77
|
+
ledger?: GatedRequestLedger;
|
|
78
|
+
gates?: RequestGateInput["gates"];
|
|
79
|
+
/**
|
|
80
|
+
* A last check just before the spend, for a fact that can change while the
|
|
81
|
+
* request waited (a run that may hold the lock came back). A string refuses
|
|
82
|
+
* the operation with that reason, and the approval is not spent.
|
|
83
|
+
*/
|
|
84
|
+
beforeSpend?: () => Promise<string | undefined>;
|
|
85
|
+
/** The flat facts of a failed act's finished line, beside its `error`, such as the binary's exit code and last lines. */
|
|
86
|
+
failedDetail?: (error: Error) => Record<string, string | number | boolean>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** How a gated operation ended. Only `done` and `failed` acted. */
|
|
90
|
+
export type GatedOpResult<T> =
|
|
91
|
+
| Exclude<RequestGateResult, { status: "approved" }>
|
|
92
|
+
| { status: "held"; digest: string; request: GatedRequest; reason: string }
|
|
93
|
+
| { status: "done"; digest: string; request: GatedRequest; approvedBy: string; output: T; recorded: boolean }
|
|
94
|
+
| { status: "failed"; digest: string; request: GatedRequest; approvedBy: string; error: Error; recorded: boolean };
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* What an approved operation's act returns: its output, and the flat facts
|
|
98
|
+
* its finished line records. `failed` records the finished line as failed
|
|
99
|
+
* while the output still comes back, for an act that ran and did not succeed
|
|
100
|
+
* (a migration whose write left a change).
|
|
101
|
+
*/
|
|
102
|
+
export type GatedOpAct<T> = (approved: { digest: string; request: GatedRequest; approvedBy: string }) => Promise<{ output: T; detail?: Record<string, string | number | boolean>; failed?: boolean }>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Run `act` once its request is approved: ask (or read) the request, spend
|
|
106
|
+
* the approval, act, and record how it ended. A spend that cannot be pushed
|
|
107
|
+
* throws before `act` runs. A finished line that cannot be written is
|
|
108
|
+
* reported as `recorded: false`; the act already ran.
|
|
109
|
+
*/
|
|
110
|
+
export async function gatedOp<T>(input: GatedOpInput, act: GatedOpAct<T>): Promise<GatedOpResult<T>> {
|
|
111
|
+
const ledger = input.ledger ?? chantGatedLedger;
|
|
112
|
+
// The proof's digest is a field of the stored request, so the standing request is matched with it.
|
|
113
|
+
const fields = input.attachment !== undefined ? { ...input.request.fields, proof: attachmentDigest(input.attachment) } : input.request.fields;
|
|
114
|
+
const at = input.request.at ?? (await requestedAt(input.op, { ...input.request, fields }, { ...(input.now ? { now: input.now } : {}), ...(input.cwd ? { cwd: input.cwd } : {}), ledger }));
|
|
115
|
+
const request: GatedRequest = { kind: input.request.kind, subject: input.request.subject, by: input.request.by, at, fields };
|
|
116
|
+
const asked = await ledger.requestGate({
|
|
117
|
+
op: input.op,
|
|
118
|
+
request,
|
|
119
|
+
rules: input.rules,
|
|
120
|
+
...(input.description ? { description: input.description } : {}),
|
|
121
|
+
...(input.expiry ? { expiry: input.expiry } : {}),
|
|
122
|
+
...(input.base ? { base: input.base } : {}),
|
|
123
|
+
...(input.attachment !== undefined ? { attachment: input.attachment } : {}),
|
|
124
|
+
...(input.cwd ? { cwd: input.cwd } : {}),
|
|
125
|
+
...(input.now ? { now: input.now } : {}),
|
|
126
|
+
...(input.gates ? { gates: input.gates } : {}),
|
|
127
|
+
});
|
|
128
|
+
if (asked.status !== "approved") return asked;
|
|
129
|
+
const { digest } = asked;
|
|
130
|
+
const approvedBy = asked.approval.resolvedBy;
|
|
131
|
+
const held = await input.beforeSpend?.();
|
|
132
|
+
if (held) return { status: "held", digest, request: asked.request, reason: held };
|
|
133
|
+
const spent = await ledger.spendGatedRequest({
|
|
134
|
+
op: input.op,
|
|
135
|
+
gate: request.subject,
|
|
136
|
+
digest,
|
|
137
|
+
approval: asked.approval,
|
|
138
|
+
...(input.runId ? { runId: input.runId } : {}),
|
|
139
|
+
...(input.commit ? { commit: input.commit } : {}),
|
|
140
|
+
...(input.cwd ? { cwd: input.cwd } : {}),
|
|
141
|
+
...(input.now ? { now: input.now } : {}),
|
|
142
|
+
});
|
|
143
|
+
const finish = async (result: "applied" | "failed", detail?: Record<string, string | number | boolean>): Promise<boolean> => {
|
|
144
|
+
try {
|
|
145
|
+
const f = await ledger.finishGatedRequest({ op: input.op, gate: request.subject, digest, applied: spent.timestamp, result, ...(detail ? { detail } : {}), ...(input.cwd ? { cwd: input.cwd } : {}) });
|
|
146
|
+
return f.pushed;
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
try {
|
|
152
|
+
const { output, detail, failed } = await act({ digest, request: asked.request, approvedBy });
|
|
153
|
+
return { status: "done", digest, request: asked.request, approvedBy, output, recorded: await finish(failed ? "failed" : "applied", detail) };
|
|
154
|
+
} catch (e) {
|
|
155
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
156
|
+
return { status: "failed", digest, request: asked.request, approvedBy, error, recorded: await finish("failed", { ...(input.failedDetail?.(error) ?? {}), error: error.message.slice(0, 400) }) };
|
|
157
|
+
}
|
|
158
|
+
}
|