@intentius/chant-lexicon-pulumi 0.124.85 → 0.124.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stack-ops.js CHANGED
@@ -1,9 +1,18 @@
1
1
  /**
2
2
  * Gated stack operations (#4578): a stack's export, a stuck lock's release,
3
- * and a move of resources between stacks, each run only after a gated
4
- * request (#4551) is approved on the workspace ledger. INTENTIUS/plywood#16
5
- * puts its `export`, `cancel` and `move` verbs on these; plywood holds the
6
- * words only.
3
+ * a move of resources between stacks and a day-2 action, each run only
4
+ * after a gated request (#4551) is approved on the workspace ledger.
5
+ * INTENTIUS/plywood#16 puts its `export`, `cancel`, `move` and `action`
6
+ * verbs on these; plywood holds the words only.
7
+ *
8
+ * Since #4808 each one runs on chant core's walk rather than one of its
9
+ * own: the export is core's `exportStateVersion` over a Pulumi
10
+ * {@link pulumiStackVersionSource}, the cancel is core's `releaseStateLock`
11
+ * over a Pulumi lock source, the move is core's `runStateMigration` over a
12
+ * Pulumi migration engine, and the action is core's `gatedOp`. So each one
13
+ * gets what core's adapters check: the export of one version, the live-run
14
+ * check before a cancel, and the check that nothing moved between a move's
15
+ * plan and its write.
7
16
  *
8
17
  * ## The request
9
18
  *
@@ -13,40 +22,51 @@
13
22
  *
14
23
  * | Operation | kind | subject (the gate) | fields |
15
24
  * |---|---|---|---|
16
- * | export | `stack-export` | `<stack>` | `stack`, `engine`, `deliver: requester` |
17
- * | cancel | `stack-cancel` | `<stack>` | `stack`, `lockId` |
18
- * | move | `stack-move` | `move:<source>:<dest>` | `source`, `dest`, `engine`, `urns` (sorted, comma-joined) |
25
+ * | export | `stack-export` | `<stack>` | `location`, `version_id` |
26
+ * | cancel | `stack-cancel` | `<stack>` | `location`, `id` (the lock id) |
27
+ * | move | `stack-move` | `move:<source>:<dest>` | `source`, `dest`, `engine`, `urns` (sorted, comma-joined), `roots`, `proof` (the plan's digest) |
19
28
  * | action | `stack-action` | `action:<stack>:<name>` (the URN without a name) | `stack`, `urn`, `engine`, `preview` (the preview's digest), `name` when given |
20
29
  *
21
30
  * The first call records the pending fact and answers `waiting` with the
22
31
  * `chant approve` command. A later call with the same request reuses the
23
32
  * standing request's `at`, so it digests the same and finds the approval.
24
33
  * The requester's own approval never counts (`refused`). Once approved, the
25
- * request is spent (`spendGatedRequest`, pushed before anything runs), the
26
- * operation runs, and a `finished` line records how it ended with flat
27
- * facts: never the export's content, only its digest and size.
34
+ * request is spent (pushed before anything runs), the operation runs, and a
35
+ * `finished` line records how it ended with flat facts: never a state's
36
+ * content, only digests, ids and counts.
28
37
  *
29
38
  * ## What runs
30
39
  *
31
- * - export: `pulumi stack export --stack <s>` (`plunge stack export` on
32
- * plunge), the read form #4546 allows. The output goes to the requester's
33
- * machine only: a file outside every git working tree, mode 600, never
34
- * overwritten, and the call is refused in CI (`CI`, `GITHUB_ACTIONS`,
35
- * `GITLAB_CI`, `FORGEJO_ACTIONS`), where it would become a job artifact.
36
- * - cancel: `pulumi cancel --yes --stack <s>`, after checking the stack's
37
- * lock is still the one approved when the backend is a `file://` path
38
- * (`.pulumi/locks/...`); another backend's lock is read by the caller's
39
- * `readLockId`, or the check is reported as not made. A stack on plunge is
40
- * refused: plunge keeps no stack lock.
41
- * - move: both stacks preview first, and the move runs only when the
42
- * previews change nothing but the moved resources (each a delete in the
43
- * source and a create of the same type and name in the destination), so
44
- * the move leaves both previewing no change. On plunge, `plunge stack move
45
- * ... --json` plans it as well and its refusals refuse the request. Then
46
- * `pulumi state move --source --dest --yes <urn>...` on stock, or `plunge
47
- * stack move ... --json --yes` (INTENTIUS/plunge#56). Both stacks preview
48
- * again afterwards; a change left on either finishes the request `failed`
49
- * with the changes named.
40
+ * - export: the version asked for, else the one the stack holds now. On a
41
+ * backend that numbers its updates (Pulumi Cloud) the version is the
42
+ * update's number from `stack history`, and the approved call runs
43
+ * `pulumi stack export --stack <s> --version <n>`. A file backend, a
44
+ * bucket and plunge number none, so there the version is the `sha256:`
45
+ * digest of the stack's export now, and the approved call writes the
46
+ * export only while its digest is still that one; a stack updated after
47
+ * the approval asks again. The output goes to the requester's machine
48
+ * only: a file outside every git working tree, mode 600, never
49
+ * overwritten, and the call is refused in CI.
50
+ * - cancel: the lock is read first (a `file://` backend's lock file under
51
+ * `.pulumi/locks/...`, or the caller's `readLockId`); an approved lock
52
+ * that is not the one held is refused before anything is asked. While a
53
+ * run of the repository that began before the lock was taken is alive,
54
+ * nothing is asked ({@link PulumiStackOpRefused} `live-run`), and the runs
55
+ * are read again just before the spend (`held`). Then `pulumi cancel
56
+ * --yes --stack <s>`, and the lock is read again to check it went. A stack
57
+ * on plunge is refused: plunge keeps no stack lock.
58
+ * - move: both stacks preview first, and the move is asked for only when
59
+ * the previews change nothing but the moved resources (each a delete in
60
+ * the source and a create of the same type and name in the destination).
61
+ * On plunge, `plunge stack move ... --json` plans it as well and its
62
+ * refusals refuse the request. The request binds each stack's export
63
+ * digest, so a stack updated before the approval asks again. Approved,
64
+ * each stack's export is read again just before the write, and one that
65
+ * is not the planned one refuses the move with nothing moved (`failed`,
66
+ * `check: "moved"`). Then `pulumi state move --source --dest --yes
67
+ * <urn>...` on stock, or `plunge stack move ... --json --yes`
68
+ * (INTENTIUS/plunge#56), and both stacks preview again; a change left on
69
+ * either finishes the request `failed` with the changes named.
50
70
  *
51
71
  * - action (#4654): a day-2 action is a `command:` resource
52
72
  * (`command:local:Command`, `command:remote:Command`) whose replacement is
@@ -61,76 +81,51 @@
61
81
  * lines. A request that applied answers `spent` to the same call, unless
62
82
  * the caller asks `anew`.
63
83
  *
64
- * The writes go through `runGatedPulumi` and `runGatedPlunge`
65
- * (`./run.ts`), whose fixed forms are the whole of what may run.
84
+ * The writes go through `runGatedPulumi` and `runGatedPlunge`, and the
85
+ * version reads through `runStackOpReadPulumi` (`./run.ts`), whose fixed
86
+ * forms are the whole of what may run.
66
87
  */
67
88
  import { createHash } from "node:crypto";
68
- import { existsSync, readdirSync, writeFileSync } from "node:fs";
69
- import { dirname, isAbsolute, join, resolve } from "node:path";
89
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
90
+ import { isAbsolute, join, resolve } from "node:path";
91
+ import { chantGatedLedger, gatedOp } from "@intentius/chant/lifecycle/gated-op";
92
+ import { exportStateVersion, StateExportError } from "@intentius/chant/state-export";
93
+ import { runStateMigration } from "@intentius/chant/state-migration";
94
+ import { describeRun, forgeLiveRuns, releaseStateLock } from "@intentius/chant/state-unlock";
70
95
  import { parsePulumiUrn, pulumiNodeKey } from "@intentius/chant/pulumi-urn";
71
96
  import { pulumiStackBackend } from "./adopt.js";
72
97
  import { pulumiExportResources, pulumiPreviewDigest, pulumiSteps, PULUMI_UNCHANGED_OPS } from "./change-set.js";
73
98
  import { pulumiMemberEngine } from "./member-engine.js";
74
- import { defaultPlungeRunner, defaultPulumiRunner, plungeMoveArgs, previewPulumiMemberRead, pulumiActionPreviewArgs, pulumiActionUpArgs, pulumiCancelArgs, pulumiRunFailure, pulumiStateMoveArgs, runAllowedPlunge, runAllowedPulumi, runGatedPlunge, runGatedPulumi, } from "./run.js";
99
+ import { defaultPlungeRunner, defaultPulumiRunner, plungeMoveArgs, previewPulumiMemberRead, pulumiActionPreviewArgs, pulumiActionUpArgs, pulumiCancelArgs, pulumiRunFailure, pulumiStackExportVersionArgs, pulumiStackHistoryArgs, pulumiStateMoveArgs, runAllowedPlunge, runAllowedPulumi, runGatedPlunge, runGatedPulumi, runStackOpReadPulumi, } from "./run.js";
75
100
  import { isObject } from "./values.js";
76
101
  /** The op the requests are recorded under, unless the caller names its own. */
77
102
  export const PULUMI_STACK_OPS_OP = "pulumi-stack-ops";
78
- async function gatedApi(given) {
79
- if (given)
80
- return given;
81
- try {
82
- const mod = (await import("@intentius/chant/lifecycle/gated-request"));
83
- if (mod.requestGate && mod.spendGatedRequest && mod.finishGatedRequest && mod.readGatedRequests)
84
- return mod;
85
- }
86
- catch {
87
- // Fall through to the refusal.
103
+ /** An operation core's checks refused before it acted: `code` says which, `runs` names the live runs. */
104
+ export class PulumiStackOpRefused extends Error {
105
+ constructor(code, message, extra = {}) {
106
+ super(`${code}: ${message}`);
107
+ this.name = "PulumiStackOpRefused";
108
+ this.code = code;
109
+ this.runs = extra.runs ?? [];
110
+ if (extra.digest)
111
+ this.digest = extra.digest;
88
112
  }
89
- throw new Error("this chant has no gated requests (#4551), so a gated stack operation cannot be asked for; upgrade @intentius/chant");
90
113
  }
91
- const sameFields = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => b[k] === v);
92
- /**
93
- * Ask for the request, and run `act` once it is approved: the shared walk of
94
- * every operation. `precheck` runs after the approval and before the request
95
- * is spent, so a refusal there leaves the approval unspent.
96
- */
97
- async function askThenAct(common, kind, subject, fields, description, act, precheck, options = {}) {
98
- const api = await gatedApi(common.gated);
99
- const op = common.op ?? PULUMI_STACK_OPS_OP;
100
- const cwd = common.ledgerCwd ?? process.cwd();
101
- // With reuseApplied (#4654), a request with these fields that applied already is asked again as itself, so it answers `spent`.
102
- const standing = (await api.readGatedRequests(op, { cwd }).catch(() => []))
103
- .filter((r) => (options.reuseApplied || !r.applied) && r.request.kind === kind && r.request.subject === subject && r.request.by === common.by && sameFields(r.request.fields, fields))
104
- .at(-1);
105
- const request = { kind, subject, by: common.by, at: standing?.request.at ?? common.now ?? new Date().toISOString(), fields };
106
- const asked = await api.requestGate({
107
- op,
108
- request,
114
+ /** The gated-request settings core's walks take, from the common options. */
115
+ function gatedSettings(common) {
116
+ return {
109
117
  rules: common.rules,
110
- description,
111
- cwd,
118
+ ...(common.ledgerCwd ? { cwd: common.ledgerCwd } : {}),
112
119
  ...(common.expiry ? { expiry: common.expiry } : {}),
120
+ ...(common.base ? { base: common.base } : {}),
113
121
  ...(common.now ? { now: common.now } : {}),
114
- });
115
- if (asked.status === "waiting")
116
- return { status: "waiting", digest: asked.digest, request: asked.request, command: asked.command };
117
- if (asked.status === "refused")
118
- return { status: "refused", digest: asked.digest, request: asked.request, by: asked.by, reason: asked.reason, command: asked.command };
119
- if (asked.status === "spent")
120
- return { status: "spent", digest: asked.digest, request: asked.request };
121
- if (precheck)
122
- await precheck();
123
- const applied = await api.spendGatedRequest({ op, gate: subject, digest: asked.digest, approval: asked.approval, cwd, ...(common.now ? { now: common.now } : {}) });
124
- try {
125
- const { result, detail, failed } = await act();
126
- await api.finishGatedRequest({ op, gate: subject, digest: asked.digest, applied: applied.timestamp, result: failed ? "failed" : "applied", detail: failed ? { ...detail, error: failed } : detail, cwd });
127
- return failed ? { status: "failed", digest: asked.digest, request: asked.request, error: failed } : { status: "done", digest: asked.digest, request: asked.request, result };
128
- }
129
- catch (err) {
130
- const error = err instanceof Error ? err.message : String(err);
131
- await api.finishGatedRequest({ op, gate: subject, digest: asked.digest, applied: applied.timestamp, result: "failed", detail: { error: error.slice(0, 2000) }, cwd }).catch(() => undefined);
132
- return { status: "failed", digest: asked.digest, request: asked.request, error };
133
- }
122
+ ...(common.gated ? { ledger: common.gated } : {}),
123
+ };
124
+ }
125
+ /** The request core asked under `digest`, read back from the ledger, since core's outcomes name only its digest; `fallback` when the ledger has none. */
126
+ async function askedRequest(common, digest, fallback) {
127
+ const read = digest ? await (common.gated ?? chantGatedLedger).readGatedRequests(common.op ?? PULUMI_STACK_OPS_OP, common.ledgerCwd ? { cwd: common.ledgerCwd } : undefined).catch(() => []) : [];
128
+ return read.find((g) => g.digest === digest)?.request ?? { ...fallback, at: "" };
134
129
  }
135
130
  function stackDirOf(dir, cwd) {
136
131
  return isAbsolute(dir) ? dir : resolve(cwd ?? process.cwd(), dir);
@@ -142,71 +137,165 @@ function why(err, binary) {
142
137
  const f = pulumiRunFailure(err);
143
138
  return f.missingBinary ? `the ${binary} binary was not found on PATH` : (f.stderr?.trim() || f.message).split("\n").slice(-3).join("\n");
144
139
  }
145
- // ── export ───────────────────────────────────────────────────────────────
146
- /** The CI variables that mark a job, where an export would become an artifact. */
147
- export const CI_MARKERS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "FORGEJO_ACTIONS", "BUILDKITE", "JENKINS_URL"];
148
- /** The git working tree `path` sits in, or undefined. */
149
- export function enclosingWorkTree(path) {
150
- let dir = resolve(path);
151
- for (;;) {
152
- if (existsSync(join(dir, ".git")))
153
- return dir;
154
- const up = dirname(dir);
155
- if (up === dir)
156
- return undefined;
157
- dir = up;
140
+ const sha256 = (text) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
141
+ /** Where a stack's state is, as messages and the record name it: the stack and its backend's URL, never a credential. */
142
+ function stackLocation(dir, stack, env) {
143
+ const backend = pulumiStackBackend(dir, { env });
144
+ return `stack ${stack}${backend ? ` at ${backend.url}` : ""}`;
145
+ }
146
+ /** The stack's export now, under its engine's read form. */
147
+ async function exportNow(opts) {
148
+ const args = ["stack", "export", "--stack", opts.stack];
149
+ try {
150
+ const { stdout } = opts.engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, opts.dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir);
151
+ return stdout;
152
+ }
153
+ catch (err) {
154
+ throw new Error(`${opts.engine} ${args.join(" ")} failed: ${why(err, opts.engine)}`);
158
155
  }
159
156
  }
157
+ // ── export ───────────────────────────────────────────────────────────────
158
+ /** The CI variables that mark a job, where an export would become an artifact. Core's list (`@intentius/chant/state-export`). */
159
+ export { CI_MARKERS, enclosingWorkTree } from "@intentius/chant/state-export";
160
+ /** A version id that is an update's number, as `stack history` and `stack export --version` take it. */
161
+ const UPDATE_NUMBER = /^[1-9][0-9]*$/;
160
162
  /**
161
- * A stack's export, delivered to the requester's machine after a second
162
- * identity approves it. Refused in CI and for a destination inside a git
163
- * working tree, before anything is asked.
163
+ * A stack's state read by version (#4808), core's `StateVersionSource` for
164
+ * `exportStateVersion`. On a backend that numbers its updates the version
165
+ * is the newest update's number (`stack history --json --page-size 1`), a
166
+ * version is held when it is between 1 and that number, and one is read
167
+ * with `stack export --version <n>`. A backend that numbers none (a file
168
+ * backend answers `0`, plunge keeps no history chant reads) has one version,
169
+ * the one it holds now, named by its export's `sha256:` digest; reading it
170
+ * exports again and refuses an export whose digest moved. `read` keeps the
171
+ * last export's size and resource count for the caller.
164
172
  */
165
- export async function gatedStackExport(opts) {
166
- const env = opts.env ?? process.env;
167
- const marker = CI_MARKERS.find((k) => env[k] !== undefined && env[k] !== "" && env[k] !== "false");
168
- if (marker)
169
- throw new Error(`a stack export goes to the requester's machine only, and ${marker} is set, so this is a CI job whose files can become artifacts; ask for it from your own machine`);
170
- const out = resolve(opts.out);
171
- const tree = enclosingWorkTree(dirname(out));
172
- if (tree)
173
- throw new Error(`a stack export never goes into a repository, and ${out} is inside the git working tree ${tree}; name a path outside it`);
174
- if (existsSync(out))
175
- throw new Error(`${out} already exists; a stack export never overwrites a file`);
176
- const dir = stackDirOf(opts.dir, opts.cwd);
177
- const engine = engineOf(dir, opts.engine, env);
178
- return askThenAct(opts, "stack-export", opts.stack, { stack: opts.stack, engine, deliver: "requester" }, `export of stack ${opts.stack} to ${opts.by}'s machine`, async () => {
179
- const args = ["stack", "export", "--stack", opts.stack];
173
+ export function pulumiStackVersionSource(opts) {
174
+ const location = stackLocation(opts.dir, opts.stack, opts.env ?? process.env);
175
+ const newest = async () => {
176
+ if (opts.engine === "plunge")
177
+ return undefined;
180
178
  let stdout;
181
179
  try {
182
- ({ stdout } = engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, args, dir));
180
+ ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, pulumiStackHistoryArgs(opts.stack), opts.dir));
183
181
  }
184
- catch (err) {
185
- throw new Error(`${engine} ${args.join(" ")} failed: ${why(err, engine)}`);
182
+ catch {
183
+ // A history that cannot be read numbers nothing; the export by digest still stands.
184
+ return undefined;
185
+ }
186
+ try {
187
+ const doc = JSON.parse(stdout);
188
+ const first = Array.isArray(doc) ? doc[0] : undefined;
189
+ const v = isObject(first) && typeof first.version === "number" ? first.version : 0;
190
+ return v > 0 ? v : undefined;
191
+ }
192
+ catch {
193
+ return undefined;
186
194
  }
187
- let resources = 0;
195
+ };
196
+ const checked = (body, what) => {
197
+ let resources;
188
198
  try {
189
- resources = pulumiExportResources(JSON.parse(stdout)).length;
199
+ resources = pulumiExportResources(JSON.parse(body)).length;
190
200
  }
191
201
  catch {
192
- throw new Error(`${engine} ${args.join(" ")} printed no JSON`);
202
+ throw new StateExportError(`${what} printed no JSON`);
193
203
  }
194
- writeFileSync(out, stdout, { mode: 0o600, flag: "wx" });
195
- const sha256 = createHash("sha256").update(stdout).digest("hex");
196
- const bytes = Buffer.byteLength(stdout);
197
- return { result: { file: out, sha256, bytes, resources }, detail: { sha256, bytes, resources } };
204
+ source.read = { bytes: Buffer.byteLength(body), resources };
205
+ return body;
206
+ };
207
+ const source = {
208
+ location,
209
+ async current() {
210
+ const n = await newest();
211
+ if (n !== undefined)
212
+ return { exists: true, versionId: String(n) };
213
+ return { exists: true, versionId: sha256(await exportNow(opts)) };
214
+ },
215
+ async hasVersion(id) {
216
+ if (UPDATE_NUMBER.test(id)) {
217
+ const n = await newest();
218
+ return n !== undefined && Number(id) <= n;
219
+ }
220
+ return id.startsWith("sha256:") && (await newest()) === undefined && sha256(await exportNow(opts)) === id;
221
+ },
222
+ async readVersion(id) {
223
+ if (UPDATE_NUMBER.test(id)) {
224
+ const args = pulumiStackExportVersionArgs(opts.stack, id);
225
+ let stdout;
226
+ try {
227
+ ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir));
228
+ }
229
+ catch (err) {
230
+ throw new StateExportError(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
231
+ }
232
+ return checked(stdout, `pulumi ${args.join(" ")}`);
233
+ }
234
+ const body = await exportNow(opts);
235
+ if (sha256(body) !== id)
236
+ throw new StateExportError(`${location} changed since the request: its export is no longer ${id}, so nothing was written; ask again for the state it holds now`);
237
+ return checked(body, `${opts.engine} stack export --stack ${opts.stack}`);
238
+ },
239
+ };
240
+ return source;
241
+ }
242
+ /**
243
+ * A stack's export, one version of it, delivered to the requester's machine
244
+ * after a second identity approves it: core's `exportStateVersion` over
245
+ * {@link pulumiStackVersionSource}. Refused in CI, for a destination inside
246
+ * a git working tree or over a file, and for a version the stack does not
247
+ * have, before anything is asked.
248
+ */
249
+ export async function gatedStackExport(opts) {
250
+ const env = opts.env ?? process.env;
251
+ const dir = stackDirOf(opts.dir, opts.cwd);
252
+ const engine = engineOf(dir, opts.engine, env);
253
+ const source = pulumiStackVersionSource({ dir, stack: opts.stack, engine, env, ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}) });
254
+ const out = resolve(opts.out);
255
+ const r = await exportStateVersion({
256
+ subject: opts.stack,
257
+ by: opts.by,
258
+ source,
259
+ out,
260
+ ...(opts.version ? { version: opts.version } : {}),
261
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-export" },
262
+ env,
263
+ ...gatedSettings(opts),
198
264
  });
265
+ const request = await askedRequest(opts, r.digest, { kind: "stack-export", subject: opts.stack, by: opts.by, fields: { location: r.location, version_id: r.version } });
266
+ switch (r.status) {
267
+ case "waiting":
268
+ return { status: "waiting", digest: r.digest, request, command: r.command };
269
+ case "refused":
270
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
271
+ case "spent":
272
+ return { status: "spent", digest: r.digest, request };
273
+ case "failed":
274
+ return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
275
+ case "written":
276
+ return {
277
+ status: "done",
278
+ digest: r.digest,
279
+ request,
280
+ approvedBy: r.approvedBy,
281
+ recorded: r.recorded,
282
+ result: { file: r.file, sha256: r.contentDigest.replace(/^sha256:/, ""), bytes: source.read?.bytes ?? 0, resources: source.read?.resources ?? 0, version: r.version },
283
+ };
284
+ }
199
285
  }
200
286
  // ── cancel ───────────────────────────────────────────────────────────────
287
+ /** The two lock directories of a DIY backend at `root` for a stack: project-scoped first, then the older layout. */
288
+ function diyLockDirs(root, project, stack) {
289
+ return [...(project ? [join(root, ".pulumi", "locks", "organization", project, stack)] : []), join(root, ".pulumi", "locks", stack)];
290
+ }
201
291
  /**
202
292
  * The lock ids a DIY backend at `root` holds for a stack: the file names
203
293
  * under `.pulumi/locks/organization/<project>/<stack>/` (project-scoped
204
294
  * stacks) and `.pulumi/locks/<stack>/` (the older layout), without `.json`.
205
295
  */
206
296
  export function diyStackLockIds(root, project, stack) {
207
- const dirs = [...(project ? [join(root, ".pulumi", "locks", "organization", project, stack)] : []), join(root, ".pulumi", "locks", stack)];
208
297
  const ids = new Set();
209
- for (const d of dirs) {
298
+ for (const d of diyLockDirs(root, project, stack)) {
210
299
  if (!existsSync(d))
211
300
  continue;
212
301
  for (const f of readdirSync(d))
@@ -215,6 +304,44 @@ export function diyStackLockIds(root, project, stack) {
215
304
  }
216
305
  return [...ids].sort();
217
306
  }
307
+ /**
308
+ * One DIY lock as core's `LockInfo` (#4808): its id, and from the lock
309
+ * file Pulumi writes (`pid`, `username`, `hostname`, `timestamp`) who took
310
+ * it and when, so the live-run check knows which runs could hold it.
311
+ * Undefined when the stack holds no lock of that id.
312
+ */
313
+ export function diyStackLock(root, project, stack, id) {
314
+ for (const d of diyLockDirs(root, project, stack)) {
315
+ const file = join(d, `${id}.json`);
316
+ if (!existsSync(file))
317
+ continue;
318
+ let doc;
319
+ try {
320
+ doc = JSON.parse(readFileSync(file, "utf-8"));
321
+ }
322
+ catch {
323
+ doc = undefined;
324
+ }
325
+ const s = (k) => (isObject(doc) && typeof doc[k] === "string" && doc[k] !== "" ? doc[k] : undefined);
326
+ const who = s("username") && s("hostname") ? `${s("username")}@${s("hostname")}` : s("username");
327
+ return { ID: id, ...(who ? { Who: who } : {}), ...(s("timestamp") ? { Created: s("timestamp") } : {}) };
328
+ }
329
+ return undefined;
330
+ }
331
+ /** The DIY root and project of a stack on a `file://` backend, or undefined for any other backend. */
332
+ async function diyRootOf(dir, env, project) {
333
+ const backend = pulumiStackBackend(dir, { env });
334
+ const m = backend ? /^file:\/\/(.*)$/.exec(backend.url) : null;
335
+ if (!m)
336
+ return backend ? { backend: backend.url } : {};
337
+ const root = isAbsolute(m[1]) ? m[1] : resolve(dir, m[1]);
338
+ let name = project;
339
+ if (!name) {
340
+ const { pulumiYamlName } = await import("./lint/post-synth/member-read-helpers.js");
341
+ name = pulumiYamlName(dir);
342
+ }
343
+ return { root, backend: backend.url, ...(name ? { project: name } : {}) };
344
+ }
218
345
  /**
219
346
  * The lock ids a stack holds now (#4615), for a caller that needs the id
220
347
  * `gatedStackCancel` asks for: the stack's backend from its directory (the
@@ -228,19 +355,26 @@ export async function pulumiStackLockIds(opts) {
228
355
  const dir = stackDirOf(opts.dir, opts.cwd);
229
356
  if (engineOf(dir, opts.engine, env) === "plunge")
230
357
  return { checked: true, ids: [] };
231
- const backend = pulumiStackBackend(dir, { env });
232
- const m = backend ? /^file:\/\/(.*)$/.exec(backend.url) : null;
233
- if (!m)
234
- return { checked: false, ...(backend ? { backend: backend.url } : {}), ids: [] };
235
- const root = isAbsolute(m[1]) ? m[1] : resolve(dir, m[1]);
236
- let project = opts.project;
237
- if (!project) {
238
- const { pulumiYamlName } = await import("./lint/post-synth/member-read-helpers.js");
239
- project = pulumiYamlName(dir);
240
- }
241
- return { checked: true, backend: backend.url, ids: diyStackLockIds(root, project, opts.stack) };
358
+ const at = await diyRootOf(dir, env, opts.project);
359
+ if (!at.root)
360
+ return { checked: false, ...(at.backend ? { backend: at.backend } : {}), ids: [] };
361
+ return { checked: true, ...(at.backend ? { backend: at.backend } : {}), ids: diyStackLockIds(at.root, at.project, opts.stack) };
242
362
  }
243
- /** Release a stuck lock after an approval of its lock id. Refused for plunge, which keeps no stack lock. */
363
+ /** The runs of the forge `forge` names over `env`, as core reads them (#4808). */
364
+ function forgeRuns(env, forge) {
365
+ return async () => {
366
+ const { forgeTargetWith } = await import("@intentius/chant/forge-flags");
367
+ const t = forgeTargetWith(env, forge ?? {});
368
+ return forgeLiveRuns({ kind: t.kind, apiBase: t.apiBase, repo: t.repo, token: t.token, ...(t.tokenHeader ? { tokenHeader: t.tokenHeader } : {}) });
369
+ };
370
+ }
371
+ /**
372
+ * Release a stuck lock after an approval of its lock id, while no run that
373
+ * may hold it is alive: core's `releaseStateLock` over the stack's lock.
374
+ * Refused for plunge, which keeps no stack lock. On a backend chant cannot
375
+ * list and with no `readLockId`, the lock is the one the caller names and
376
+ * `lockChecked` is false.
377
+ */
244
378
  export async function gatedStackCancel(opts) {
245
379
  const env = opts.env ?? process.env;
246
380
  const dir = stackDirOf(opts.dir, opts.cwd);
@@ -249,31 +383,72 @@ export async function gatedStackCancel(opts) {
249
383
  throw new Error(`stack ${opts.stack} runs on plunge, which keeps no stack lock, so there is nothing to cancel; a stuck plunge update is finished by running it again`);
250
384
  if (!opts.lockId || opts.lockId.startsWith("-"))
251
385
  throw new Error("a cancel names the lock id it releases");
252
- const readLock = async () => {
386
+ const at = opts.readLockId ? {} : await diyRootOf(dir, env, opts.project);
387
+ const checked = opts.readLockId !== undefined || at.root !== undefined;
388
+ const heldIds = async () => {
253
389
  if (opts.readLockId) {
254
390
  const id = await opts.readLockId();
255
- return { checked: true, ids: id ? [id] : [] };
391
+ return id ? [id] : [];
256
392
  }
257
- const locks = await pulumiStackLockIds({ dir, stack: opts.stack, engine, env, ...(opts.project ? { project: opts.project } : {}) });
258
- return { checked: locks.checked, ids: locks.ids };
393
+ return at.root ? diyStackLockIds(at.root, at.project, opts.stack) : [];
259
394
  };
260
- let checked = false;
261
- return askThenAct(opts, "stack-cancel", opts.stack, { stack: opts.stack, lockId: opts.lockId }, `release of lock ${opts.lockId} on stack ${opts.stack}`, async () => {
262
- const args = pulumiCancelArgs({ stack: opts.stack });
263
- try {
264
- await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
265
- }
266
- catch (err) {
267
- throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
268
- }
269
- return { result: { lockChecked: checked }, detail: { lockId: opts.lockId, lockChecked: checked } };
270
- }, async () => {
271
- const lock = await readLock();
272
- checked = lock.checked;
273
- if (lock.checked && !lock.ids.includes(opts.lockId)) {
274
- throw new Error(`refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is ${lock.ids.length === 0 ? "gone, and the stack holds no lock" : `not the one it holds now (${lock.ids.join(", ")})`}; ask again for the lock it holds`);
395
+ if (checked) {
396
+ const ids = await heldIds();
397
+ if (!ids.includes(opts.lockId)) {
398
+ throw new PulumiStackOpRefused("lock-gone", `refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is ${ids.length === 0 ? "gone, and the stack holds no lock" : `not the one it holds now (${ids.join(", ")})`}; ask again for the lock it holds`);
275
399
  }
400
+ }
401
+ const location = at.root ? `${at.backend} lock of stack ${opts.stack}` : stackLocation(dir, opts.stack, env);
402
+ let released = false;
403
+ const lock = {
404
+ location,
405
+ async read() {
406
+ // A backend chant cannot list holds the lock the caller names until the release ran.
407
+ if (!checked)
408
+ return released ? undefined : { ID: opts.lockId };
409
+ if (!(await heldIds()).includes(opts.lockId))
410
+ return undefined;
411
+ return (at.root ? diyStackLock(at.root, at.project, opts.stack, opts.lockId) : undefined) ?? { ID: opts.lockId };
412
+ },
413
+ async release() {
414
+ const args = pulumiCancelArgs({ stack: opts.stack });
415
+ try {
416
+ await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
417
+ }
418
+ catch (err) {
419
+ throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
420
+ }
421
+ released = true;
422
+ },
423
+ };
424
+ const r = await releaseStateLock({
425
+ subject: opts.stack,
426
+ by: opts.by,
427
+ lock,
428
+ liveRuns: opts.liveRuns ?? forgeRuns(env, opts.forge),
429
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-cancel" },
430
+ ...(opts.commit ? { commit: opts.commit } : {}),
431
+ ...gatedSettings(opts),
276
432
  });
433
+ const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-cancel", subject: opts.stack, by: opts.by, fields: { location, id: opts.lockId } });
434
+ switch (r.status) {
435
+ case "free":
436
+ throw new PulumiStackOpRefused("lock-gone", `refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is gone; ask again for the lock it holds`);
437
+ case "alive":
438
+ throw new PulumiStackOpRefused("live-run", `a run that began before ${opts.lockId} was taken is alive, so it may hold the lock, and nothing was asked: ${r.alive.map(describeRun).join("; ")}`, { runs: r.alive });
439
+ case "held":
440
+ throw new PulumiStackOpRefused("held", `${r.reason}; the approval stands unspent, so run the cancel again once that run finished`, { digest: r.digest });
441
+ case "waiting":
442
+ return { status: "waiting", digest: r.digest, request, command: r.command };
443
+ case "refused":
444
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
445
+ case "spent":
446
+ return { status: "spent", digest: r.digest, request };
447
+ case "failed":
448
+ return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
449
+ case "released":
450
+ return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { lockChecked: checked, liveRuns: r.liveRuns } };
451
+ }
277
452
  }
278
453
  /** The entries of a preview that change anything. */
279
454
  function changing(part) {
@@ -328,14 +503,25 @@ function moveView(text) {
328
503
  }
329
504
  }
330
505
  /**
331
- * Move resources between two stacks after an approval: `pulumi state move`
332
- * on stock, plunge's marker move on plunge. Refused before anything is asked
333
- * for an empty or non-URN list or two engines.
506
+ * Move resources between two stacks after an approval: core's
507
+ * `runStateMigration` (#4808) with the two stacks as its roots. Each call
508
+ * plans: both previews, plunge's plan on plunge, and each stack's export
509
+ * digest as its state before. The request binds that plan. Approved, the
510
+ * engine reads each export again and refuses a state that moved, runs
511
+ * `pulumi state move` (plunge's marker move on plunge), and previews both
512
+ * stacks again. A Pulumi move's new states are the engine's to write, so
513
+ * each root's `after` digest binds what the move does to it (the stacks and
514
+ * the URNs), not bytes. Pulumi takes each stack's lock inside the move
515
+ * itself; chant takes none, and refuses while a `file://` backend shows
516
+ * either stack locked. Refused before anything is asked for an empty or
517
+ * non-URN list, two engines, or a plan that changes more than the move.
334
518
  */
335
519
  export async function gatedStackMove(opts) {
336
520
  const env = opts.env ?? process.env;
337
521
  if (opts.urns.length === 0 || !opts.urns.every((u) => u.startsWith("urn:pulumi:")))
338
522
  throw new Error("a move names the source URNs it moves, each urn:pulumi:...");
523
+ if (opts.source.member === opts.dest.member)
524
+ throw new Error(`a move is between two members, and both sides are ${opts.source.member}`);
339
525
  const sourceDir = stackDirOf(opts.source.dir, opts.cwd);
340
526
  const destDir = stackDirOf(opts.dest.dir, opts.cwd);
341
527
  const engine = engineOf(sourceDir, opts.engine, env);
@@ -344,74 +530,139 @@ export async function gatedStackMove(opts) {
344
530
  throw new Error(`${opts.source.member} runs on ${engine} and ${opts.dest.member} on ${destEngine}; a move needs both stacks on one engine`);
345
531
  const urns = [...new Set(opts.urns)].sort();
346
532
  const runners = { ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}), engine };
533
+ const sides = [
534
+ { ...opts.source, dir: sourceDir },
535
+ { ...opts.dest, dir: destDir },
536
+ ];
537
+ const side = (member) => sides.find((s) => s.member === member);
347
538
  const previews = async () => {
348
- const [s, d] = await Promise.all([
349
- previewPulumiMemberRead({ member: opts.source.member, dir: sourceDir, stack: opts.source.stack, ...runners }),
350
- previewPulumiMemberRead({ member: opts.dest.member, dir: destDir, stack: opts.dest.stack, ...runners }),
351
- ]);
539
+ const [s, d] = await Promise.all(sides.map((x) => previewPulumiMemberRead({ member: x.member, dir: x.dir, stack: x.stack, ...runners })));
352
540
  for (const p of [s.part, d.part]) {
353
541
  if (p.member.status === "failed")
354
542
  throw new Error(`the preview of ${p.member.member} failed: ${p.member.error ?? "no error printed"}`);
355
543
  }
356
544
  return { source: s.part, dest: d.part };
357
545
  };
358
- return askThenAct(opts, "stack-move", `move:${opts.source.stack}:${opts.dest.stack}`, { source: opts.source.stack, dest: opts.dest.stack, engine, urns: urns.join(",") }, `move of ${urns.length} resource(s) from ${opts.source.stack} to ${opts.dest.stack}`, async () => {
359
- let outcome;
360
- if (engine === "plunge") {
361
- const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns, yes: true });
362
- try {
363
- const { stdout } = await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir);
364
- outcome = moveView(stdout)?.doc;
546
+ // The plan: previews that change only the moved resources, plunge's own plan, each state's digest now.
547
+ const before = await previews();
548
+ const left = moveLeftovers(urns, before.source, before.dest);
549
+ if (left.length > 0)
550
+ throw new Error(`refusing to move: the previews change more than the moved resources, so the stacks would not preview no change after it: ${left.join("; ")}`);
551
+ if (engine === "plunge") {
552
+ const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
553
+ let view;
554
+ try {
555
+ view = moveView((await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir)).stdout);
556
+ }
557
+ catch (err) {
558
+ view = moveView(pulumiRunFailure(err).stdout);
559
+ if (!view)
560
+ throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
561
+ }
562
+ if (!view || view.status !== "planned") {
563
+ const reasons = view?.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
564
+ throw new Error(`refusing to move: plunge's plan is ${view?.status ?? "missing"}${reasons ? `: ${reasons}` : ""}`);
565
+ }
566
+ }
567
+ const digestOf = async (member) => sha256(await exportNow({ ...side(member), ...runners }));
568
+ const move = { source: opts.source.stack, dest: opts.dest.stack, urns };
569
+ const proof = { changes: [], summary: `the previews change only the ${urns.length} moved resource(s)` };
570
+ const roots = [];
571
+ for (const s of sides) {
572
+ roots.push({ root: s.member, location: stackLocation(s.dir, s.stack, env), before: { digest: await digestOf(s.member) }, after: { digest: sha256(JSON.stringify({ root: s.member, move })) }, proof });
573
+ }
574
+ let outcome;
575
+ const migration = {
576
+ async lock() {
577
+ for (const s of sides) {
578
+ const locks = engine === "plunge" ? { checked: false, ids: [] } : await pulumiStackLockIds({ dir: s.dir, stack: s.stack.split("/").at(-1), engine, env });
579
+ if (locks.ids.length > 0)
580
+ throw new Error(`${s.member} holds lock ${locks.ids.join(", ")}: an update is running on it, so nothing was moved`);
365
581
  }
366
- catch (err) {
367
- const view = moveView(pulumiRunFailure(err).stdout);
368
- if (view) {
369
- const reasons = view.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
370
- throw new Error(`plunge stack move ${view.status}: ${reasons || view.error || "no reason printed"}${view.status === "interrupted" ? "; run the move again to finish it" : ""}`);
582
+ return async () => undefined;
583
+ },
584
+ async current(root) {
585
+ return { digest: await digestOf(root) };
586
+ },
587
+ async write() {
588
+ if (engine === "plunge") {
589
+ const args = plungeMoveArgs({ ...move, yes: true });
590
+ try {
591
+ const { stdout } = await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir);
592
+ outcome = moveView(stdout)?.doc;
371
593
  }
372
- throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
594
+ catch (err) {
595
+ const view = moveView(pulumiRunFailure(err).stdout);
596
+ if (view) {
597
+ const reasons = view.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
598
+ throw new Error(`plunge stack move ${view.status}: ${reasons || view.error || "no reason printed"}${view.status === "interrupted" ? "; run the move again to finish it" : ""}`);
599
+ }
600
+ throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
601
+ }
602
+ return;
373
603
  }
374
- }
375
- else {
376
- const args = pulumiStateMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
604
+ const args = pulumiStateMoveArgs(move);
377
605
  try {
378
606
  await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, sourceDir);
379
607
  }
380
608
  catch (err) {
381
609
  throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
382
610
  }
383
- }
384
- // Both stacks must preview no change once the move is made.
385
- const after = await previews();
386
- const left = [...changing(after.source).map((e) => `${opts.source.member}: ${e.action} ${e.address}`), ...changing(after.dest).map((e) => `${opts.dest.member}: ${e.action} ${e.address}`)];
387
- const result = { engine, moved: urns, ...(outcome !== undefined ? { outcome } : {}) };
388
- return {
389
- result,
390
- detail: { moved: urns.length, engine, afterNoChange: left.length === 0 },
391
- ...(left.length > 0 ? { failed: `the move ran, and the stacks still preview changes: ${left.join("; ")}` } : {}),
392
- };
393
- }, async () => {
394
- const before = await previews();
395
- const left = moveLeftovers(urns, before.source, before.dest);
396
- if (left.length > 0)
397
- throw new Error(`refusing to move: the previews change more than the moved resources, so the stacks would not preview no change after it: ${left.join("; ")}`);
398
- if (engine === "plunge") {
399
- const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
400
- let view;
401
- try {
402
- view = moveView((await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir)).stdout);
403
- }
404
- catch (err) {
405
- view = moveView(pulumiRunFailure(err).stdout);
406
- if (!view)
407
- throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
408
- }
409
- if (!view || view.status !== "planned") {
410
- const reasons = view?.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
411
- throw new Error(`refusing to move: plunge's plan is ${view?.status ?? "missing"}${reasons ? `: ${reasons}` : ""}`);
412
- }
413
- }
611
+ },
612
+ async verify(root) {
613
+ const s = side(root);
614
+ const { part } = await previewPulumiMemberRead({ member: s.member, dir: s.dir, stack: s.stack, ...runners });
615
+ if (part.member.status === "failed")
616
+ return { changes: [`the preview failed: ${part.member.error ?? "no error printed"}`], summary: "preview failed" };
617
+ const changes = changing(part).map((e) => `${e.action} ${e.address}`);
618
+ return { changes, summary: changes.length === 0 ? "no change" : `${changes.length} change(s)` };
619
+ },
620
+ };
621
+ const subject = `move:${opts.source.stack}:${opts.dest.stack}`;
622
+ const fields = { source: opts.source.stack, dest: opts.dest.stack, engine, urns: urns.join(",") };
623
+ const r = await runStateMigration({
624
+ name: subject,
625
+ by: opts.by,
626
+ roots,
627
+ engine: migration,
628
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-move" },
629
+ fields,
630
+ detail: (res) => ({ urns: urns.length, engine, afterNoChange: res.status === "applied" }),
631
+ description: `move of ${urns.length} resource(s) from ${opts.source.stack} to ${opts.dest.stack}`,
632
+ ...(opts.runId ? { runId: opts.runId } : {}),
633
+ ...(opts.commit ? { commit: opts.commit } : {}),
634
+ ...gatedSettings(opts),
414
635
  });
636
+ const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-move", subject, by: opts.by, fields });
637
+ switch (r.status) {
638
+ case "proof-failed":
639
+ throw new Error(`refusing to move: ${r.failing.join(", ")} plan changes`);
640
+ case "waiting":
641
+ return { status: "waiting", digest: r.digest, request, command: r.command };
642
+ case "refused":
643
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
644
+ case "spent":
645
+ return { status: "spent", digest: r.digest, request };
646
+ case "approval-moved":
647
+ // An approval of an earlier request for these stacks stands, but their state moved since it (#4806), so it
648
+ // doesn't count for this one, and this request waits for its own.
649
+ return { status: "waiting", digest: r.digest, request, command: r.command };
650
+ case "moved":
651
+ return {
652
+ status: "failed",
653
+ digest: r.digest,
654
+ request,
655
+ check: "moved",
656
+ recorded: r.recorded,
657
+ error: `the state of ${(r.result.moved ?? []).join(", ")} changed since the plan, so nothing was moved; the approval is spent, so ask again for the stacks as they are now`,
658
+ };
659
+ case "failed": {
660
+ const still = (r.result?.roots ?? []).flatMap((x) => (x.verify?.changes ?? []).map((c) => `${x.root}: ${c}`));
661
+ return { status: "failed", digest: r.digest, request, recorded: r.recorded, error: still.length > 0 ? `the move ran, and the stacks still preview changes: ${still.join("; ")}` : r.error };
662
+ }
663
+ case "applied":
664
+ return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { engine, moved: urns, ...(outcome !== undefined ? { outcome } : {}) } };
665
+ }
415
666
  }
416
667
  /** A stack action refused before its request: `code` says why, `urns` names what the preview changed besides the action, for `action-scope`. */
417
668
  export class PulumiStackActionRefused extends Error {
@@ -512,22 +763,42 @@ export async function gatedStackAction(opts) {
512
763
  const digest = pulumiPreviewDigest(preview, { changedOnly: true });
513
764
  const subject = stackActionSubject(opts.stack, opts.name ?? opts.urn);
514
765
  const fields = { stack: opts.stack, urn: opts.urn, engine, preview: digest, ...(opts.name ? { name: opts.name } : {}) };
515
- return askThenAct(opts, "stack-action", subject, fields, `action ${opts.name ?? opts.urn} on stack ${opts.stack}: replace ${opts.urn}, requested by ${opts.by}`, async () => {
766
+ // core's gatedOp (#4808); reuseApplied makes a retried call with the same request answer `spent`.
767
+ const r = await gatedOp({
768
+ op: opts.op ?? PULUMI_STACK_OPS_OP,
769
+ request: { kind: "stack-action", subject, by: opts.by, fields },
770
+ description: `action ${opts.name ?? opts.urn} on stack ${opts.stack}: replace ${opts.urn}, requested by ${opts.by}`,
771
+ ...(opts.anew ? {} : { reuseApplied: true }),
772
+ ...gatedSettings(opts),
773
+ }, (async () => {
516
774
  const args = pulumiActionUpArgs(target);
517
775
  try {
518
776
  const done = engine === "plunge" ? await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, dir) : await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
519
777
  const tail = lastLines(done.stdout, 10);
520
- return { result: { urn: opts.urn, engine, preview: digest, exit: 0, tail }, detail: { result: "ok", exit: 0, tail: tail.slice(-400), urn: opts.urn } };
778
+ return { output: { result: { urn: opts.urn, engine, preview: digest, exit: 0, tail } }, detail: { result: "ok", exit: 0, tail: tail.slice(-400), urn: opts.urn } };
521
779
  }
522
780
  catch (err) {
523
781
  const f = pulumiRunFailure(err);
524
782
  const exit = f.exitCode ?? 1;
525
783
  const tail = lastLines(`${f.stdout ?? ""}\n${f.stderr ?? ""}`, 10);
526
- return {
527
- result: { urn: opts.urn, engine, preview: digest, exit, tail },
528
- detail: { result: "failed", exit, tail: tail.slice(-400), urn: opts.urn },
529
- failed: `${engine} ${args.join(" ")} failed: ${why(err, engine)}`,
530
- };
784
+ const error = `${engine} ${args.join(" ")} failed: ${why(err, engine)}`;
785
+ return { output: { result: { urn: opts.urn, engine, preview: digest, exit, tail }, error }, detail: { result: "failed", exit, tail: tail.slice(-400), urn: opts.urn, error: error.slice(0, 400) }, failed: true };
531
786
  }
532
- }, undefined, { reuseApplied: !opts.anew });
787
+ }));
788
+ switch (r.status) {
789
+ case "waiting":
790
+ return { status: "waiting", digest: r.digest, request: r.request, command: r.command };
791
+ case "refused":
792
+ return { status: "refused", digest: r.digest, request: r.request, by: r.by, reason: r.reason, command: r.command };
793
+ case "spent":
794
+ return { status: "spent", digest: r.digest, request: r.request };
795
+ case "held":
796
+ return { status: "failed", digest: r.digest, request: r.request, error: r.reason, recorded: false };
797
+ case "failed":
798
+ return { status: "failed", digest: r.digest, request: r.request, error: r.error.message, recorded: r.recorded };
799
+ case "done":
800
+ return r.output.error !== undefined
801
+ ? { status: "failed", digest: r.digest, request: r.request, error: r.output.error, recorded: r.recorded }
802
+ : { status: "done", digest: r.digest, request: r.request, result: r.output.result, approvedBy: r.approvedBy, recorded: r.recorded };
803
+ }
533
804
  }