Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lexicons/aws/src/member-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* The report of the workspace member read in this process (#3179).
* `graphMeta` receives only the entities, so the hook that read the member
* leaves its report here for the hook that publishes it; `chant graph` runs
* the two in order in one process.
*
* Kept apart from ./workspace-member.ts so the plugin can clear and read the
* report without loading the member reader, which a project with no member
* never needs (#5219).
*/

import type { AwsMemberReport } from "./workspace-member";

let lastReport: AwsMemberReport | undefined;

export function setLastMemberReport(report: AwsMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): AwsMemberReport | undefined {
return lastReport;
}
3 changes: 2 additions & 1 deletion lexicons/aws/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import { canDescribe, describeOwnProperties, stampRegion } from "./properties";
import { stampProviderDefaults } from "./defaults";
import { resolveTemplateAttrs } from "./live-attrs";
import { CFParser } from "./import/parser";
import { lastMemberReport, readCloudFormationMember, setLastMemberReport } from "./workspace-member";
import { lastMemberReport, setLastMemberReport } from "./member-report";
import { CFGenerator } from "./import/generator";
import { parseStackTemplate } from "./import/live-export";
import { awsCompletions } from "./lsp/completions";
Expand Down Expand Up @@ -76,6 +76,7 @@ export const awsPlugin: LexiconPlugin = {
setLastMemberReport(undefined);
const member = (ctx.config as { aws?: { member?: { kind?: "cloudformation" | "cdk"; dir: string; label?: string } } }).aws?.member;
if (!member) return { entities: new Map() };
const { readCloudFormationMember } = await import("./workspace-member");
const read = readCloudFormationMember({ member });
setLastMemberReport(read.report);
return { entities: read.entities, warnings: read.warnings };
Expand Down
15 changes: 1 addition & 14 deletions lexicons/aws/src/workspace-member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,4 @@ export function readCloudFormationMember(opts: { member: AwsMemberConfig }): {
};
}

let lastReport: AwsMemberReport | undefined;

/**
* The report of the read in this process. `graphMeta` receives only the
* entities, so the hook that read the member leaves its report here for the
* hook that publishes it; `chant graph` runs the two in order in one process.
*/
export function setLastMemberReport(report: AwsMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): AwsMemberReport | undefined {
return lastReport;
}
export { lastMemberReport, setLastMemberReport } from "./member-report";
22 changes: 22 additions & 0 deletions lexicons/helm/src/member-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* The report of the workspace member read in this process (#3179).
* `graphMeta` receives only the entities, so the hook that read the member
* leaves its report here for the hook that publishes it; `chant graph` runs
* the two in order in one process.
*
* Kept apart from ./workspace-member.ts so the plugin can clear and read the
* report without loading the member reader, which a project with no member
* never needs (#5219).
*/

import type { HelmMemberReport } from "./workspace-member";

let lastReport: HelmMemberReport | undefined;

export function setLastMemberReport(report: HelmMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): HelmMemberReport | undefined {
return lastReport;
}
3 changes: 2 additions & 1 deletion lexicons/helm/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { helmSerializer } from "./serializer";
import { helmCompletions } from "./lsp/completions";
import { helmHover } from "./lsp/hover";
import { helmConfigSchema } from "./config";
import { lastMemberReport, readHelmMember, setLastMemberReport } from "./workspace-member";
import { lastMemberReport, setLastMemberReport } from "./member-report";
import { helmProjectCodegen } from "./project-codegen";
import { helmDeepNormalizationHooks } from "./deep-observe-hooks";
import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
Expand Down Expand Up @@ -53,6 +53,7 @@ export const helmPlugin: LexiconPlugin = {
setLastMemberReport(undefined);
const member = (ctx.config as { helm?: { member?: { dir: string; label?: string } } }).helm?.member;
if (!member) return { entities: new Map() };
const { readHelmMember } = await import("./workspace-member");
const read = await readHelmMember({ member });
setLastMemberReport(read.report);
return { entities: read.entities, warnings: read.warnings };
Expand Down
15 changes: 1 addition & 14 deletions lexicons/helm/src/workspace-member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,4 @@ export async function readHelmMember(opts: {
return { entities, warnings, report: { rendered: true, objects: entities.size } };
}

let lastReport: HelmMemberReport | undefined;

/**
* The report of the read in this process. `graphMeta` receives only the
* entities, so the hook that read the member leaves its report here for the
* hook that publishes it; `chant graph` runs the two in order in one process.
*/
export function setLastMemberReport(report: HelmMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): HelmMemberReport | undefined {
return lastReport;
}
export { lastMemberReport, setLastMemberReport } from "./member-report";
22 changes: 22 additions & 0 deletions lexicons/k8s/src/member-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* The report of the workspace member read in this process (#3179).
* `graphMeta` receives only the entities, so the hook that read the member
* leaves its report here for the hook that publishes it; `chant graph` runs
* the two in order in one process.
*
* Kept apart from ./workspace-member.ts so the plugin can clear and read the
* report without loading the member reader, which a project with no member
* never needs (#5219).
*/

import type { K8sMemberReport } from "./workspace-member";

let lastReport: K8sMemberReport | undefined;

export function setLastMemberReport(report: K8sMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): K8sMemberReport | undefined {
return lastReport;
}
3 changes: 2 additions & 1 deletion lexicons/k8s/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
import { k8sConfigSchema } from "./config-schema";
import type { K8sChantConfig } from "./config";
import { renderKustomizeRoots } from "./kustomize/root";
import { lastMemberReport, readK8sMember, setLastMemberReport } from "./workspace-member";
import { lastMemberReport, setLastMemberReport } from "./member-report";
import { encryptedSecretBuildRoot } from "./sops/encrypted-secret-file";
import { k8sProjectCodegen } from "./crd/project-codegen";
import { includeBuildRoot } from "./include/resolve";
Expand Down Expand Up @@ -121,6 +121,7 @@ export const k8sPlugin: LexiconPlugin = {
setLastMemberReport(undefined);
const member = (ctx.config as { k8s?: K8sChantConfig }).k8s?.member;
if (member) {
const { readK8sMember } = await import("./workspace-member");
const read = await readK8sMember({ member });
for (const [name, entity] of read.entities) entities.set(name, entity);
warnings.push(...read.warnings);
Expand Down
15 changes: 1 addition & 14 deletions lexicons/k8s/src/workspace-member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,17 +246,4 @@ export async function readK8sMember(opts: {
};
}

let lastReport: K8sMemberReport | undefined;

/**
* The report of the read in this process. `graphMeta` receives only the
* entities, so the hook that read the member leaves its report here for the
* hook that publishes it; `chant graph` runs the two in order in one process.
*/
export function setLastMemberReport(report: K8sMemberReport | undefined): void {
lastReport = report;
}

export function lastMemberReport(): K8sMemberReport | undefined {
return lastReport;
}
export { lastMemberReport, setLastMemberReport } from "./member-report";
4 changes: 2 additions & 2 deletions lexicons/otel/src/clickhouse-tables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,10 @@ describe("OTEL129: the exporter's tables against the sql build in the same root"
});

describe("the otel lexicon's workspace links", () => {
test("each table the exporter writes, and each column its insert names anchored on the table", () => {
test("each table the exporter writes, and each column its insert names anchored on the table", async () => {
const entities = new Map<string, Declarable>();
collector({ database: "otel", create_schema: false }).forEach((e, i) => entities.set(i === 2 ? "clickhouse" : `e${i}`, e));
const links = otelPlugin.workspaceLinks!(entities)!;
const links = (await otelPlugin.workspaceLinks!(entities))!;
expect(links.gaps).toBeUndefined();
const tables = links.links.filter((l) => !l.anchor).map((l) => l.output);
expect(tables).toEqual([
Expand Down
8 changes: 4 additions & 4 deletions lexicons/otel/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { compositeCatalog } from "./composites/catalog";
import { DEFAULT_TEMPLATE, GENAI_TEMPLATE, K8S_AGENT_TEMPLATE } from "./init-templates";
import { COLLECTOR_PIN } from "./define";
import { collectorTopologyOf } from "./topology";
import { otelWorkspaceLinks } from "./workspace-links";

/** opentelemetry-collector-releases also tags its tools (`cmd/builder/v0.163.2`); only the plain release tags are distributions. */
function releaseTag(tag: string): string | null {
Expand Down Expand Up @@ -134,9 +133,10 @@ export const otelPlugin: LexiconPlugin = {
},

// The tables and columns a clickhouse exporter writes, as links to the sql
// member that declares them (#4397), for `chant workspace check`.
workspaceLinks(entities) {
return otelWorkspaceLinks(entities);
// member that declares them (#4397), for `chant workspace check`. Loaded
// here so a project that is no workspace member never loads it (#5219).
async workspaceLinks(entities) {
return (await import("./workspace-links")).otelWorkspaceLinks(entities);
},

postSynthChecks() {
Expand Down
6 changes: 4 additions & 2 deletions lexicons/terraform/src/components/compose-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import type { ChangeSetPart } from "@intentius/chant/change-set";
import type { DriverComponent } from "@intentius/chant/components/driver";
import { wiringReferencesAt } from "@intentius/chant/components/driver";
import { computePlanDigest } from "@intentius/chant/lifecycle/plan-digest";
import { declaredTargetCloudIdentity, type TargetCloudIdentityLookup } from "@intentius/chant/workspace/ci-cloud-identity";
import type { TargetCloudIdentityLookup } from "@intentius/chant/workspace/ci-cloud-identity";
import { COMPOSE_STEP_KIND, composeOff, compositionIfEnabled, identityKey, rootHclReads, type Composition } from "../compose";
import type { TerraformConfig } from "../config";
import { terraformBinary, terraformOutputs } from "../op/activities/terraform";
Expand Down Expand Up @@ -365,7 +365,9 @@ export function composeGroup(deps: ComposeGroupDeps = {}): ComposeGroupMethods {
const envOf = (): NodeJS.ProcessEnv => deps.env ?? process.env;
const log = deps.log ?? ((line: string) => console.error(line));
const readOutputs = deps.outputs ?? ((root: string) => terraformOutputs({ root }));
const identities = deps.identity ?? declaredTargetCloudIdentity;
// #5219: the workspace reader loads when a composed group runs, not when the plugin does.
const identities =
deps.identity ?? (async (root: string, env: string) => (await import("@intentius/chant/workspace/ci-cloud-identity")).declaredTargetCloudIdentity(root, env));

/** The composition of `members` as `groupFallback` judges it, with each member's identity. */
async function compositionOf(ctx: GroupContext, p: ComposeProject, members: readonly GroupMember<StepInput>[]): Promise<Composition> {
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/ci-evidence-claims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ export const EVIDENCE_SOURCES_ENV = "CHANT_EVIDENCE_SOURCES";
*/
export const WAVE_EVIDENCE_ENV = "CHANT_WAVE_EVIDENCE";

/**
* The variable a generated job hands the runner key in, as PEM (the same one
* the tick and `chant ci run` read). Kept here rather than in
* ./workspace/trust/ so the wave runner can ask whether it signs without
* loading a workspace module (#5219).
*/
export const CHECK_EVIDENCE_KEY_ENV = "CHANT_RUNNER_KEY";

/**
* The variable a generated job sets to `oidc` when it signs keyless from
* its OIDC identity (#4869) instead of with a runner key.
*/
export const RUNNER_IDENTITY_ENV = "CHANT_RUNNER_IDENTITY";

/** Where one check's pass is read from (#4926). */
export interface EvidenceSourceSpec {
/** The job's name in the run. Default: `--from-job`'s. */
Expand Down
71 changes: 71 additions & 0 deletions packages/core/src/cli/level0-imports.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* Level 0 loads no workspace module (#2525 rule 2). The level-0 goldens check
* it at run time on the example projects; this checks the static import graph
* of what those commands load, so a new static import that reaches workspace
* code fails in the unit suite too (#5219). Only static imports count: an
* `import()` loads when the code that calls it runs.
*
* A workspace module is what test/level0-goldens/harness.ts counts: anything
* under core's src/workspace/, and any chant module whose file name starts
* with `workspace`.
*/

import { join } from "node:path";
import { build } from "esbuild";
import { describe, expect, test } from "vitest";

const SRC = import.meta.dirname;
const LEXICONS = join(SRC, "../../../../lexicons");

// The handlers of build, lint, graph, run (list), audit (in misc) and init, and
// the plugins of the lexicons the goldens' example projects load.
const ENTRIES: Record<string, string> = {
...Object.fromEntries(["build", "lint", "graph", "run", "misc", "init"].map((h) => [`cli/handlers/${h}.ts`, join(SRC, "handlers", `${h}.ts`)])),
...Object.fromEntries(["aws", "helm", "k8s", "otel", "terraform"].map((l) => [`lexicons/${l}/src/plugin.ts`, join(LEXICONS, l, "src", "plugin.ts")])),
};

const result = await build({
entryPoints: Object.values(ENTRIES),
bundle: true,
platform: "node",
format: "esm",
packages: "external",
metafile: true,
write: false,
outdir: "level0-imports-out",
logLevel: "silent",
});
const inputs = result.metafile.inputs;

function isWorkspaceModule(path: string): boolean {
return /packages\/core\/src\/workspace\//.test(path) || /(^|\/)workspace[^/]*$/.test(path) || /^@intentius\/chant[^/]*\/workspace/.test(path);
}

/** Each workspace module `entry` reaches by static imports, with the chain that reaches it. */
function workspaceChains(entry: string): string[] {
const start = Object.keys(inputs).find((k) => entry.endsWith(k))!;
const parent = new Map<string, string | null>([[start, null]]);
const queue = [start];
while (queue.length) {
const from = queue.shift()!;
for (const im of inputs[from]?.imports ?? []) {
if (im.kind !== "import-statement" || parent.has(im.path)) continue;
parent.set(im.path, from);
if (!im.external) queue.push(im.path);
}
}
return [...parent.keys()].filter(isWorkspaceModule).map((k) => {
const chain: string[] = [];
for (let c: string | null | undefined = k; c; c = parent.get(c)) chain.unshift(c.replace(/^(\.\.\/)*/, ""));
return chain.join(" -> ");
});
}

describe("level 0 imports no workspace module statically (#5219)", () => {
for (const [name, entry] of Object.entries(ENTRIES)) {
test(name, () => {
expect(Object.keys(inputs).some((k) => entry.endsWith(k)), `${name} is in the build`).toBe(true);
expect(workspaceChains(entry)).toEqual([]);
});
}
});
6 changes: 4 additions & 2 deletions packages/core/src/lexicon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2111,9 +2111,11 @@ export interface LexiconPlugin {
* folded source, as it calls `workspaceOutputs`, and checks each link like
* one a kind's reader found (WSP093 to WSP095, WSP099 for `gaps`), naming
* the file and line of the declaring entity. Pure: no I/O. Return
* `undefined` when the project declares nothing that links.
* `undefined` when the project declares nothing that links. It may return
* a promise, so a lexicon can load the code that reads its links only when
* a workspace asks for them (#5219).
*/
workspaceLinks?(entities: ReadonlyMap<string, Declarable>, unread?: readonly LexiconUnreadSource[]): LexiconWorkspaceLinks | undefined;
workspaceLinks?(entities: ReadonlyMap<string, Declarable>, unread?: readonly LexiconUnreadSource[]): LexiconWorkspaceLinks | undefined | Promise<LexiconWorkspaceLinks | undefined>;

// LSP
/** Provide completions for LSP */
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/op/local-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { stepLabel, withRunConsole, withStepConsole } from "./step-console";
import { stepTimeoutProblem } from "./activity-profiles";
import { knownOutputsOf } from "./activity-failure";
import { describeGateMismatch, evaluateGate, gateIsSealed, gitGateLedgerPort, type GateApprovalRule, type GateCheck, type GateLedgerPort, type WorkspaceGateStandIn } from "./gate";
import { resolveWorkspaceRun, type WorkspaceRunCitation } from "./workspace-run-env";
import type { WorkspaceRunCitation } from "./workspace-run-env";
import { gateName } from "./gate-name";
import { resolveGateAliases } from "./gate-alias";
import { gatePointOf } from "./gate-point";
Expand Down Expand Up @@ -1570,7 +1570,8 @@ async function runOpInTurn(
// #4020: the CI run this one is in, in the shape a deploy record carries it.
const ciRun = resolveCiRun();
// #2554: the workspace run that started this one, which its record cites.
const workspaceRun = options.workspaceRun ?? resolveWorkspaceRun();
// #5219: read when an Op runs, so a command that only loads the executor loads no workspace module.
const workspaceRun = options.workspaceRun ?? (await import("./workspace-run-env")).resolveWorkspaceRun();
// #4041: the run's events name it the way its run record does: its own id,
// the commit, and the CI run it is in.
// #4042: a run that writes to the ledger also keeps its events on this host,
Expand Down
12 changes: 10 additions & 2 deletions packages/core/src/op/op-waves-evidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,14 @@
import { execFileSync } from "node:child_process";
import type { OpRunPolicyRow } from "./runtime";
export { opWavesEvidenceProblems, type OpWavesEvidence } from "./op-waves-evidence-spec";
import { WAVE_EVIDENCE_ENV, writeCheckClaimFile } from "../ci-evidence-claims";
import { CHECK_EVIDENCE_KEY_ENV, missingCheckEvidence, recordChecks, RUNNER_IDENTITY_ENV, runnerEvidenceSigner, signChecks } from "../workspace/trust/check-evidence";
import { CHECK_EVIDENCE_KEY_ENV, RUNNER_IDENTITY_ENV, WAVE_EVIDENCE_ENV, writeCheckClaimFile } from "../ci-evidence-claims";

/**
* The signer is loaded only when a wave reads or signs evidence. A static
* import would put workspace/trust/ and its imports on every command that
* reaches the op runner, `chant build` at level 0 among them (#5219).
*/
const checkEvidence = () => import("../workspace/trust/check-evidence");

function top(cwd: string): string {
return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
Expand All @@ -36,6 +42,7 @@ function top(cwd: string): string {
/** Why the wave's commit is refused for want of evidence, or null. */
export async function opWaveEvidenceRefusal(cwd: string, head: string, base: string, requires: readonly string[] | undefined): Promise<string | null> {
if (!requires || requires.length === 0) return null;
const { missingCheckEvidence } = await checkEvidence();
return missingCheckEvidence(top(cwd), head, base, requires);
}

Expand All @@ -61,6 +68,7 @@ export async function signOpWaveChecks(input: { cwd: string; head: string; base:
if (mode === "job") return [];
if (!env[CHECK_EVIDENCE_KEY_ENV] && !env[RUNNER_IDENTITY_ENV]) return [];
try {
const { recordChecks, runnerEvidenceSigner, signChecks } = await checkEvidence();
const repo = top(input.cwd);
const signer = (await runnerEvidenceSigner(repo, input.base, { env, ...(input.fetch ? { fetch: input.fetch } : {}) }))!;
const rows = [...input.policyRows.values()];
Expand Down
Loading
Loading