@intentius/chant-lexicon-terraform 0.124.102 → 0.124.104

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.
@@ -238,6 +238,7 @@
238
238
  */
239
239
  import { mergeObservations, normalizeObservation, observation, observeEntities, } from "@intentius/chant/observation";
240
240
  import { observedInstanceNodeId, rollupInstances, terraformInstancePath, TERRAFORM_INSTANCE_ROLLUP, } from "@intentius/chant/instance-nodes";
241
+ import { engineGapsOf, engineOwnershipRowsOf, mergeOwnershipRows, withOwnershipRows, } from "@intentius/chant/engine-facts";
241
242
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
242
243
  import { tmpdir } from "node:os";
243
244
  import { isAbsolute, join } from "node:path";
@@ -355,11 +356,13 @@ export function indexLivePlan(document) {
355
356
  const addr = asString(row.addr);
356
357
  if (!addr)
357
358
  continue;
359
+ const identityValues = Object.fromEntries(Object.entries(asRecord(row.identity_values)).filter((e) => typeof e[1] === "string"));
358
360
  index.bound.set(addr, {
359
361
  addr,
360
362
  ...(asString(row.type) ? { type: asString(row.type) } : {}),
361
363
  ...(asString(row.identity) ? { identity: asString(row.identity) } : {}),
362
364
  ...(asString(row.source) ? { source: asString(row.source) } : {}),
365
+ ...(Object.keys(identityValues).length > 0 ? { identityValues } : {}),
363
366
  });
364
367
  }
365
368
  for (const entry of asArray(doc.omissions)) {
@@ -385,6 +388,7 @@ export function indexLivePlan(document) {
385
388
  ...(asString(row.tofu_estate) ? { heldBy: asString(row.tofu_estate) } : {}),
386
389
  ...(asString(row.adopt_tofu_estate) ? { adoptEstate: asString(row.adopt_tofu_estate) } : {}),
387
390
  ...(asString(row.adopt_tofu_address) ? { adoptAddress: asString(row.adopt_tofu_address) } : {}),
391
+ ...adoptCommandOf(row),
388
392
  });
389
393
  }
390
394
  for (const entry of asArray(doc.adoptable)) {
@@ -402,6 +406,7 @@ export function indexLivePlan(document) {
402
406
  ...(asString(row.identity) ? { identity: asString(row.identity) } : {}),
403
407
  ...(asString(row.adopt_tofu_estate) ? { adoptEstate: asString(row.adopt_tofu_estate) } : {}),
404
408
  ...(asString(row.adopt_tofu_address) ? { adoptAddress: asString(row.adopt_tofu_address) } : {}),
409
+ ...adoptCommandOf(row),
405
410
  ...(matched.length > 0 ? { matched } : {}),
406
411
  });
407
412
  }
@@ -421,6 +426,63 @@ export function indexLivePlan(document) {
421
426
  ].sort();
422
427
  return index;
423
428
  }
429
+ /** An `unowned[]` or `adoptable[]` row's composed write: `adopt_command`, else `hint`. */
430
+ function adoptCommandOf(row) {
431
+ const command = asString(row.adopt_command) ?? asString(row.hint);
432
+ return command ? { adoptCommand: command } : {};
433
+ }
434
+ /**
435
+ * The rows behind each address's ownership (#5402), by the address
436
+ * `live-plan` printed: `bound[]`'s source and `identity_values`, the
437
+ * omission, and the adoption an `unowned[]` or `adoptable[]` row offers. With
438
+ * a `live-ls` listing, also its `gaps[]` (read `listing`, the rung as the
439
+ * reason) and, on a bound address, whether the listing holds it under the
440
+ * estate's marker. An address with none of these is left out.
441
+ */
442
+ export function ownershipRowsByAddress(index, listing) {
443
+ const out = new Map();
444
+ const add = (address, rows) => {
445
+ const merged = mergeOwnershipRows(out.get(address), rows);
446
+ if (merged)
447
+ out.set(address, merged);
448
+ };
449
+ const listed = listing ? new Set(listing.items.map((i) => i.address).filter((a) => !!a)) : undefined;
450
+ for (const [address, row] of index.bound) {
451
+ add(address, {
452
+ ...(row.source ? { boundBy: row.source } : {}),
453
+ ...(row.identityValues ? { identityValues: row.identityValues } : {}),
454
+ ...(listed ? { listed: listed.has(address) } : {}),
455
+ });
456
+ }
457
+ for (const [address, row] of index.omissions) {
458
+ if (row.reason)
459
+ add(address, { omission: { reason: row.reason, detail: row.detail } });
460
+ }
461
+ const adoption = (row) => {
462
+ const matched = "matched" in row ? row.matched : undefined;
463
+ const adopt = {
464
+ ...(row.adoptEstate ? { owner: row.adoptEstate } : {}),
465
+ ...(row.adoptAddress ? { address: row.adoptAddress } : {}),
466
+ ...(row.adoptCommand ? { command: row.adoptCommand } : {}),
467
+ ...(matched?.length ? { matched } : {}),
468
+ };
469
+ return Object.keys(adopt).length > 0 ? { adopt } : {};
470
+ };
471
+ for (const [address, row] of index.unowned)
472
+ add(address, adoption(row));
473
+ for (const [address, row] of index.adoptable) {
474
+ // An unowned[] row answers first, as `classifyLiveInstance` reads it.
475
+ if (!index.unowned.has(address))
476
+ add(address, adoption(row));
477
+ }
478
+ for (const gap of listing?.gaps ?? []) {
479
+ add(gap.address, { gaps: [{ read: "listing", reason: gap.rung, detail: gap.detail }] });
480
+ }
481
+ for (const [address, rows] of out)
482
+ if (Object.keys(rows).length === 0)
483
+ out.delete(address);
484
+ return out;
485
+ }
424
486
  /** The chant verdict for one omission: `no-credentials` when its detail says so. */
425
487
  function omissionVerdict(row) {
426
488
  const mapped = LIVE_PLAN_OMISSION_REASONS[row.reason] ?? "read-failed";
@@ -629,9 +691,9 @@ function readLiveResource(entity, index, root, queried) {
629
691
  * The environment variable that asks for each live root's `live-plan -json`
630
692
  * document as a file, in a directory the caller owns (behold#924).
631
693
  *
632
- * The overlay keeps chant's verdict per block and drops the rows behind it:
633
- * each instance's omission reason and detail, `identity_values`, the adoptable
634
- * row's own fields. A caller that paints ownership from those rows and wants
694
+ * The overlay keeps chant's verdict per block; the rows behind it (each
695
+ * instance's omission reason and detail, `identity_values`, the adoptable
696
+ * row's own fields) ride on each node's `facts.ownershipRows` (#5402). A caller that paints ownership from those rows and wants
635
697
  * the plan's attributes from the plan depth would otherwise run its own
636
698
  * `live-plan` beside this one, two refreshes of the estate that can disagree
637
699
  * (choudoufu #1014). With this set to an absolute directory, the document this
@@ -784,6 +846,9 @@ function engineFactsOf(value) {
784
846
  const observedAt = asString(f.observedAt);
785
847
  if (observedAt)
786
848
  out.observedAt = observedAt;
849
+ const rows = engineOwnershipRowsOf(f.ownershipRows);
850
+ if (rows)
851
+ out.ownershipRows = rows;
787
852
  return Object.keys(out).length > 0 ? out : undefined;
788
853
  }
789
854
  /**
@@ -796,16 +861,30 @@ function engineFactsOf(value) {
796
861
  * the configuration reads, `estate:<name>`) has no chant entity, so its
797
862
  * edges are left out. Edges keep their grain; one without a grain is left out.
798
863
  *
864
+ * Each node's facts also carry its `ownershipRows` (#5402): `rows`, by the
865
+ * address `live-plan` printed (`ownershipRowsByAddress`), and the
866
+ * document's own `meta.engineGraph.gaps` entry for the node, read `graph`.
867
+ *
799
868
  * Throws when the document is not an engine graph document.
800
869
  */
801
- export function readEngineGraph(root, document) {
870
+ export function readEngineGraph(root, document, rows) {
802
871
  const doc = asRecord(document);
803
872
  const engineGraph = asRecord(asRecord(doc.meta).engineGraph);
804
873
  if (doc.version !== 1 || engineGraph.format !== 1 || !Array.isArray(doc.nodes)) {
805
874
  throw new Error("not an engine graph document (want GraphIR version 1 with meta.engineGraph format 1)");
806
875
  }
876
+ const graphGaps = new Map();
877
+ for (const entry of asArray(engineGraph.gaps)) {
878
+ const gap = asRecord(entry);
879
+ const address = asString(gap.address);
880
+ const [g] = engineGapsOf([{ read: "graph", reason: gap.reason, detail: gap.detail }]);
881
+ if (address && g)
882
+ graphGaps.set(address, mergeOwnershipRows(graphGaps.get(address), { gaps: [g] }));
883
+ }
884
+ const rowsFor = (id) => mergeOwnershipRows(rows?.get(id), graphGaps.get(id));
807
885
  const blocks = new Map();
808
886
  const instances = new Map();
887
+ const instanceNodes = new Map();
809
888
  const nodeIds = new Map();
810
889
  for (const entry of doc.nodes) {
811
890
  const node = asRecord(entry);
@@ -813,7 +892,7 @@ export function readEngineGraph(root, document) {
813
892
  const address = asString(asRecord(node.attrs).address);
814
893
  if (!id || !address)
815
894
  continue;
816
- const facts = engineFactsOf(node.facts);
895
+ const facts = withOwnershipRows(engineFactsOf(node.facts), rowsFor(id));
817
896
  const instanceOf = asString(node.instanceOf);
818
897
  if (instanceOf) {
819
898
  const block = entityKeyFor(root, instanceOf);
@@ -824,8 +903,10 @@ export function readEngineGraph(root, document) {
824
903
  ...(key !== undefined ? { key } : {}),
825
904
  ...(scope !== undefined ? { scope } : {}),
826
905
  });
827
- if (liveId)
906
+ if (liveId) {
828
907
  nodeIds.set(id, liveId);
908
+ instanceNodes.set(id, liveId);
909
+ }
829
910
  if (facts) {
830
911
  let byAddress = instances.get(block);
831
912
  if (!byAddress)
@@ -857,7 +938,7 @@ export function readEngineGraph(root, document) {
857
938
  seen.add(key);
858
939
  edges.push({ from, to, kind: "ref", ...(viaAttr ? { viaAttr } : {}), grain: grain });
859
940
  }
860
- return { blocks, instances, edges };
941
+ return { blocks, instances, instanceNodes, edges };
861
942
  }
862
943
  /**
863
944
  * `resources` with {@link readEngineGraph}'s facts on them: a block's on
@@ -884,6 +965,65 @@ export function withEngineFacts(resources, read) {
884
965
  }
885
966
  return out;
886
967
  }
968
+ /**
969
+ * The facts of {@link readEngineGraph}'s reads that no node of the live graph
970
+ * will carry (#5333), by the node id the declared graph gives them: a block
971
+ * `resources` does not hold (a pending create, or one `owned` filtered out),
972
+ * and an instance that is not a present instance of a block it holds. These
973
+ * are the `pending` nodes of a live root, and its `unowned` and `foreign`
974
+ * ones under `--owned`; `chant graph --live --overlay` puts them on the
975
+ * declared nodes (`ObservationResult.engineFacts`).
976
+ */
977
+ export function engineFactsBeside(resources, reads) {
978
+ const drawn = new Set(Object.keys(resources));
979
+ for (const [name, meta] of Object.entries(resources)) {
980
+ for (const inst of meta.instances ?? []) {
981
+ if (inst.verdict !== "present")
982
+ continue;
983
+ const id = observedInstanceNodeId(name, inst);
984
+ if (id)
985
+ drawn.add(id);
986
+ }
987
+ }
988
+ const out = {};
989
+ for (const read of reads) {
990
+ for (const [key, facts] of read.blocks)
991
+ if (!drawn.has(key))
992
+ out[key] = facts;
993
+ for (const byAddress of read.instances.values()) {
994
+ for (const [address, facts] of byAddress) {
995
+ const id = read.instanceNodes.get(address);
996
+ if (id && !drawn.has(id))
997
+ out[id] = facts;
998
+ }
999
+ }
1000
+ }
1001
+ return out;
1002
+ }
1003
+ /**
1004
+ * The environment variable that adds a `live-ls -json` listing to each live
1005
+ * root's engine facts (#5402). Set to `1`, a live read also runs `choudoufu
1006
+ * live-ls -estate=<estate> -json .` per root, and each node's
1007
+ * `facts.ownershipRows` carries the listing's `gaps[]` and, on a bound node,
1008
+ * `listed`. Unset, no listing runs.
1009
+ */
1010
+ export const TERRAFORM_LIVE_LISTING_ENV = "CHANT_TERRAFORM_LIVE_LISTING";
1011
+ /**
1012
+ * The listing {@link TERRAFORM_LIVE_LISTING_ENV} asks for, or none. A failed
1013
+ * listing is a note, and the rows from `live-plan` still ride.
1014
+ */
1015
+ async function ownershipListing(root, cwd, deps) {
1016
+ if (process.env[TERRAFORM_LIVE_LISTING_ENV] !== "1")
1017
+ return {};
1018
+ try {
1019
+ const listed = await deps.liveLs({ root, compare: true, ...(cwd ? { cwd } : {}) });
1020
+ return { listing: readLiveLs(listed.json) };
1021
+ }
1022
+ catch (err) {
1023
+ const message = (err instanceof Error ? err.message : String(err)).split("\n")[0];
1024
+ return { note: `terraform.roots.${root}: the listing's rows are absent: \`choudoufu live-ls -json\` failed (${message}); the rest of the read is unchanged` };
1025
+ }
1026
+ }
887
1027
  /**
888
1028
  * Run `choudoufu live-graph -json -from-plan=<file>` over the document a
889
1029
  * live root's bind handed off, and read it (#4528). Never throws: facts are
@@ -907,7 +1047,10 @@ async function engineGraphFor(root, cwd, deps, handoff) {
907
1047
  `(${graph.detail}), which needs v${MIN_CHOUDOUFU_GRAPH_VERSION} or later; the rest of the read is unchanged`,
908
1048
  };
909
1049
  }
910
- return { read: readEngineGraph(root, graph.json) };
1050
+ const listed = await ownershipListing(root, cwd, deps);
1051
+ const rows = ownershipRowsByAddress(indexLivePlan(handoff.json), listed.listing);
1052
+ const read = readEngineGraph(root, graph.json, rows);
1053
+ return { read, ...(listed.listing ? { listing: listed.listing } : {}), ...(listed.note ? { note: listed.note } : {}) };
911
1054
  }
912
1055
  catch (err) {
913
1056
  const message = (err instanceof Error ? err.message : String(err)).split("\n")[0];
@@ -920,6 +1063,91 @@ async function engineGraphFor(root, cwd, deps, handoff) {
920
1063
  rmSync(scratch, { recursive: true, force: true });
921
1064
  }
922
1065
  }
1066
+ /** True when a declared block of the root answers for `address`: its own block, or a module call it sits under. */
1067
+ function declaresAddress(address, declared) {
1068
+ const block = blockAddressOf(address);
1069
+ return declared.some((entity) => entity.type === MODULE_TYPE ? underModule(address, entity.address) : entity.type === RESOURCE_TYPE && entity.address === block);
1070
+ }
1071
+ /** The engine graph's facts for a choudoufu address, block or instance, if the read has a node for it. */
1072
+ function engineFactsAt(read, key, address) {
1073
+ if (!read)
1074
+ return undefined;
1075
+ const block = read.blocks.get(key);
1076
+ if (block)
1077
+ return block;
1078
+ for (const byAddress of read.instances.values()) {
1079
+ const facts = byAddress.get(address);
1080
+ if (facts)
1081
+ return facts;
1082
+ }
1083
+ return undefined;
1084
+ }
1085
+ /**
1086
+ * The objects a live root's estate binds that no block of its configuration
1087
+ * declares (#5429), as live nodes keyed by {@link entityKeyFor}: each
1088
+ * `live-plan` `bound[]` address no declared block or module call answers for
1089
+ * (choudoufu's `live-graph` gives it a `not-in-configuration` gap), and each
1090
+ * `live-ls` item with `declared: false` when the listing ran.
1091
+ *
1092
+ * Each one's `type` is the resource type choudoufu prints (`bound[].type`, or
1093
+ * the item's `type`), its status `orphan`, the word {@link observeAmbient}
1094
+ * gives the same object, and its ownership `owned`, since the estate's marker
1095
+ * or record bound it. Its facts are the engine graph's node for the address
1096
+ * with the address's rows under `ownershipRows`: `boundBy`, `listed` and the
1097
+ * gaps from `live-graph` and `live-ls`.
1098
+ *
1099
+ * Empty when every bound address and listed item is declared, so such a root
1100
+ * reads exactly as before.
1101
+ */
1102
+ export function undeclaredBound(root, declared, index, listing, read) {
1103
+ const rows = ownershipRowsByAddress(index, listing);
1104
+ const listedItems = new Map();
1105
+ for (const item of listing?.items ?? []) {
1106
+ if (!item.declared)
1107
+ listedItems.set(item.address ?? item.id, item);
1108
+ }
1109
+ const addresses = new Set();
1110
+ for (const address of index.bound.keys())
1111
+ if (!declaresAddress(address, declared))
1112
+ addresses.add(address);
1113
+ for (const address of listedItems.keys())
1114
+ if (!declaresAddress(address, declared))
1115
+ addresses.add(address);
1116
+ const estate = index.estate || listing?.estate || "";
1117
+ const out = {};
1118
+ for (const address of [...addresses].sort()) {
1119
+ const bound = index.bound.get(address);
1120
+ const item = listedItems.get(address);
1121
+ const type = bound?.type ?? item?.type;
1122
+ if (!type)
1123
+ continue;
1124
+ const key = entityKeyFor(root, address);
1125
+ // An object only the listing names is listed, though no bound row says so.
1126
+ const facts = withOwnershipRows(engineFactsAt(read, key, address), mergeOwnershipRows(rows.get(address), item ? { listed: true } : undefined));
1127
+ // A marker was read when the plan bound it by marker, or the listing found it by its tags.
1128
+ const byMarker = bound ? bound.source === "marker" : item !== undefined;
1129
+ out[key] = {
1130
+ type,
1131
+ physicalId: bound?.identity ?? item?.id ?? address,
1132
+ status: "orphan",
1133
+ ownership: "owned",
1134
+ ...(byMarker && estate ? { marker: { stack: estate } } : {}),
1135
+ ambient: true,
1136
+ attributes: {
1137
+ address,
1138
+ root,
1139
+ estate,
1140
+ resourceType: type,
1141
+ status: "orphan",
1142
+ ...(bound?.source ? { boundBy: bound.source } : {}),
1143
+ ...(item?.slot ? { slot: item.slot } : {}),
1144
+ ...(item?.source ? { listedBy: item.source } : {}),
1145
+ },
1146
+ ...(facts ? { facts } : {}),
1147
+ };
1148
+ }
1149
+ return out;
1150
+ }
923
1151
  /** Parse a `live-ls -json` document. A missing section reads as empty, never as a throw. */
924
1152
  export function readLiveLs(document) {
925
1153
  const doc = asRecord(document);
@@ -1536,14 +1764,20 @@ export async function describeResources(options, deps = REAL_DEPS) {
1536
1764
  const sources = {};
1537
1765
  const rootReads = {};
1538
1766
  const edges = [];
1767
+ const engineReads = [];
1768
+ // Bound objects no block declares (#5429), as live nodes beside the read.
1769
+ const undeclared = {};
1539
1770
  // A live root's observation with the engine graph's facts and edges on it (#4528).
1540
- const withEngineGraph = async (root, handoff, observed) => {
1771
+ const withEngineGraph = async (root, declared, handoff, observed) => {
1541
1772
  const graph = await engineGraphFor(root, options.cwd, deps, handoff);
1542
1773
  if (graph.note)
1543
1774
  notes.push(graph.note);
1775
+ if (handoff.json !== undefined)
1776
+ Object.assign(undeclared, undeclaredBound(root, declared, indexLivePlan(handoff.json), graph.listing, graph.read));
1544
1777
  if (!graph.read)
1545
1778
  return observed;
1546
1779
  edges.push(...graph.read.edges);
1780
+ engineReads.push(graph.read);
1547
1781
  return { ...observed, resources: withEngineFacts(observed.resources, graph.read) };
1548
1782
  };
1549
1783
  const depthOf = byRoot.size > 0 ? await observeDepths(options, notes) : () => "state";
@@ -1568,14 +1802,14 @@ export async function describeResources(options, deps = REAL_DEPS) {
1568
1802
  rootReads[`terraform.roots.${root}`] = outcome.read;
1569
1803
  if (outcome.note)
1570
1804
  notes.push(outcome.note);
1571
- parts.push(await withEngineGraph(root, handoff, normalizeObservation(read)));
1805
+ parts.push(await withEngineGraph(root, declared, handoff, normalizeObservation(read)));
1572
1806
  continue;
1573
1807
  }
1574
1808
  for (const entity of declared)
1575
1809
  sources[entity.name] = "live";
1576
1810
  const handoff = {};
1577
1811
  const read = await observeEntities(declared, liveAdapter(root, options.cwd, deps, handoff));
1578
- parts.push(await withEngineGraph(root, handoff, normalizeObservation(read)));
1812
+ parts.push(await withEngineGraph(root, declared, handoff, normalizeObservation(read)));
1579
1813
  continue;
1580
1814
  }
1581
1815
  if (depth === "plan") {
@@ -1626,6 +1860,14 @@ export async function describeResources(options, deps = REAL_DEPS) {
1626
1860
  }
1627
1861
  }
1628
1862
  // A planned create's plan attributes (#4372) ride beside the verdict, never
1629
- // in `resources`: the block stays absent.
1630
- return observation(resources, unobserved, merged.queried, merged.notes, undefined, sources, merged.annotations, rootReads, edges);
1863
+ // in `resources`: the block stays absent. So do the engine's facts about
1864
+ // what no live node will carry (#5333), after --owned has filtered.
1865
+ const result = observation(resources, unobserved, merged.queried, merged.notes, undefined, sources, merged.annotations, rootReads, edges);
1866
+ // An undeclared object's facts ride on its own node (#5429), not beside.
1867
+ const beside = engineFactsBeside({ ...undeclared, ...resources }, engineReads);
1868
+ return {
1869
+ ...result,
1870
+ ...(Object.keys(beside).length > 0 ? { engineFacts: beside } : {}),
1871
+ ...(Object.keys(undeclared).length > 0 ? { undeclared } : {}),
1872
+ };
1631
1873
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `classifyDisruption` for terraform (#5338): what applying a planned update
3
+ * costs, from the plan's own `actions`.
4
+ *
5
+ * Terraform already says it. A `resource_changes[]` entry's
6
+ * `change.actions` is `["update"]` for a change in place, `["create",
7
+ * "delete"]` for a replacement created before the old one goes
8
+ * (`create_before_destroy`), `["delete", "create"]` for one that deletes
9
+ * first, and `["delete"]` for a removal. `replace_paths` names the
10
+ * attributes that forced a replacement.
11
+ *
12
+ * | actions | disruption |
13
+ * |---|---|
14
+ * | `update` | `in-place` |
15
+ * | `create`, `delete` | `replace` |
16
+ * | `delete`, `create` | `destroy` |
17
+ * | `delete` | `destroy` |
18
+ *
19
+ * The classifier answers through core's contract, from the attributes the
20
+ * plan depth puts on each block (`planActions`, keyed by instance, and
21
+ * `planReplacePaths`, see `./plan-observation.ts`). A block's verdict is its
22
+ * most disruptive instance's. A query whose attributes carry no plan gets no
23
+ * verdict, which core reads as `unknown`. {@link terraformDisruptionQueries}
24
+ * builds the same queries straight from a `show -json` plan, one per
25
+ * resource change, for a caller holding the plan rather than a read.
26
+ *
27
+ * The table itself is `terraformActionsDisruption` in `./change-set.ts`,
28
+ * which the change set adapter reads too, so the two agree and the change
29
+ * set bundle stays as light as it was.
30
+ */
31
+ import type { DisruptionQuery, DisruptionVerdict } from "@intentius/chant/lexicon";
32
+ import { terraformActionsDisruption } from "./change-set.js";
33
+ export { terraformActionsDisruption };
34
+ /** One query's verdict, or undefined when its attributes carry no plan. */
35
+ export declare function terraformQueryVerdict(query: DisruptionQuery): DisruptionVerdict | undefined;
36
+ /** `LexiconPlugin.classifyDisruption` for terraform. */
37
+ export declare function classifyTerraformDisruption(options: {
38
+ environment: string;
39
+ changes: DisruptionQuery[];
40
+ }): Record<string, DisruptionVerdict>;
41
+ /**
42
+ * The queries a `show -json` plan holds: one per `resource_changes[]` entry
43
+ * that changes something existing (an update, a replacement or a delete),
44
+ * named by its address, with the plan's actions and replace paths as the
45
+ * attributes the classifier reads.
46
+ */
47
+ export declare function terraformDisruptionQueries(plan: unknown): DisruptionQuery[];
@@ -0,0 +1,74 @@
1
+ import { terraformActionsDisruption } from "./change-set.js";
2
+ import { indexPlan } from "./plan-observation.js";
3
+ export { terraformActionsDisruption };
4
+ const RANK = { "in-place": 0, replace: 1, destroy: 2 };
5
+ const DETAIL = {
6
+ "in-place": "the plan updates it in place",
7
+ replace: "the plan creates a replacement, then deletes the old one",
8
+ destroy: "the plan deletes it before anything replaces it",
9
+ };
10
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /** One attribute off the query: its observed value, else the new value of a delta on it. */
12
+ function attribute(query, key) {
13
+ if (query.attributes && key in query.attributes)
14
+ return query.attributes[key];
15
+ return query.deltas.find((d) => d.path === `attributes.${key}`)?.newValue;
16
+ }
17
+ /** One query's verdict, or undefined when its attributes carry no plan. */
18
+ export function terraformQueryVerdict(query) {
19
+ const planActions = attribute(query, "planActions");
20
+ if (!isRecord(planActions))
21
+ return undefined;
22
+ let worst;
23
+ for (const actions of Object.values(planActions)) {
24
+ const d = terraformActionsDisruption(actions);
25
+ if (d && (!worst || RANK[d] > RANK[worst]))
26
+ worst = d;
27
+ }
28
+ if (!worst)
29
+ return undefined;
30
+ const paths = attribute(query, "planReplacePaths");
31
+ const because = worst !== "in-place" && Array.isArray(paths) ? paths.filter((p) => typeof p === "string") : [];
32
+ return {
33
+ disruption: worst,
34
+ ...(because.length > 0 ? { because } : {}),
35
+ detail: because.length > 0 ? `${DETAIL[worst]}; ${because.join(", ")} forced it` : DETAIL[worst],
36
+ };
37
+ }
38
+ /** `LexiconPlugin.classifyDisruption` for terraform. */
39
+ export function classifyTerraformDisruption(options) {
40
+ const out = {};
41
+ for (const query of options.changes) {
42
+ const verdict = terraformQueryVerdict(query);
43
+ if (verdict)
44
+ out[query.name] = verdict;
45
+ }
46
+ return out;
47
+ }
48
+ /**
49
+ * The queries a `show -json` plan holds: one per `resource_changes[]` entry
50
+ * that changes something existing (an update, a replacement or a delete),
51
+ * named by its address, with the plan's actions and replace paths as the
52
+ * attributes the classifier reads.
53
+ */
54
+ export function terraformDisruptionQueries(plan) {
55
+ const index = indexPlan(plan);
56
+ const out = [];
57
+ const raw = isRecord(plan) && Array.isArray(plan.resource_changes) ? plan.resource_changes.filter(isRecord) : [];
58
+ for (const rc of raw) {
59
+ const address = typeof rc.address === "string" ? rc.address : undefined;
60
+ const change = address ? index.changes.get(address) : undefined;
61
+ if (!address || !change || !terraformActionsDisruption(change.actions))
62
+ continue;
63
+ out.push({
64
+ name: address,
65
+ ...(typeof rc.type === "string" ? { type: rc.type } : {}),
66
+ deltas: [],
67
+ attributes: {
68
+ planActions: { [address]: change.actions },
69
+ ...(change.replacePaths.length > 0 ? { planReplacePaths: change.replacePaths } : {}),
70
+ },
71
+ });
72
+ }
73
+ return out;
74
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Health for a terraform root (#5338), through the provider lexicons.
3
+ *
4
+ * This lexicon reads no provider API. A root's `aws_ecs_service` is the same
5
+ * object the aws lexicon reads as `AWS::ECS::Service`, so `chant lifecycle
6
+ * health` hands it to that reader. What this lexicon adds is the two facts
7
+ * the reader cannot find on its own: which health type the resource is
8
+ * ({@link TERRAFORM_HEALTH_TYPES}), and the id the root's state recorded for
9
+ * it, read by the same state read `describeResources` makes. The aws reader
10
+ * otherwise finds ids through CloudFormation's `describeStackResources`,
11
+ * which knows nothing of a terraform root.
12
+ *
13
+ * A block expanded with `count` or `for_each` is one target per instance,
14
+ * named by its instance node id (`app/aws_ecs_service.api[0]`). A
15
+ * `resource` block of any other type goes in `uncovered`, and core reports it
16
+ * `unknown`: nothing reads whether it is up. Other blocks (variables, data
17
+ * sources, modules) are not resources and are left out.
18
+ */
19
+ import type { HealthReadOptions, HealthTargetsResult } from "@intentius/chant/lexicon";
20
+ import type { DescribeResourcesResult } from "@intentius/chant/lexicon";
21
+ /**
22
+ * Each terraform resource type a provider lexicon reads health for, with
23
+ * that lexicon and its health type. The docs page on health lists the same
24
+ * table.
25
+ */
26
+ export declare const TERRAFORM_HEALTH_TYPES: Readonly<Record<string, {
27
+ lexicon: string;
28
+ type: string;
29
+ }>>;
30
+ /** The read the targets take their ids from: the lexicon's `describeResources`, at the state depth. */
31
+ export type TerraformIdRead = (options: {
32
+ environment: string;
33
+ buildOutput: string;
34
+ entityNames: string[];
35
+ entities: Map<string, {
36
+ entityType: string;
37
+ props: Record<string, unknown>;
38
+ }>;
39
+ depth: "state";
40
+ }) => Promise<DescribeResourcesResult>;
41
+ /** `LexiconPlugin.healthTargets` for terraform. */
42
+ export declare function terraformHealthTargets(options: HealthReadOptions, read?: TerraformIdRead): Promise<HealthTargetsResult>;
@@ -0,0 +1,96 @@
1
+ import { normalizeObservation } from "@intentius/chant/observation";
2
+ import { observedInstanceNodeId } from "@intentius/chant/instance-nodes";
3
+ import { RESOURCE_TYPE } from "./hcl/parse.js";
4
+ /**
5
+ * Each terraform resource type a provider lexicon reads health for, with
6
+ * that lexicon and its health type. The docs page on health lists the same
7
+ * table.
8
+ */
9
+ export const TERRAFORM_HEALTH_TYPES = {
10
+ aws_route53_health_check: { lexicon: "aws", type: "AWS::Route53::HealthCheck" },
11
+ aws_ecs_service: { lexicon: "aws", type: "AWS::ECS::Service" },
12
+ azurerm_container_app: { lexicon: "azure", type: "Microsoft.App/containerApps" },
13
+ google_cloud_run_v2_service: { lexicon: "gcp", type: "GCP::Run::Service" },
14
+ google_cloud_run_service: { lexicon: "gcp", type: "GCP::Run::Service" },
15
+ google_compute_backend_service: { lexicon: "gcp", type: "GCP::Compute::BackendService" },
16
+ google_compute_region_backend_service: { lexicon: "gcp", type: "GCP::Compute::BackendService" },
17
+ google_project_iam_member: { lexicon: "gcp", type: "GCP::Iam::PolicyMember" },
18
+ };
19
+ const defaultRead = async (options) => {
20
+ const { describeResources } = await import("./describe-resources.js");
21
+ return describeResources(options);
22
+ };
23
+ /** The terraform resource type of a declared entity, or undefined for a block that is not a `resource`. */
24
+ function resourceTypeOf(entity) {
25
+ if (entity.entityType !== RESOURCE_TYPE)
26
+ return undefined;
27
+ const type = entity.props.type;
28
+ return typeof type === "string" && type.length > 0 ? type : undefined;
29
+ }
30
+ /** `LexiconPlugin.healthTargets` for terraform. */
31
+ export async function terraformHealthTargets(options, read = defaultRead) {
32
+ const covered = new Map();
33
+ const kinds = new Map();
34
+ const uncovered = {};
35
+ for (const [name, entity] of options.entities) {
36
+ const type = resourceTypeOf(entity);
37
+ if (!type)
38
+ continue;
39
+ if (TERRAFORM_HEALTH_TYPES[type]) {
40
+ covered.set(name, entity);
41
+ kinds.set(name, type);
42
+ }
43
+ else {
44
+ uncovered[name] = type;
45
+ }
46
+ }
47
+ const targets = {};
48
+ const unobserved = {};
49
+ const absent = [];
50
+ if (covered.size === 0)
51
+ return { targets, unobserved, absent, uncovered };
52
+ const observed = normalizeObservation(await read({
53
+ environment: options.environment,
54
+ buildOutput: options.buildOutput,
55
+ entityNames: [...covered.keys()],
56
+ entities: covered,
57
+ depth: "state",
58
+ }));
59
+ for (const [name] of covered) {
60
+ const engineType = kinds.get(name);
61
+ const { lexicon, type } = TERRAFORM_HEALTH_TYPES[engineType];
62
+ const target = (physicalId) => ({ lexicon, type, engineType, physicalId });
63
+ const hole = observed.unobserved[name];
64
+ const present = observed.resources[name];
65
+ if (hole) {
66
+ unobserved[name] = { type, reason: hole.reason, ...(hole.detail ? { detail: hole.detail } : {}) };
67
+ continue;
68
+ }
69
+ if (!present) {
70
+ absent.push(name);
71
+ continue;
72
+ }
73
+ const instances = present.instances ?? [];
74
+ if (instances.length > 0) {
75
+ for (const inst of instances) {
76
+ const id = observedInstanceNodeId(name, inst) ?? `${name}${inst.key ?? ""}`;
77
+ if (inst.verdict === "absent")
78
+ absent.push(id);
79
+ else if (inst.verdict !== "present")
80
+ unobserved[id] = { type, reason: "read-failed", detail: `the state read did not observe ${inst.address}` };
81
+ else if (!inst.physicalId)
82
+ unobserved[id] = { type, reason: "read-failed", detail: `the state records no id for ${inst.address}` };
83
+ else
84
+ targets[id] = target(inst.physicalId);
85
+ }
86
+ continue;
87
+ }
88
+ const address = typeof present.attributes?.address === "string" ? present.attributes.address : undefined;
89
+ if (!present.physicalId || present.physicalId === address) {
90
+ unobserved[name] = { type, reason: "read-failed", detail: `the state records no id for ${address ?? name}` };
91
+ continue;
92
+ }
93
+ targets[name] = target(present.physicalId);
94
+ }
95
+ return { targets, unobserved, absent, uncovered };
96
+ }