@intentius/chant-lexicon-terraform 0.124.50 → 0.124.52

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/src/report.ts ADDED
@@ -0,0 +1,775 @@
1
+ /**
2
+ * `chant terraform report`: a run report from `show -json` of a saved plan, in
3
+ * the `terragucci.report/v1` shape that behold's kiosk reads, for pipelines
4
+ * that run plain `terraform`, `terragrunt`, `atmos` or `choudoufu` and have no
5
+ * terragucci in them.
6
+ *
7
+ * It covers one composed run: a root whose only content is `module` calls
8
+ * (choudoufu's composed root, chant#4419), planned and applied as one. Each
9
+ * top-level module becomes one root of the report, with its part of the plan
10
+ * taken as if it had planned alone (`module.<m>.` off every address), the way
11
+ * terragucci's own composed run reports it.
12
+ *
13
+ * What it writes is the part of the v1 contract a reader needs to draw the
14
+ * run: roots, their changes with before and after values, "known after
15
+ * apply" for values the plan cannot know, one composed wave, the totals,
16
+ * groups and named destroys, the index row, and each root's `reads`: the
17
+ * `data "terraform_estate_outputs"` blocks that read another module's estate,
18
+ * and, in an Atmos repo, the `!terraform.output` calls in its stack manifests,
19
+ * which behold draws as the lines between roots. The estate of each module
20
+ * comes from the `live` block in its directory (`<repo>/<root-dir>/<module>`),
21
+ * since the plan holds none. After an apply, a second
22
+ * `show -json` (of a plan made once the apply finished, whose `prior_state`
23
+ * holds the state) fills in the values the plan left unknown. It writes no
24
+ * report.html, no plan files, no policy, cost or approval fields.
25
+ *
26
+ * The change set is {@link terraformChangeSetPart}'s, and the grouping is
27
+ * chant's `groupChangeSet`, so a report here and one from terragucci agree on
28
+ * what changed.
29
+ */
30
+
31
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
32
+ import { dirname, join } from "node:path";
33
+ import { changeSetDigest, composeChangeSet, type ChangeSetAction, type ChangeSetAttribute, type ChangeSetEntry, type ChangeSetPlanner } from "@intentius/chant/change-set";
34
+ import { groupChangeSet } from "@intentius/chant/plan-summary";
35
+ import { plannerForBinary, terraformChangeSetPart } from "./change-set";
36
+
37
+ type Json = Record<string, unknown>;
38
+ const isObject = (v: unknown): v is Json => v !== null && typeof v === "object" && !Array.isArray(v);
39
+
40
+ export const REPORT_SCHEMA = "terragucci.report/v1";
41
+ export const INDEX_SCHEMA = "terragucci.report-index/v1";
42
+ /** The minor of the v1 contract the report is written to: `compose.estate` is minor 48. */
43
+ export const REPORT_MINOR = 48;
44
+ /** What terragucci puts in place of a redacted value; the report carries no values it would need to redact. */
45
+ export const REDACTED = "(sensitive, redacted by terragucci)";
46
+
47
+ export type ReportStage = "tf-plan" | "tf-apply";
48
+
49
+ export interface RunFacts {
50
+ /** `<host>/<path>` of the repo, as terragucci names a project. */
51
+ project: string;
52
+ commit: string;
53
+ job_url?: string;
54
+ commit_url?: string;
55
+ pull_request?: string;
56
+ pull_request_url?: string;
57
+ }
58
+
59
+ /**
60
+ * The run's facts from a Forgejo, Gitea or GitHub Actions environment
61
+ * (`GITHUB_REPOSITORY`, `GITHUB_SERVER_URL`, `GITHUB_SHA`, `GITHUB_RUN_ID`,
62
+ * which Forgejo sets too). `project` and `commit` override it; `pullRequest`
63
+ * is the number, when the run has one.
64
+ */
65
+ export function runFactsFromEnv(env: NodeJS.ProcessEnv, over: { pullRequest?: string; project?: string; commit?: string } = {}): RunFacts {
66
+ const repo = env.GITHUB_REPOSITORY;
67
+ const server = (env.GITHUB_SERVER_URL ?? "https://github.com").replace(/\/+$/, "");
68
+ const commit = over.commit ?? env.GITHUB_SHA;
69
+ const project = over.project ?? (repo ? `${new URL(server).host}/${repo}` : undefined);
70
+ if (!project || !commit) throw new Error("GITHUB_REPOSITORY and GITHUB_SHA are not set; pass --project and --commit");
71
+ const web = repo ? `${server}/${repo}` : undefined;
72
+ const forgejo = env.FORGEJO_ACTIONS === "true" || env.GITEA_ACTIONS === "true";
73
+ const number = over.pullRequest && /^\d+$/.test(over.pullRequest.trim()) ? over.pullRequest.trim() : undefined;
74
+ return {
75
+ project,
76
+ commit,
77
+ ...(web && env.GITHUB_RUN_ID ? { job_url: `${web}/actions/runs/${env.GITHUB_RUN_ID}` } : {}),
78
+ ...(web ? { commit_url: `${web}/commit/${commit}` } : {}),
79
+ ...(web && number ? { pull_request: number, pull_request_url: `${web}/${forgejo ? "pulls" : "pull"}/${number}` } : number ? { pull_request: number } : {}),
80
+ };
81
+ }
82
+
83
+ export interface TerraformReportInput {
84
+ stage: ReportStage;
85
+ /** `show -json` of the saved plan. */
86
+ plan: unknown;
87
+ /** tf-apply: `show -json` of a plan made after the apply. Its `prior_state` holds the applied values. */
88
+ applied?: unknown;
89
+ run: RunFacts;
90
+ /** The binary that planned, by name or path. Default `terraform`. */
91
+ binary?: string;
92
+ /** The binary's version, when known. */
93
+ binaryVersion?: string;
94
+ /** Where each root lives in the repo: the root of module `network` is `<rootDir>/network`. Default: the module's name. */
95
+ rootDir?: string;
96
+ /** The path of the composed root itself, which holds any resource declared outside a module. Default: `rootDir`, else `.`. */
97
+ selfRoot?: string;
98
+ /**
99
+ * The estate each module's directory names in its `live` block, by module:
100
+ * what ties a `terraform_estate_outputs` read to the module that owns the
101
+ * estate. The plan carries no `live` block, so {@link moduleEstates} reads it
102
+ * from the directories. A read of an estate none of these names has no edge.
103
+ */
104
+ estates?: Record<string, string>;
105
+ /**
106
+ * What each module reads off the others' outputs through the stack that
107
+ * wires them, by module: Atmos's `!terraform.output` ({@link atmosStackReads}).
108
+ * Atmos resolves those into plain variables before the plan, so the plan
109
+ * holds no trace of them. A module already read through an estate data
110
+ * block is not read twice.
111
+ */
112
+ componentReads?: ComponentReads;
113
+ started?: string;
114
+ finished: string;
115
+ runtime?: string;
116
+ }
117
+
118
+ export interface IndexRow {
119
+ project: string;
120
+ commit: string;
121
+ stage: ReportStage;
122
+ finished: string;
123
+ path: string;
124
+ roots: number;
125
+ groups: number;
126
+ totals: { create: number; update: number; replace: number; delete: number };
127
+ refused: number;
128
+ failed: number;
129
+ changed: number;
130
+ destroys: string[];
131
+ applied?: string;
132
+ commit_url?: string;
133
+ pull_request?: string;
134
+ pull_request_url?: string;
135
+ job_url?: string;
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // Slicing the composed plan into one plan per module.
140
+ // ---------------------------------------------------------------------------
141
+
142
+ const TOP_MODULE = /^module\.([^.[\]]+)(?:\[(?:"(?:[^"\\]|\\.)*"|\d+)\])?(?:\.|$)/;
143
+
144
+ /** The top-level module an address or module address is in, or undefined for the composed root's own. */
145
+ export function topModule(address: string): string | undefined {
146
+ return TOP_MODULE.exec(address)?.[1];
147
+ }
148
+
149
+ /** `address` with its leading `module.<m>` (and index) taken off. */
150
+ function unprefix(address: string): string {
151
+ const m = TOP_MODULE.exec(address);
152
+ return m ? address.slice(m[0].length) : address;
153
+ }
154
+
155
+ /** The plan's `resource_changes` that belong to module `m` (undefined: the root's own), each with the module taken off its address. */
156
+ export function slicePlan(plan: unknown, m: string | undefined): Json {
157
+ const p = isObject(plan) ? plan : {};
158
+ const list = Array.isArray(p.resource_changes) ? p.resource_changes : [];
159
+ const mine = list.filter((r) => isObject(r) && topModule(String(r.module_address ?? r.address ?? "")) === m);
160
+ const resource_changes = mine.map((r) => {
161
+ const rc = r as Json;
162
+ const out: Json = { ...rc, address: unprefix(String(rc.address)) };
163
+ if (typeof rc.previous_address === "string") out.previous_address = unprefix(rc.previous_address);
164
+ if (typeof rc.module_address === "string") {
165
+ const rest = unprefix(rc.module_address);
166
+ if (rest === "" || rest === rc.module_address) delete out.module_address;
167
+ else out.module_address = rest;
168
+ }
169
+ return out;
170
+ });
171
+ return { ...(p.errored === true ? { errored: true } : {}), resource_changes };
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // Applied values: the state after the apply gives the values the plan left unknown.
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /** Whether a sensitivity map marks anything under it `true`. */
179
+ function marks(v: unknown): boolean {
180
+ if (v === true) return true;
181
+ if (Array.isArray(v)) return v.some(marks);
182
+ if (isObject(v)) return Object.values(v).some(marks);
183
+ return false;
184
+ }
185
+
186
+ /** Every resource of a `show -json` state, by address. A deposed object is left out. */
187
+ function stateResources(show: unknown): Map<string, { values: Json; sensitive: Json }> {
188
+ const out = new Map<string, { values: Json; sensitive: Json }>();
189
+ const walk = (mod: unknown): void => {
190
+ if (!isObject(mod)) return;
191
+ for (const r of Array.isArray(mod.resources) ? mod.resources : []) {
192
+ if (!isObject(r) || typeof r.address !== "string" || r.deposed_key !== undefined) continue;
193
+ out.set(r.address, { values: isObject(r.values) ? r.values : {}, sensitive: isObject(r.sensitive_values) ? r.sensitive_values : {} });
194
+ }
195
+ for (const c of Array.isArray(mod.child_modules) ? mod.child_modules : []) walk(c);
196
+ };
197
+ const root = isObject(show) ? show : {};
198
+ // A plan's `prior_state` is the state; a `show -json` of state has `values` itself.
199
+ const state = isObject(root.prior_state) ? root.prior_state : root;
200
+ const values = isObject(state.values) ? state.values : {};
201
+ walk(values.root_module);
202
+ return out;
203
+ }
204
+
205
+ /** Each unknown attribute given the value the state holds. One the state lacks stays unknown; a sensitive one stays `sensitive`. */
206
+ function resolveUnknowns(attributes: ChangeSetAttribute[], res: { values: Json; sensitive: Json } | undefined): ChangeSetAttribute[] {
207
+ if (!res || !attributes.some((a) => a.unknown)) return attributes;
208
+ return attributes.map((a) => {
209
+ if (!a.unknown) return a;
210
+ const { unknown: _u, before: _b, after: _a, ...rest } = a;
211
+ if (a.sensitive || marks(res.sensitive[a.path])) return { ...rest, sensitive: true as const };
212
+ const value = res.values[a.path];
213
+ if (value === undefined) return a;
214
+ return { ...rest, ...(a.before !== undefined ? { before: a.before } : {}), after: value };
215
+ });
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // Reads: `data "terraform_estate_outputs"` blocks between the composed modules.
220
+ // ---------------------------------------------------------------------------
221
+
222
+ /** One `read` of the report schema's `reads`, as a composed run writes it. */
223
+ export interface ReportRead {
224
+ upstream: string;
225
+ data: string;
226
+ outputs: "planned";
227
+ unknown?: string[];
228
+ /** Why the read is there, when no data block names it: Atmos's `!terraform.output` and the outputs it reads. */
229
+ why?: string;
230
+ composed: true;
231
+ }
232
+
233
+ /** The estate named by the first `live { estate = "..." }` block in a directory's `.tf` files, or undefined. */
234
+ export function estateOfDir(dir: string): string | undefined {
235
+ let files: string[];
236
+ try {
237
+ files = readdirSync(dir).filter((f) => f.endsWith(".tf")).sort();
238
+ } catch {
239
+ return undefined;
240
+ }
241
+ for (const f of files) {
242
+ const text = readFileSync(join(dir, f), "utf8").replace(/^\s*(#|\/\/).*$/gm, "");
243
+ const live = /\blive\s*\{/.exec(text);
244
+ if (!live) continue;
245
+ const m = /\bestate\s*=\s*"([^"]+)"/.exec(text.slice(live.index + live[0].length));
246
+ if (m) return m[1];
247
+ }
248
+ return undefined;
249
+ }
250
+
251
+ /** Each module's estate, read from `<repo>/<rootDir>/<module>`. A module whose directory has no `live` block is left out. */
252
+ export function moduleEstates(repo: string, rootDir: string, modules: readonly string[]): Record<string, string> {
253
+ const out: Record<string, string> = {};
254
+ for (const m of modules) {
255
+ const dir = join(repo, rootDir, m);
256
+ const estate = existsSync(dir) ? estateOfDir(dir) : undefined;
257
+ if (estate) out[m] = estate;
258
+ }
259
+ return out;
260
+ }
261
+
262
+ function anyUnknown(v: unknown): boolean {
263
+ if (v === true) return true;
264
+ if (Array.isArray(v)) return v.some(anyUnknown);
265
+ if (isObject(v)) return Object.values(v).some(anyUnknown);
266
+ return false;
267
+ }
268
+
269
+ /** The module's own configuration (`configuration.root_module.module_calls.<m>.module`), or undefined. */
270
+ function moduleConfig(plan: Json, m: string): Json | undefined {
271
+ const root = isObject(plan.configuration) && isObject(plan.configuration.root_module) ? plan.configuration.root_module : {};
272
+ const call = isObject(root.module_calls) ? root.module_calls[m] : undefined;
273
+ return isObject(call) && isObject(call.module) ? call.module : undefined;
274
+ }
275
+
276
+ /** Every `references` string under an expression or a configuration. */
277
+ function references(v: unknown, out: string[] = []): string[] {
278
+ if (Array.isArray(v)) for (const x of v) references(x, out);
279
+ else if (isObject(v)) {
280
+ for (const [k, x] of Object.entries(v)) {
281
+ if (k === "references" && Array.isArray(x)) {
282
+ for (const r of x) if (typeof r === "string") out.push(r);
283
+ } else references(x, out);
284
+ }
285
+ }
286
+ return out;
287
+ }
288
+
289
+ /**
290
+ * The outputs of module `u` that the plan cannot know. Two sources, joined:
291
+ * the composed root's own planned outputs (`<u>__<name>`, as terragucci's
292
+ * composed root writes them), and each output of `u`'s configuration whose
293
+ * expression refers to an attribute of a resource the plan leaves unknown.
294
+ */
295
+ function unknownOutputsOf(plan: Json, u: string): Set<string> {
296
+ const out = new Set<string>();
297
+ const prefix = `${u}__`;
298
+ if (isObject(plan.output_changes)) {
299
+ for (const [k, c] of Object.entries(plan.output_changes)) if (k.startsWith(prefix) && isObject(c) && anyUnknown(c.after_unknown)) out.add(k.slice(prefix.length));
300
+ } else if (isObject(plan.planned_values) && isObject(plan.planned_values.outputs)) {
301
+ for (const [k, o] of Object.entries(plan.planned_values.outputs)) if (k.startsWith(prefix) && isObject(o) && !("value" in o)) out.add(k.slice(prefix.length));
302
+ }
303
+ const cfg = moduleConfig(plan, u);
304
+ const outputs = cfg && isObject(cfg.outputs) ? cfg.outputs : {};
305
+ const changes = (Array.isArray(plan.resource_changes) ? plan.resource_changes : []).filter((r): r is Json => isObject(r) && topModule(String(r.module_address ?? r.address ?? "")) === u);
306
+ for (const [name, o] of Object.entries(outputs)) {
307
+ for (const ref of references(o)) {
308
+ const parts = ref.split(".");
309
+ const data = parts[0] === "data";
310
+ const [type, rname, attr] = data ? [parts[1], parts[2], parts[3]] : [parts[0], parts[1], parts[2]];
311
+ if (!type || !rname) continue;
312
+ const unprefixed = (c: Json): string => unprefix(String(c.address)).replace(/\[[^\]]*\]$/, "");
313
+ for (const c of changes) {
314
+ if (unprefixed(c) !== `${data ? "data." : ""}${type}.${rname}`) continue;
315
+ const after = isObject(c.change) ? c.change.after_unknown : undefined;
316
+ if (attr === undefined ? anyUnknown(after) : isObject(after) && anyUnknown(after[attr])) out.add(name);
317
+ }
318
+ }
319
+ }
320
+ return out;
321
+ }
322
+
323
+ const ESTATE_READ_TYPE = "terraform_estate_outputs";
324
+
325
+ /** The names a module reads off `data.terraform_estate_outputs.<name>.values`, or undefined when it reads the whole object. */
326
+ function valuesRead(refs: readonly string[], name: string): Set<string> | undefined {
327
+ const re = new RegExp(`^data\\.${ESTATE_READ_TYPE}\\.${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.values\\.([A-Za-z_][\\w-]*)`);
328
+ const read = new Set<string>();
329
+ for (const r of refs) {
330
+ const m = re.exec(r);
331
+ if (m) read.add(m[1]!);
332
+ }
333
+ return read.size > 0 ? read : undefined;
334
+ }
335
+
336
+ /**
337
+ * Module `m`'s reads of another module's estate, as terragucci writes them for
338
+ * a composed run: `{ upstream, data, outputs: "planned", unknown?, composed }`.
339
+ * `unknown` names the outputs it reads that the plan cannot know. A read of an
340
+ * estate no other module owns has no edge and is left out.
341
+ */
342
+ export function estateReads(plan: Json, m: string, estates: Readonly<Record<string, string>>, rootOf: (m: string | undefined) => string): ReportRead[] {
343
+ const cfg = moduleConfig(plan, m);
344
+ if (!cfg) return [];
345
+ const refs = references(cfg);
346
+ const reads: ReportRead[] = [];
347
+ for (const r of Array.isArray(cfg.resources) ? cfg.resources : []) {
348
+ if (!isObject(r) || r.mode !== "data" || r.type !== ESTATE_READ_TYPE || typeof r.name !== "string") continue;
349
+ const expr = isObject(r.expressions) && isObject(r.expressions.estate) ? r.expressions.estate : undefined;
350
+ const estate = expr && typeof expr.constant_value === "string" ? expr.constant_value : undefined;
351
+ if (estate === undefined) continue;
352
+ const upstream = Object.keys(estates).sort().find((o) => o !== m && estates[o] === estate);
353
+ if (upstream === undefined) continue;
354
+ const read = valuesRead(refs, r.name);
355
+ const unknown = [...unknownOutputsOf(plan, upstream)].filter((n) => read === undefined || read.has(n)).sort();
356
+ reads.push({ upstream: rootOf(upstream), data: r.name, outputs: "planned", ...(unknown.length ? { unknown } : {}), composed: true });
357
+ }
358
+ return reads;
359
+ }
360
+
361
+ // ---------------------------------------------------------------------------
362
+ // Reads: Atmos `!terraform.output` between the stack's components.
363
+ // ---------------------------------------------------------------------------
364
+
365
+ /** What each component reads off another with `!terraform.output`: reader -> upstream -> output names. */
366
+ export type ComponentReads = Record<string, Record<string, string[]>>;
367
+
368
+ const unquote = (s: string): string => s.replace(/^(["'])(.*)\1$/, "$2");
369
+
370
+ /**
371
+ * Each component's `!terraform.output <component> [<stack>] <output>` reads in
372
+ * one Atmos stack manifest. The components are the keys under
373
+ * `components.terraform`, named by their `metadata.component` when they set
374
+ * one. A line scan, not a YAML parser: Atmos writes the function as a tagged
375
+ * scalar, one per line, which is all this reads.
376
+ */
377
+ export function atmosOutputReads(yaml: string): ComponentReads {
378
+ const path: { indent: number; key: string }[] = [];
379
+ const found: { component: string; upstream: string; output: string }[] = [];
380
+ const dirOf = new Map<string, string>();
381
+ for (const raw of yaml.split(/\r?\n/)) {
382
+ const line = raw.replace(/\s+#.*$/, "");
383
+ if (!line.trim() || /^\s*#/.test(line)) continue;
384
+ const indent = line.length - line.trimStart().length;
385
+ const key = /^\s*(?:-\s+)?(["']?)([^"':#\s][^"':#]*?)\1\s*:(?:\s+(.*))?$/.exec(line);
386
+ while (path.length && path[path.length - 1]!.indent >= indent) path.pop();
387
+ const keys = path.map((p) => p.key);
388
+ const at = keys.findIndex((k, i) => k === "components" && keys[i + 1] === "terraform");
389
+ const component = at >= 0 ? keys[at + 2] : undefined;
390
+ const value = key ? (key[3] ?? "") : line.trim().replace(/^-\s+/, "");
391
+ if (key) {
392
+ if (component !== undefined && keys.length === at + 4 && keys[at + 3] === "metadata" && key[2] === "component" && value) {
393
+ dirOf.set(component, unquote(value.trim()));
394
+ }
395
+ path.push({ indent, key: key[2]! });
396
+ }
397
+ const call = /!terraform\.output\s+(.+)$/.exec(value);
398
+ if (!call || component === undefined) continue;
399
+ const args = call[1]!.trim().split(/\s+/).map(unquote);
400
+ if (args.length < 2) continue;
401
+ const output = /^\.?([A-Za-z_][\w-]*)/.exec(args[args.length - 1]!)?.[1];
402
+ if (output) found.push({ component, upstream: args[0]!, output });
403
+ }
404
+ const out: ComponentReads = {};
405
+ for (const f of found) {
406
+ const reader = dirOf.get(f.component) ?? f.component;
407
+ const upstream = dirOf.get(f.upstream) ?? f.upstream;
408
+ if (reader === upstream) continue;
409
+ const names = ((out[reader] ??= {})[upstream] ??= []);
410
+ if (!names.includes(f.output)) names.push(f.output);
411
+ }
412
+ for (const ups of Object.values(out)) for (const names of Object.values(ups)) names.sort();
413
+ return out;
414
+ }
415
+
416
+ /**
417
+ * The `!terraform.output` reads of every stack manifest in an Atmos repo: the
418
+ * `.yaml`/`.yml` files under `stacks.base_path` of `<repo>/atmos.yaml`
419
+ * (`stacks` when it names none), joined. Empty when the repo has no atmos.yaml.
420
+ */
421
+ export function atmosStackReads(repo: string): ComponentReads {
422
+ const config = join(repo, "atmos.yaml");
423
+ if (!existsSync(config)) return {};
424
+ let base = "stacks";
425
+ const text = readFileSync(config, "utf8");
426
+ const stacks = /^stacks\s*:\s*$([\s\S]*?)(?=^\S|(?![\s\S]))/m.exec(text);
427
+ const named = stacks ? /^\s+base_path\s*:\s*(["']?)([^"'#\s]+)\1/m.exec(stacks[1]!) : null;
428
+ if (named) base = named[2]!;
429
+ const out: ComponentReads = {};
430
+ const walk = (dir: string): void => {
431
+ let entries: import("node:fs").Dirent[];
432
+ try {
433
+ entries = readdirSync(dir, { withFileTypes: true });
434
+ } catch {
435
+ return;
436
+ }
437
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
438
+ const p = join(dir, e.name);
439
+ if (e.isDirectory()) walk(p);
440
+ else if (/\.ya?ml$/.test(e.name)) {
441
+ for (const [reader, ups] of Object.entries(atmosOutputReads(readFileSync(p, "utf8")))) {
442
+ for (const [up, names] of Object.entries(ups)) {
443
+ const into = ((out[reader] ??= {})[up] ??= []);
444
+ for (const n of names) if (!into.includes(n)) into.push(n);
445
+ into.sort();
446
+ }
447
+ }
448
+ }
449
+ }
450
+ };
451
+ walk(join(repo, base));
452
+ return out;
453
+ }
454
+
455
+ /**
456
+ * Module `m`'s reads of the other modules' outputs that the stack wires in
457
+ * (`componentReads`, from Atmos's `!terraform.output`): one per upstream that
458
+ * is a module of this run, planned and composed, as {@link estateReads} writes
459
+ * them. Under choudoufu the reader is planned on the upstream's planned
460
+ * outputs, so `unknown` names the ones read that the plan cannot know.
461
+ */
462
+ export function componentOutputReads(plan: Json, m: string, componentReads: ComponentReads, modules: readonly string[], rootOf: (m: string | undefined) => string): ReportRead[] {
463
+ const reads: ReportRead[] = [];
464
+ for (const [upstream, names] of Object.entries(componentReads[m] ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
465
+ if (upstream === m || !modules.includes(upstream)) continue;
466
+ const unknown = [...unknownOutputsOf(plan, upstream)].filter((n) => names.includes(n)).sort();
467
+ reads.push({ upstream: rootOf(upstream), data: upstream, outputs: "planned", ...(unknown.length ? { unknown } : {}), why: `!terraform.output ${upstream}: ${names.join(", ")}`, composed: true });
468
+ }
469
+ return reads;
470
+ }
471
+
472
+ // ---------------------------------------------------------------------------
473
+ // The report.
474
+ // ---------------------------------------------------------------------------
475
+
476
+ const COUNTED: ReadonlySet<ChangeSetAction> = new Set(["create", "update", "replace", "delete", "forget"]);
477
+
478
+ interface RawChange {
479
+ replace_paths?: (string | number)[][];
480
+ importing?: string;
481
+ }
482
+
483
+ function rawChanges(plan: Json): Map<string, RawChange> {
484
+ const out = new Map<string, RawChange>();
485
+ for (const r of Array.isArray(plan.resource_changes) ? plan.resource_changes : []) {
486
+ if (!isObject(r)) continue;
487
+ const change = isObject(r.change) ? r.change : {};
488
+ const paths = Array.isArray(change.replace_paths) ? (change.replace_paths.filter(Array.isArray) as (string | number)[][]) : [];
489
+ const importing = isObject(change.importing) ? String(change.importing.id ?? change.importing.identity ?? "") : undefined;
490
+ out.set(`${r.address}\u0000${r.deposed ?? ""}`, { ...(paths.length > 0 ? { replace_paths: paths } : {}), ...(importing !== undefined ? { importing } : {}) });
491
+ }
492
+ return out;
493
+ }
494
+
495
+ export interface TerraformReport {
496
+ report: Json;
497
+ /** The run's directory, relative to the project's own index: `yyyy/mm/<commit>/<stage>`. */
498
+ path: string;
499
+ row: IndexRow;
500
+ }
501
+
502
+ /** Where a run's report lives under its project: `yyyy/mm/<commit>/<stage>`, by the day it finished. */
503
+ export function runPath(commit: string, stage: ReportStage, finished: string): string {
504
+ const at = new Date(finished);
505
+ return `${at.getUTCFullYear()}/${String(at.getUTCMonth() + 1).padStart(2, "0")}/${commit}/${stage}`;
506
+ }
507
+
508
+ /** The report for one composed run, and its index row. Pure. */
509
+ export function terraformReport(input: TerraformReportInput): TerraformReport {
510
+ const plan = isObject(input.plan) ? input.plan : {};
511
+ const planner: ChangeSetPlanner = plannerForBinary(input.binary);
512
+ const rootDir = (input.rootDir ?? "").replace(/\/+$/, "");
513
+ const rootOf = (m: string | undefined): string => (m === undefined ? input.selfRoot ?? (rootDir || ".") : rootDir ? `${rootDir}/${m}` : m);
514
+
515
+ const changes = Array.isArray(plan.resource_changes) ? plan.resource_changes : [];
516
+ const modules = [...new Set(changes.flatMap((r) => (isObject(r) ? [topModule(String(r.module_address ?? r.address ?? ""))] : [])))];
517
+ // Roots in module order, the composed root's own resources (if any) last.
518
+ const keys = [...modules.filter((m): m is string => m !== undefined).sort(), ...(modules.includes(undefined) ? [undefined] : [])];
519
+ if (keys.length === 0) throw new Error("the plan has no resource changes, so there is nothing to report");
520
+
521
+ const applied = input.applied !== undefined ? stateResources(input.applied) : undefined;
522
+ if (input.stage === "tf-apply" && !applied) throw new Error("a tf-apply report needs the post-apply plan (applied) for the values the plan left unknown");
523
+
524
+ const slices = new Map(keys.map((m) => [m, slicePlan(plan, m)] as const));
525
+ const parts = keys.map((m) => terraformChangeSetPart({ member: rootOf(m), plan: slices.get(m), planner }));
526
+ const doc = composeChangeSet(parts);
527
+ const summary = groupChangeSet(doc);
528
+ const memberGroup = new Map<string, string>();
529
+ if (summary.unit === "member") for (const g of summary.groups) for (const u of g.units) memberGroup.set(u, g.id);
530
+
531
+ const prefixOf = new Map(keys.map((m) => [rootOf(m), m === undefined ? "" : `module.${m}.`] as const));
532
+ const moduleOf = new Map(keys.map((m) => [rootOf(m), m === undefined ? "." : `module.${m}`] as const));
533
+
534
+ const roots = doc.members.map((member) => {
535
+ const raw = rawChanges(slices.get(keys.find((m) => rootOf(m) === member.member)!)!);
536
+ const counts: Record<string, number> = {};
537
+ const rootChanges: Json[] = [];
538
+ for (const e of doc.entries as ChangeSetEntry[]) {
539
+ if (e.member !== member.member) continue;
540
+ counts[e.action] = (counts[e.action] ?? 0) + 1;
541
+ const r = raw.get(`${e.address}\u0000${e.deposed ?? ""}`);
542
+ if (e.action === "no-op" && r?.importing === undefined) continue;
543
+ const attributes = applied ? resolveUnknowns(e.attributes, applied.get(`${prefixOf.get(member.member)}${e.address}`)) : e.attributes;
544
+ rootChanges.push({
545
+ address: e.address,
546
+ type: e.type,
547
+ action: e.action,
548
+ ...(e.disruption ? { disruption: e.disruption } : {}),
549
+ ...(e.deposed !== undefined ? { deposed: e.deposed } : {}),
550
+ ...(e.module ? { module: e.module } : {}),
551
+ ...(e.index !== undefined ? { index: e.index } : {}),
552
+ attributes,
553
+ ...(r?.replace_paths ? { replace_paths: r.replace_paths } : {}),
554
+ ...(r?.importing !== undefined ? { importing: r.importing } : {}),
555
+ fold: "open",
556
+ });
557
+ }
558
+ const failed = member.status === "failed";
559
+ const group = memberGroup.get(member.member);
560
+ const mod = keys.find((m) => rootOf(m) === member.member);
561
+ const reads = mod !== undefined && input.estates ? estateReads(plan, mod, input.estates, rootOf) : [];
562
+ if (mod !== undefined && input.componentReads) {
563
+ const named = new Set(reads.map((r) => r.upstream));
564
+ const declared = keys.filter((k): k is string => k !== undefined);
565
+ for (const r of componentOutputReads(plan, mod, input.componentReads, declared, rootOf)) if (!named.has(r.upstream)) reads.push(r);
566
+ }
567
+ return {
568
+ path: member.member,
569
+ binary: { name: planner, ...(input.binaryVersion ? { version: input.binaryVersion } : {}) },
570
+ status: member.status,
571
+ ...(member.error ? { error: member.error } : {}),
572
+ plan_digest: member.planDigest,
573
+ counts,
574
+ ...(group ? { group } : {}),
575
+ plan: {},
576
+ ...(reads.length > 0 ? { reads } : {}),
577
+ ...(input.run.job_url ? { job_url: input.run.job_url } : {}),
578
+ changes: rootChanges,
579
+ highlights: [],
580
+ fold: rootChanges.length > 0 || failed ? "open" : "folded",
581
+ why: failed ? ["refused to plan"] : [],
582
+ composed: { wave: 1, module: moduleOf.get(member.member)! },
583
+ };
584
+ });
585
+
586
+ const groups = summary.groups.map((g) => ({
587
+ id: g.id,
588
+ ...(g.resource ? { resource: g.resource } : {}),
589
+ units: g.units,
590
+ outlier: g.outlier,
591
+ noChanges: g.noChanges,
592
+ changes: g.changes,
593
+ ...(g.extends ? { extends: g.extends } : {}),
594
+ ...(g.plus ? { plus: g.plus } : {}),
595
+ destroys: g.destroys.length,
596
+ varies: [],
597
+ fold: g.destroys.length > 0 || g.outlier ? "open" : "folded",
598
+ why: [...(g.outlier ? ["outlier: read it on its own"] : []), ...(g.destroys.length > 0 ? [`${g.destroys.length} destroys or replacements`] : [])],
599
+ }));
600
+
601
+ const named: { root: string; address?: string; type?: string; action: string; deposed?: string; reason?: string }[] = [
602
+ ...summary.destroys.map((d) => ({ root: d.member, address: d.address, type: d.type, action: d.action, ...(d.deposed ? { deposed: d.deposed } : {}) })),
603
+ ...summary.forgets.map((d) => ({ root: d.member, address: d.address, type: d.type, action: "forget" as const })),
604
+ ...summary.failed.map((f) => ({ root: f.member, action: "refused" as const, reason: f.reason })),
605
+ ];
606
+
607
+ const totals = { ...doc.summary.actions } as Record<ChangeSetAction, number>;
608
+ const changing = new Set(doc.entries.filter((e) => COUNTED.has(e.action)).map((e) => e.member));
609
+ const planDigests = doc.members.map((m) => m.planDigest);
610
+ const failedAny = planDigests.some((d) => d === null);
611
+ const stage = input.stage;
612
+ const rootPaths = doc.members.map((m) => m.member);
613
+ const members = doc.members.map((m) => {
614
+ const planned = Object.entries(roots.find((r) => r.path === m.member)!.counts).filter(([a]) => COUNTED.has(a as ChangeSetAction)).reduce((n, [, c]) => n + c, 0);
615
+ return {
616
+ root: m.member,
617
+ module: moduleOf.get(m.member)!,
618
+ ...(stage === "tf-apply" ? { apply: planned === 0 ? "no-changes" : "applied", changes: { done: planned, planned }, state: "written" } : {}),
619
+ };
620
+ });
621
+ const wave = {
622
+ number: 1,
623
+ roots: rootPaths,
624
+ set_digest: failedAny ? null : changeSetDigest(doc.members),
625
+ approval: "not-requested",
626
+ state: failedAny ? "failed" : stage === "tf-apply" ? "applied" : "planned",
627
+ composed: { plan_digest: failedAny ? null : changeSetDigest(doc.members), members },
628
+ };
629
+
630
+ const run = {
631
+ project: input.run.project,
632
+ commit: input.run.commit,
633
+ stage,
634
+ binary: planner,
635
+ runtime: input.runtime ?? "ci",
636
+ started: input.started ?? input.finished,
637
+ finished: input.finished,
638
+ ...(input.run.job_url ? { job_url: input.run.job_url } : {}),
639
+ ...(input.run.commit_url ? { commit_url: input.run.commit_url } : {}),
640
+ ...(input.run.pull_request ? { pull_request: input.run.pull_request } : {}),
641
+ ...(input.run.pull_request_url ? { pull_request_url: input.run.pull_request_url } : {}),
642
+ };
643
+
644
+ const report: Json = {
645
+ schema: REPORT_SCHEMA,
646
+ minor: REPORT_MINOR,
647
+ run,
648
+ change_set: doc.digest,
649
+ unit: summary.unit,
650
+ units: summary.units,
651
+ totals,
652
+ totals_roots: changing.size,
653
+ groups,
654
+ roots,
655
+ waves: [wave],
656
+ named,
657
+ holes: summary.holes.map((h) => ({ root: h.member, address: h.address, ...(h.type ? { type: h.type } : {}), reason: h.reason })),
658
+ redaction: { marker: REDACTED, values: 0 },
659
+ compose: { roots: rootPaths, max: rootPaths.length, wave: 1, ...(planner === "choudoufu" ? { estate: true as const } : {}) },
660
+ };
661
+
662
+ const path = runPath(input.run.commit, stage, input.finished);
663
+ const failed = roots.filter((r) => r.status === "failed").length;
664
+ const row: IndexRow = {
665
+ project: input.run.project,
666
+ commit: input.run.commit,
667
+ stage,
668
+ finished: input.finished,
669
+ path,
670
+ roots: roots.length,
671
+ groups: groups.length,
672
+ totals: { create: totals.create, update: totals.update, replace: totals.replace, delete: totals.delete },
673
+ refused: named.filter((n) => n.action === "refused").length,
674
+ failed,
675
+ changed: roots.filter((r) => r.status === "planned" && r.changes.length > 0).length,
676
+ destroys: named.filter((n) => n.action === "delete" || n.action === "replace").map((n) => `${n.root}: ${n.address}`),
677
+ ...(stage === "tf-apply" && failed === 0 ? { applied: input.finished } : {}),
678
+ ...(run.commit_url ? { commit_url: run.commit_url } : {}),
679
+ ...(run.pull_request ? { pull_request: run.pull_request } : {}),
680
+ ...(run.pull_request_url ? { pull_request_url: run.pull_request_url } : {}),
681
+ ...(run.job_url ? { job_url: run.job_url } : {}),
682
+ };
683
+ return { report, path, row };
684
+ }
685
+
686
+ // ---------------------------------------------------------------------------
687
+ // The indexes.
688
+ // ---------------------------------------------------------------------------
689
+
690
+ /** How many rows an index keeps. */
691
+ export const INDEX_ROWS = 500;
692
+
693
+ /**
694
+ * `existing` index text with `row` added: a row at the same path is replaced,
695
+ * newest first, an unreadable index starts again from this row.
696
+ */
697
+ export function addToIndex(existing: string | undefined, row: IndexRow): { schema: string; reports: IndexRow[] } {
698
+ let reports: IndexRow[] = [];
699
+ if (existing) {
700
+ try {
701
+ const parsed = JSON.parse(existing) as { reports?: unknown };
702
+ if (Array.isArray(parsed.reports)) reports = parsed.reports as IndexRow[];
703
+ } catch {
704
+ // An unreadable index is rebuilt from this run on.
705
+ }
706
+ }
707
+ reports = [...reports.filter((r) => r.path !== row.path), row];
708
+ reports.sort((a, b) => (a.finished < b.finished ? 1 : a.finished > b.finished ? -1 : a.path < b.path ? -1 : 1));
709
+ return { schema: INDEX_SCHEMA, reports: reports.slice(0, INDEX_ROWS) };
710
+ }
711
+
712
+ /** A place the report's files go: a key is `project/...` under the reports prefix. */
713
+ export interface ReportStore {
714
+ read(key: string): Promise<string | undefined>;
715
+ put(key: string, body: string): Promise<void>;
716
+ }
717
+
718
+ /**
719
+ * Write the run's `report.json` and add its row to the project's index
720
+ * (`<project>/index.json`, paths relative to it) and to the prefix's
721
+ * (`index.json`, paths starting at the project), the two places terragucci
722
+ * writes. Returns the keys written.
723
+ */
724
+ export async function writeReport(store: ReportStore, r: TerraformReport): Promise<string[]> {
725
+ const project = r.row.project;
726
+ const keys: string[] = [];
727
+ const put = async (key: string, value: unknown): Promise<void> => {
728
+ await store.put(key, JSON.stringify(value, null, 2) + "\n");
729
+ keys.push(key);
730
+ };
731
+ await put(`${project}/${r.path}/report.json`, r.report);
732
+ for (const [key, path] of [[`${project}/index.json`, r.path], ["index.json", `${project}/${r.path}`]] as const) {
733
+ await put(key, addToIndex(await store.read(key), { ...r.row, path }));
734
+ }
735
+ return keys;
736
+ }
737
+
738
+ /** A store under a local directory: what the tests and a job that uploads itself use. */
739
+ export function dirStore(dir: string): ReportStore {
740
+ return {
741
+ async read(key) {
742
+ try {
743
+ return readFileSync(join(dir, key), "utf8");
744
+ } catch {
745
+ return undefined;
746
+ }
747
+ },
748
+ async put(key, body) {
749
+ mkdirSync(dirname(join(dir, key)), { recursive: true });
750
+ writeFileSync(join(dir, key), body);
751
+ },
752
+ };
753
+ }
754
+
755
+ /**
756
+ * A store behind an HTTP address that takes unsigned `GET` and `PUT` of
757
+ * `<base>/<key>`: the demo's floci bucket, `http://floci:4566/<bucket>/<prefix>`.
758
+ * It signs nothing, so it does not write to AWS S3 or another store that asks
759
+ * for credentials. A 404 on read is no object.
760
+ */
761
+ export function httpStore(base: string, fetcher: typeof fetch = fetch): ReportStore {
762
+ const url = (key: string): string => `${base.replace(/\/+$/, "")}/${key.split("/").map(encodeURIComponent).join("/")}`;
763
+ return {
764
+ async read(key) {
765
+ const res = await fetcher(url(key));
766
+ if (res.status === 404) return undefined;
767
+ if (!res.ok) throw new Error(`GET ${url(key)}: ${res.status}`);
768
+ return res.text();
769
+ },
770
+ async put(key, body) {
771
+ const res = await fetcher(url(key), { method: "PUT", headers: { "content-type": "application/json" }, body });
772
+ if (!res.ok) throw new Error(`PUT ${url(key)}: ${res.status}`);
773
+ },
774
+ };
775
+ }