@intentius/chant-lexicon-terraform 0.124.76 → 0.124.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/drift-record.d.ts +24 -0
  2. package/dist/drift-record.d.ts.map +1 -1
  3. package/dist/drift-record.js +52 -0
  4. package/dist/drift-rows.d.ts +49 -4
  5. package/dist/drift-rows.d.ts.map +1 -1
  6. package/dist/drift-rows.js +87 -19
  7. package/dist/integrity.json +2 -2
  8. package/dist/manifest.json +1 -1
  9. package/dist/pr-env.d.ts +138 -0
  10. package/dist/pr-env.d.ts.map +1 -0
  11. package/dist/pr-env.js +248 -0
  12. package/dist/state/gitlab.d.ts +74 -0
  13. package/dist/state/gitlab.d.ts.map +1 -0
  14. package/dist/state/gitlab.js +275 -0
  15. package/dist/state/index.d.ts +2 -0
  16. package/dist/state/index.d.ts.map +1 -1
  17. package/dist/state/index.js +2 -0
  18. package/dist/state/store.d.ts +2 -1
  19. package/dist/state/store.d.ts.map +1 -1
  20. package/dist/state/versions.d.ts +39 -0
  21. package/dist/state/versions.d.ts.map +1 -0
  22. package/dist/state/versions.js +85 -0
  23. package/dist/state-migration.d.ts +85 -0
  24. package/dist/state-migration.d.ts.map +1 -0
  25. package/dist/state-migration.js +296 -0
  26. package/dist/state-ops.d.ts +54 -87
  27. package/dist/state-ops.d.ts.map +1 -1
  28. package/dist/state-ops.js +120 -77
  29. package/package.json +2 -2
  30. package/src/__fixtures__/drift-rows/refresh-plan-module.json +48 -0
  31. package/src/drift-record.test.ts +62 -0
  32. package/src/drift-record.ts +58 -0
  33. package/src/drift-rows.test.ts +90 -1
  34. package/src/drift-rows.ts +89 -18
  35. package/src/pr-env.test.ts +132 -0
  36. package/src/pr-env.ts +312 -0
  37. package/src/state/gitlab.test.ts +226 -0
  38. package/src/state/gitlab.ts +318 -0
  39. package/src/state/index.ts +2 -0
  40. package/src/state/store.ts +2 -1
  41. package/src/state/versions.ts +103 -0
  42. package/src/state-export-unlock.test.ts +230 -0
  43. package/src/state-migration.test.ts +236 -0
  44. package/src/state-migration.ts +353 -0
  45. package/src/state-ops.ts +132 -130
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A root's state read by version (#4762), for chant core's state export
3
+ * (`@intentius/chant/state-export`): the version a bucket or container
4
+ * holds now, whether it holds another, and one version's text.
5
+ *
6
+ * s3 bucket versioning: the object's `x-amz-version-id`
7
+ * gcs object versioning: a version is a generation
8
+ * azurerm blob versioning: the blob's `x-ms-version-id`; with none, the
9
+ * snapshots the backend takes when it sets `snapshot = true`, and
10
+ * a request for the current version takes one, whose id names it
11
+ * http a GitLab-managed state (./gitlab.ts): GitLab keeps each version
12
+ * by its serial, so the version id is the serial
13
+ *
14
+ * A local state keeps no versions, and is refused. Nothing here writes a
15
+ * state; the one write is the azurerm snapshot above.
16
+ *
17
+ * Lifted from terragucci's `backend.ts` (`version`, `hasVersion`,
18
+ * `readVersion` of its stores), so terragucci deletes its copy.
19
+ */
20
+ import type { StateVersionSource } from "@intentius/chant/state-export";
21
+ import { type StateObject } from "./backend.js";
22
+ import type { GitLabStateStore } from "./gitlab.js";
23
+ import type { StoreFetch } from "./object-store.js";
24
+ /** What the version reads cover, for a refusal. */
25
+ export declare const READS_VERSIONS = "a state export reads versions of s3, gcs and azurerm states and GitLab-managed state";
26
+ /**
27
+ * A root's state as a version source, or why it has none: a refused backend,
28
+ * or a local state, which keeps no versions. With `pin: false` an azurerm
29
+ * blob that keeps no versions names none for its current state, where the
30
+ * default takes a snapshot to name it.
31
+ */
32
+ export declare function stateVersionSource(o: StateObject, fetchFn?: StoreFetch, options?: {
33
+ pin?: boolean;
34
+ }): StateVersionSource | {
35
+ refused: string;
36
+ };
37
+ /** A GitLab-managed state as a version source: the version id is the serial. */
38
+ export declare function gitlabVersionSource(store: GitLabStateStore): StateVersionSource;
39
+ //# sourceMappingURL=versions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"versions.d.ts","sourceRoot":"","sources":["../../src/state/versions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,KAAK,EAAgB,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEtF,OAAO,EAA4B,KAAK,WAAW,EAAoB,MAAM,WAAW,CAAC;AAEzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGjD,mDAAmD;AACnD,eAAO,MAAM,cAAc,yFAAyF,CAAC;AAiDrH;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,UAAU,EAAE,OAAO,GAAE;IAAE,GAAG,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,kBAAkB,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAMlJ;AAED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,gBAAgB,GAAG,kBAAkB,CAU/E"}
@@ -0,0 +1,85 @@
1
+ import { AzureBlobClient } from "./azure-blob.js";
2
+ import { isRefused, stateLocation } from "./backend.js";
3
+ import { GcsClient } from "./gcs.js";
4
+ import { S3Client } from "./s3.js";
5
+ /** What the version reads cover, for a refusal. */
6
+ export const READS_VERSIONS = "a state export reads versions of s3, gcs and azurerm states and GitLab-managed state";
7
+ function s3Versions(o, fetchFn) {
8
+ const client = new S3Client(o.target, fetchFn);
9
+ return {
10
+ location: `s3://${o.bucket}/${o.key}`,
11
+ async current() {
12
+ const head = await client.head(o.key);
13
+ if (!head.exists)
14
+ return { exists: false };
15
+ return head.versionId ? { exists: true, versionId: head.versionId } : { exists: true, off: `bucket versioning is off for ${o.bucket}, so it keeps only the latest state` };
16
+ },
17
+ hasVersion: (id) => client.hasVersion(o.key, id),
18
+ readVersion: (id) => client.readVersion(o.key, id),
19
+ };
20
+ }
21
+ function gcsVersions(o, fetchFn) {
22
+ const client = new GcsClient(o.target, fetchFn);
23
+ return {
24
+ location: `gs://${o.bucket}/${o.key}`,
25
+ async current() {
26
+ const head = await client.head(o.key);
27
+ if (!head.exists)
28
+ return { exists: false };
29
+ if ((await client.versioning()) === false)
30
+ return { exists: true, off: `object versioning is off for ${o.bucket}, so it keeps only the latest state` };
31
+ return { exists: true, ...(head.generation ? { versionId: head.generation } : {}) };
32
+ },
33
+ hasVersion: async (id) => (await client.head(o.key, id)).exists,
34
+ readVersion: (id) => client.readGeneration(o.key, id),
35
+ };
36
+ }
37
+ function azureVersions(o, fetchFn, pin = true) {
38
+ const client = new AzureBlobClient({ account: o.account, container: o.container, endpoint: o.endpoint, ...o.auth }, fetchFn);
39
+ // A blob that keeps versions names each by its version id; else by a snapshot.
40
+ const at = async (id) => ((await client.head(o.key)).versionId ? { versionid: id } : { snapshot: id });
41
+ return {
42
+ location: `az://${o.account}/${o.container}/${o.key}`,
43
+ async current() {
44
+ const head = await client.head(o.key);
45
+ if (!head.exists)
46
+ return { exists: false };
47
+ if (head.versionId)
48
+ return { exists: true, versionId: head.versionId };
49
+ if (!o.snapshot)
50
+ return { exists: true, off: `blob versioning is off for ${o.account}, and the backend takes no snapshots (snapshot = true), so it keeps only the latest state` };
51
+ return pin ? { exists: true, versionId: await client.snapshot(o.key) } : { exists: true, off: "the blob keeps no versions, and only a snapshot would name this one" };
52
+ },
53
+ hasVersion: async (id) => (await client.head(o.key, await at(id))).exists,
54
+ readVersion: async (id) => client.readAt(o.key, await at(id)),
55
+ };
56
+ }
57
+ /**
58
+ * A root's state as a version source, or why it has none: a refused backend,
59
+ * or a local state, which keeps no versions. With `pin: false` an azurerm
60
+ * blob that keeps no versions names none for its current state, where the
61
+ * default takes a snapshot to name it.
62
+ */
63
+ export function stateVersionSource(o, fetchFn, options = {}) {
64
+ if (isRefused(o))
65
+ return { refused: o.reason };
66
+ if (o.backend === "local")
67
+ return { refused: `the state is a local file, ${stateLocation(o)}, which keeps no versions; ${READS_VERSIONS}` };
68
+ if (o.backend === "s3")
69
+ return s3Versions(o, fetchFn);
70
+ if (o.backend === "gcs")
71
+ return gcsVersions(o, fetchFn);
72
+ return azureVersions(o, fetchFn, options.pin ?? true);
73
+ }
74
+ /** A GitLab-managed state as a version source: the version id is the serial. */
75
+ export function gitlabVersionSource(store) {
76
+ return {
77
+ location: store.location,
78
+ async current() {
79
+ const now = await store.serial();
80
+ return now ? { exists: true, versionId: String(now.serial) } : { exists: false };
81
+ },
82
+ hasVersion: async (id) => /^\d+$/.test(id) && (await store.hasVersion(id)),
83
+ readVersion: (id) => store.readVersion(id),
84
+ };
85
+ }
@@ -0,0 +1,85 @@
1
+ import type { MigrationRootPlan, StateMigrationEngine } from "@intentius/chant/state-migration";
2
+ import { type RootRun } from "./state-ops.js";
3
+ import { type BinaryExec, type StateFile, type StateResource } from "./state/exec.js";
4
+ import { type LockOperation } from "./state/locks.js";
5
+ import type { StoreFetch } from "./state/object-store.js";
6
+ /** Resources that move from one root's state to another's. */
7
+ export interface Move {
8
+ from: string;
9
+ to: string;
10
+ addresses: string[];
11
+ }
12
+ /** A root's state put back to a version a migration recorded. */
13
+ export interface Restore {
14
+ root: string;
15
+ /** Where the state is, as the migration recorded it. */
16
+ location: string;
17
+ /** The version to put back; null when the root had no state before, so it gets an empty one. */
18
+ version_id: string | null;
19
+ /** The version the migration left: a state that moved past it is refused. */
20
+ from_version_id: string | null;
21
+ }
22
+ /** A migration that cannot be planned: an address in no state, a root that is refused. Nothing was written. */
23
+ export declare class MigrationError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /** A state's digest: sha256 of its JSON as parsed and written back, so whitespace never moves it. */
27
+ export declare const stateDigest: (s: StateFile) => string;
28
+ /** Whether a migration address names a state entry: the managed resource itself, or a module call it sits in, with its data sources. */
29
+ export declare function addressMatches(address: string, r: StateResource): boolean;
30
+ /** A lineage that a migration and a root always give the same: a state planned twice has one digest. */
31
+ export declare function derivedLineage(...parts: string[]): string;
32
+ /**
33
+ * The states after the moves. `before` holds each affected root's state, or
34
+ * null when it has none. A changed state keeps its lineage and gets the next
35
+ * serial; a root with no state gets a new one, its lineage derived from the
36
+ * migration and the root. Throws MigrationError naming every address that
37
+ * is in no state, or already in the root it moves to.
38
+ */
39
+ export declare function moveResources(name: string, moves: readonly Move[], before: ReadonlyMap<string, StateFile | null>): Map<string, StateFile>;
40
+ /** The resource changes of a plan's JSON, as `<address>: <actions>`; no-ops and reads are not changes. */
41
+ export declare function resourceChanges(plan: unknown): string[];
42
+ /** A terraform block whose backend is the local file `path`, for the proof plan's override file. Terraform and OpenTofu merge any `*_override.tf` over the root's files. */
43
+ export declare const localBackendOverride: (path: string) => string;
44
+ /** The override file a proof plan writes into a root, and removes, unless the product names its own. */
45
+ export declare const DEFAULT_OVERRIDE_FILE = "chant_migrate_override.tf";
46
+ /** What a migration's lock says, unless the product names its own. */
47
+ export declare const DEFAULT_MIGRATE_LOCK: LockOperation;
48
+ /** One root a migration reads or writes. */
49
+ export interface MigrationRootRun extends Omit<RootRun, "exec"> {
50
+ /** Run `init` in a data dir of the migration's own (default), or false for a root another tool initialised in `dir` with `env`. */
51
+ init?: boolean;
52
+ }
53
+ export interface TerraformMigrationInput {
54
+ /** The migration's name: what its gate is called, and what a new root's lineage derives from. */
55
+ name: string;
56
+ /** Resources that move between roots. */
57
+ moves?: Move[];
58
+ /** States put back to a version a migration recorded. */
59
+ restores?: Restore[];
60
+ /** Every root the moves or restores name. */
61
+ roots: MigrationRootRun[];
62
+ /** The work dir: new states, plans and data dirs. The caller removes it. */
63
+ work: string;
64
+ exec?: BinaryExec;
65
+ fetch?: StoreFetch;
66
+ /** What the migration's lock says. */
67
+ lock?: LockOperation;
68
+ /** Who the lock names. Default `chant@<host>`. */
69
+ who?: string;
70
+ /** The proof plan's override file. Default {@link DEFAULT_OVERRIDE_FILE}. */
71
+ overrideFile?: string;
72
+ log?: (line: string) => void;
73
+ }
74
+ /** A planned migration: each root's plan for core, and the engine that writes it. */
75
+ export interface TerraformMigrationPlan {
76
+ roots: MigrationRootPlan[];
77
+ engine: StateMigrationEngine;
78
+ }
79
+ /**
80
+ * Plan a migration: read every affected state and its version, build the new
81
+ * states in `work`, and plan each root against its new state. Throws
82
+ * MigrationError for a root that is refused or a move that does not fit.
83
+ */
84
+ export declare function planTerraformMigration(input: TerraformMigrationInput): Promise<TerraformMigrationPlan>;
85
+ //# sourceMappingURL=state-migration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-migration.d.ts","sourceRoot":"","sources":["../src/state-migration.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,296 @@
1
+ /**
2
+ * A state migration between Terraform roots (#4762), for chant core's
3
+ * gated migration (`@intentius/chant/state-migration`): what `moved`,
4
+ * `import` and `removed` blocks cannot do, because each works inside one
5
+ * root's state.
6
+ *
7
+ * moves resources (`[module.<m>.]<type>.<name>`) or module calls
8
+ * (`module.<m>`), with every instance, from one root's state to
9
+ * the same address in another's
10
+ * restores a root's state put back to a version a migration recorded (a
11
+ * revert), refused when the state moved past what that
12
+ * migration left
13
+ *
14
+ * Planning (planTerraformMigration) initialises each root in a data dir of
15
+ * its own, reads its backend version id and pulls its state, keeps only
16
+ * their digests, builds each new state in the work dir, and plans each root
17
+ * against its new state through a local-backend override file and another
18
+ * data dir, so the root's own `.terraform` and its real state are not
19
+ * touched. The engine it returns writes the new states for core under each
20
+ * stored state's lock (s3's lock file, the gcs lock object, the azurerm
21
+ * lease, as `./state/locks.ts` takes them): `state push -lock=false`, or a
22
+ * write under the lease on azurerm, the roots that gain resources first, so
23
+ * a write that stops half way leaves a resource in two states rather than
24
+ * in none. Then each root plans against its real backend.
25
+ *
26
+ * State contents never leave the work dir. The record holds version ids and
27
+ * digests.
28
+ *
29
+ * Lifted from terragucci's `migrate.ts` (`moveResources`, `addressMatches`,
30
+ * `derivedLineage`, `stateDigest`, `resourceChanges`, `backendBlock`,
31
+ * `proofPlan`, `planMigration`'s moves and reverts, `applyMigration`,
32
+ * `movedSince`), so terragucci deletes its copy. A backend move (a state
33
+ * read from another backend, a TFE workspace or an exported file) and a
34
+ * migration of choudoufu's live estates stay terragucci's for now.
35
+ */
36
+ import { createHash } from "node:crypto";
37
+ import { hostname } from "node:os";
38
+ import { join, resolve } from "node:path";
39
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
40
+ import { initRoot, planStateCheck, pushStateFile } from "./state-ops.js";
41
+ import { isRefused, isStored, stateLocation, stateObject } from "./state/backend.js";
42
+ import { pullState, runBinary } from "./state/exec.js";
43
+ import { takeLocksWithSources } from "./state/locks.js";
44
+ import { stateStore } from "./state/store.js";
45
+ import { stateVersionSource } from "./state/versions.js";
46
+ /** A migration that cannot be planned: an address in no state, a root that is refused. Nothing was written. */
47
+ export class MigrationError extends Error {
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "MigrationError";
51
+ }
52
+ }
53
+ const sha = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
54
+ /** A state's digest: sha256 of its JSON as parsed and written back, so whitespace never moves it. */
55
+ export const stateDigest = (s) => sha(JSON.stringify(s));
56
+ /** A resource entry's address without instance keys: `module.a.module.b.type.name`, module keys dropped. */
57
+ const resourceAddress = (r) => `${r.module ? `${r.module.replace(/\[[^\]]*\]/g, "")}.` : ""}${r.mode === "data" ? "data." : ""}${r.type}.${r.name}`;
58
+ const moduleOf = (r) => (r.module ?? "").replace(/\[[^\]]*\]/g, "");
59
+ /** Whether a migration address names a state entry: the managed resource itself, or a module call it sits in, with its data sources. */
60
+ export function addressMatches(address, r) {
61
+ if (/(^|\.)module\.[A-Za-z_][\w-]*$/.test(address))
62
+ return moduleOf(r) === address || moduleOf(r).startsWith(`${address}.`);
63
+ return r.mode === "managed" && resourceAddress(r) === address;
64
+ }
65
+ /** A lineage that a migration and a root always give the same: a state planned twice has one digest. */
66
+ export function derivedLineage(...parts) {
67
+ const h = createHash("sha256").update(parts.join("\n")).digest("hex");
68
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
69
+ }
70
+ const emptyState = (lineage, serial, terraformVersion = "1.0.0") => ({ version: 4, terraform_version: terraformVersion, serial, lineage, outputs: {}, resources: [], check_results: null });
71
+ /**
72
+ * The states after the moves. `before` holds each affected root's state, or
73
+ * null when it has none. A changed state keeps its lineage and gets the next
74
+ * serial; a root with no state gets a new one, its lineage derived from the
75
+ * migration and the root. Throws MigrationError naming every address that
76
+ * is in no state, or already in the root it moves to.
77
+ */
78
+ export function moveResources(name, moves, before) {
79
+ const after = new Map();
80
+ const take = (root, from) => {
81
+ const held = after.get(root);
82
+ if (held)
83
+ return held;
84
+ const was = before.get(root) ?? null;
85
+ const s = was ? { ...structuredClone(was), serial: was.serial + 1 } : emptyState(derivedLineage(name, root), 1, from?.terraform_version);
86
+ after.set(root, s);
87
+ return s;
88
+ };
89
+ const problems = [];
90
+ for (const m of moves) {
91
+ const src = before.get(m.from) ?? null;
92
+ if (!src) {
93
+ problems.push(`${m.from} has no state to move ${m.addresses.join(", ")} from`);
94
+ continue;
95
+ }
96
+ const from = take(m.from);
97
+ const to = take(m.to, src);
98
+ for (const address of m.addresses) {
99
+ const found = from.resources.filter((r) => addressMatches(address, r));
100
+ if (found.length === 0) {
101
+ problems.push(`${address} is not in the state of ${m.from}`);
102
+ continue;
103
+ }
104
+ if (to.resources.some((r) => addressMatches(address, r))) {
105
+ problems.push(`${address} is already in the state of ${m.to}`);
106
+ continue;
107
+ }
108
+ from.resources = from.resources.filter((r) => !found.includes(r));
109
+ to.resources.push(...found);
110
+ }
111
+ }
112
+ if (problems.length > 0)
113
+ throw new MigrationError(`migration ${name}:\n ${problems.join("\n ")}`);
114
+ return after;
115
+ }
116
+ /** The resource changes of a plan's JSON, as `<address>: <actions>`; no-ops and reads are not changes. */
117
+ export function resourceChanges(plan) {
118
+ const rc = plan?.resource_changes ?? [];
119
+ return rc
120
+ .filter((c) => {
121
+ const a = c.change?.actions ?? [];
122
+ return !(a.length === 1 && (a[0] === "no-op" || a[0] === "read"));
123
+ })
124
+ .map((c) => `${c.address}: ${(c.change?.actions ?? []).join("+")}`);
125
+ }
126
+ /** A terraform block whose backend is the local file `path`, for the proof plan's override file. Terraform and OpenTofu merge any `*_override.tf` over the root's files. */
127
+ export const localBackendOverride = (path) => `terraform {\n backend "local" {\n path = ${JSON.stringify(path)}\n }\n}\n`;
128
+ /** The override file a proof plan writes into a root, and removes, unless the product names its own. */
129
+ export const DEFAULT_OVERRIDE_FILE = "chant_migrate_override.tf";
130
+ /** What a migration's lock says, unless the product names its own. */
131
+ export const DEFAULT_MIGRATE_LOCK = { operation: "chant migrate", info: "a state migration is writing this state" };
132
+ /** A root's version id now, when its store keeps versions. `pin` lets an azurerm blob with snapshots only take one to name it. */
133
+ async function versionNow(o, fetchFn, pin) {
134
+ const src = stateVersionSource(o, fetchFn, { pin });
135
+ if ("refused" in src)
136
+ return undefined;
137
+ return (await src.current()).versionId;
138
+ }
139
+ /**
140
+ * Plan a migration: read every affected state and its version, build the new
141
+ * states in `work`, and plan each root against its new state. Throws
142
+ * MigrationError for a root that is refused or a move that does not fit.
143
+ */
144
+ export async function planTerraformMigration(input) {
145
+ const exec = input.exec ?? runBinary;
146
+ const log = input.log ?? (() => { });
147
+ const lockOp = input.lock ?? DEFAULT_MIGRATE_LOCK;
148
+ const override = input.overrideFile ?? DEFAULT_OVERRIDE_FILE;
149
+ if (!!input.moves?.length === !!input.restores?.length)
150
+ throw new MigrationError(`migration ${input.name}: give it moves or restores, one of the two`);
151
+ mkdirSync(input.work, { recursive: true });
152
+ const named = [...new Set(input.moves ? input.moves.flatMap((m) => [m.from, m.to]) : input.restores.map((r) => r.root))].sort();
153
+ const byName = new Map(input.roots.map((r) => [r.root, r]));
154
+ const missing = named.filter((n) => !byName.has(n));
155
+ if (missing.length > 0)
156
+ throw new MigrationError(`migration ${input.name}: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not among its roots`);
157
+ const runs = new Map();
158
+ const objects = new Map();
159
+ const versions = new Map();
160
+ const before = new Map();
161
+ for (const [i, name] of named.entries()) {
162
+ const r = byName.get(name);
163
+ let env = r.env ?? process.env;
164
+ if (r.init !== false) {
165
+ env = { ...env, TF_DATA_DIR: join(input.work, `data-${i}`) };
166
+ await initRoot({ ...r, env, exec, reconfigure: true });
167
+ }
168
+ const o = stateObject(r.dir, env, undefined, r.binary);
169
+ if (isRefused(o))
170
+ throw new MigrationError(`migration ${input.name} cannot run: ${name}: ${o.reason}`);
171
+ runs.set(name, { ...r, env });
172
+ objects.set(name, o);
173
+ versions.set(name, await versionNow(o, input.fetch, false));
174
+ before.set(name, await pullState(exec, r.binary, name, r.dir, env));
175
+ }
176
+ const after = new Map();
177
+ if (input.moves) {
178
+ for (const [root, s] of moveResources(input.name, input.moves, before))
179
+ after.set(root, s);
180
+ }
181
+ else {
182
+ for (const r of input.restores) {
183
+ const o = objects.get(r.root);
184
+ const location = stateLocation(o);
185
+ if (location !== r.location)
186
+ throw new MigrationError(`migration ${input.name}: ${r.root}'s state is at ${location}, and the revert restores ${r.location}`);
187
+ const v = versions.get(r.root);
188
+ if ((r.from_version_id ?? undefined) !== v)
189
+ throw new MigrationError(`migration ${input.name}: ${r.root}'s state is at version ${v ?? "none"}, and the migration it reverts left ${r.from_version_id ?? "none"}; it moved since, so putting the older version back would undo that change too`);
190
+ const now = before.get(r.root) ?? null;
191
+ const lineage = now?.lineage || derivedLineage(input.name, r.root);
192
+ const serial = (now?.serial ?? 0) + 1;
193
+ if (r.version_id === null) {
194
+ after.set(r.root, emptyState(lineage, serial, now?.terraform_version));
195
+ continue;
196
+ }
197
+ const src = stateVersionSource(o, input.fetch);
198
+ if ("refused" in src)
199
+ throw new MigrationError(`migration ${input.name}: ${r.root}: ${src.refused}`);
200
+ const text = await src.readVersion(r.version_id);
201
+ if (text === undefined)
202
+ throw new MigrationError(`migration ${input.name}: ${r.location} has no version ${r.version_id}; a lifecycle rule may have expired it`);
203
+ const old = JSON.parse(typeof text === "string" ? text : Buffer.from(text).toString("utf-8"));
204
+ after.set(r.root, { ...old, resources: Array.isArray(old.resources) ? old.resources : [], lineage, serial });
205
+ }
206
+ }
207
+ const planned = new Map();
208
+ const roots = [];
209
+ for (const [i, name] of named.entries()) {
210
+ const state = after.get(name);
211
+ if (!state)
212
+ continue;
213
+ const run = runs.get(name);
214
+ const file = join(input.work, `${i}.tfstate`);
215
+ writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
216
+ planned.set(name, { run, object: objects.get(name), file, gained: state.resources.length - (before.get(name)?.resources.length ?? 0) });
217
+ const proof = await proofPlan(run, exec, file, join(input.work, `proof-${i}`), override);
218
+ log(`${name}: ${proof.changes.length === 0 ? "no changes against its new state" : `${proof.changes.length} change${proof.changes.length === 1 ? "" : "s"} against its new state: ${proof.changes.join(", ")}`}`);
219
+ const was = before.get(name) ?? null;
220
+ const v = versions.get(name);
221
+ const location = stateLocation(objects.get(name));
222
+ roots.push({ root: name, ...(location ? { location } : {}), before: { ...(v ? { version_id: v } : {}), digest: was ? stateDigest(was) : null }, after: { digest: stateDigest(state) }, proof });
223
+ }
224
+ return { roots, engine: migrationEngine(planned, input, exec, lockOp) };
225
+ }
226
+ /**
227
+ * Plan a root against a state file: an override file switches its backend to
228
+ * that local file, in a data dir of its own, so the root's `.terraform` and
229
+ * its real state are never touched. The override file is removed whatever
230
+ * happens.
231
+ */
232
+ async function proofPlan(run, exec, file, data, override) {
233
+ const at = join(run.dir, override);
234
+ const env = { ...run.env, TF_DATA_DIR: data };
235
+ writeFileSync(at, localBackendOverride(resolve(file)));
236
+ try {
237
+ await initRoot({ ...run, env, exec, reconfigure: true });
238
+ const read = await planStateCheck({ ...run, env, exec, planFile: `${data}.tfplan` });
239
+ return { changes: resourceChanges(read.json), summary: read.summary };
240
+ }
241
+ finally {
242
+ rmSync(at, { force: true });
243
+ }
244
+ }
245
+ function migrationEngine(planned, input, exec, lockOp) {
246
+ const log = input.log ?? (() => { });
247
+ const stores = new Map();
248
+ for (const [root, p] of planned)
249
+ if (isStored(p.object))
250
+ stores.set(root, stateStore(p.object, p.run.dir, input.fetch));
251
+ const pinned = new Map();
252
+ return {
253
+ async lock() {
254
+ const got = await takeLocksWithSources({ sources: [], stores: [...stores].map(([root, store]) => ({ root, store })), now: new Date().toISOString(), op: lockOp, who: input.who ?? `chant@${hostname()}` });
255
+ return async () => {
256
+ for (const l of got.locks.reverse())
257
+ await l.release().catch((e) => log(`${l.root}: the lock could not be released: ${e.message}`));
258
+ };
259
+ },
260
+ async current(root) {
261
+ const p = planned.get(root);
262
+ const v = await versionNow(p.object, input.fetch, false);
263
+ const s = await pullState(exec, p.run.binary, root, p.run.dir, p.run.env);
264
+ return { ...(v ? { version_id: v } : {}), digest: s ? stateDigest(s) : null };
265
+ },
266
+ async write() {
267
+ // An azurerm state named by no version gets a snapshot first, so the record names what it was.
268
+ for (const [root, p] of planned) {
269
+ if (p.object.backend !== "azurerm")
270
+ continue;
271
+ if (await versionNow(p.object, input.fetch, false))
272
+ continue;
273
+ const v = await versionNow(p.object, input.fetch, true);
274
+ if (v)
275
+ pinned.set(root, v);
276
+ }
277
+ const order = [...planned].sort(([a, pa], [b, pb]) => pb.gained - pa.gained || (a < b ? -1 : 1));
278
+ for (const [root, p] of order) {
279
+ const store = stores.get(root);
280
+ // A state whose lock keeps the binary out (azurerm's lease) is written under it; the binary writes the others with the lock held for it.
281
+ if (store?.write)
282
+ await store.write(readFileSync(p.file, "utf-8"));
283
+ else
284
+ await pushStateFile({ ...p.run, exec, file: p.file, ...(store ? { lock: false } : {}) });
285
+ log(`${root}: wrote its new state`);
286
+ }
287
+ },
288
+ async verify(root) {
289
+ const p = planned.get(root);
290
+ const read = await planStateCheck({ ...p.run, exec, planFile: join(input.work, `verify-${root.replace(/[^\w.-]/g, "_")}.tfplan`), ...(stores.has(root) ? { lock: false } : {}) });
291
+ const v = await versionNow(p.object, input.fetch, true);
292
+ const was = pinned.get(root);
293
+ return { changes: resourceChanges(read.json), summary: read.summary, ...(v ? { version_id: v } : {}), ...(was ? { before_version_id: was } : {}) };
294
+ },
295
+ };
296
+ }