@intentius/chant-lexicon-pulumi 0.124.98 → 0.124.99

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 (316) hide show
  1. package/dist/adopt.d.ts +0 -1
  2. package/dist/capability-plugin.d.ts +0 -1
  3. package/dist/change-set.d.ts +0 -1
  4. package/dist/changed-units.d.ts +0 -1
  5. package/dist/check-step.d.ts +0 -1
  6. package/dist/ci-setup.d.ts +0 -1
  7. package/dist/codegen/docs-cli.d.ts +0 -1
  8. package/dist/codegen/docs.d.ts +0 -1
  9. package/dist/codegen/package.d.ts +0 -1
  10. package/dist/composites/pulumi-adopt-op.d.ts +0 -1
  11. package/dist/composites/pulumi-watch-op.d.ts +0 -1
  12. package/dist/config.d.ts +0 -1
  13. package/dist/describe-resources.d.ts +0 -1
  14. package/dist/drift-read.d.ts +0 -1
  15. package/dist/drift-record.d.ts +0 -1
  16. package/dist/engine-events.d.ts +0 -1
  17. package/dist/engine-graph.d.ts +0 -1
  18. package/dist/exit-codes.d.ts +0 -1
  19. package/dist/index.d.ts +0 -1
  20. package/dist/init-templates.d.ts +0 -1
  21. package/dist/integrity.json +2 -2
  22. package/dist/lint/audit-catalog.d.ts +0 -1
  23. package/dist/lint/post-synth/index.d.ts +0 -1
  24. package/dist/lint/post-synth/member-read-helpers.d.ts +0 -1
  25. package/dist/lint/post-synth/pul001.d.ts +0 -1
  26. package/dist/lint/post-synth/pul002.d.ts +0 -1
  27. package/dist/lint/post-synth/pul003.d.ts +0 -1
  28. package/dist/lint/post-synth/pul004.d.ts +0 -1
  29. package/dist/lint/post-synth/pul005.d.ts +0 -1
  30. package/dist/lint/post-synth/pul006.d.ts +0 -1
  31. package/dist/lint/post-synth/pul007.d.ts +0 -1
  32. package/dist/lint/post-synth/pul008.d.ts +0 -1
  33. package/dist/lint/post-synth/pul009.d.ts +0 -1
  34. package/dist/lint/post-synth/pul010.d.ts +0 -1
  35. package/dist/lint/post-synth/pul011.d.ts +0 -1
  36. package/dist/lint/post-synth/pul012.d.ts +0 -1
  37. package/dist/lint/post-synth/pul013.d.ts +0 -1
  38. package/dist/lint/post-synth/pul014.d.ts +0 -1
  39. package/dist/lint/post-synth/pul015.d.ts +0 -1
  40. package/dist/lint/rules/index.d.ts +0 -1
  41. package/dist/lint/rules/member-dir-absolute.d.ts +0 -1
  42. package/dist/lock-rows.d.ts +0 -1
  43. package/dist/lsp/completions.d.ts +0 -1
  44. package/dist/lsp/documents.d.ts +0 -1
  45. package/dist/lsp/hover.d.ts +0 -1
  46. package/dist/lsp/keys.d.ts +0 -1
  47. package/dist/lsp/object-path.d.ts +0 -1
  48. package/dist/lsp/yaml-cursor.d.ts +0 -1
  49. package/dist/manifest.json +1 -1
  50. package/dist/member-engine.d.ts +0 -1
  51. package/dist/member-outputs.d.ts +0 -1
  52. package/dist/op/activities/index.d.ts +0 -1
  53. package/dist/op/activities/pulumi-adopt.d.ts +0 -1
  54. package/dist/op/activities/pulumi.d.ts +0 -1
  55. package/dist/op/activity-contracts.d.ts +0 -1
  56. package/dist/op/builders.d.ts +0 -1
  57. package/dist/package-cli.d.ts +0 -1
  58. package/dist/plan-shape.d.ts +0 -1
  59. package/dist/planned-output-changes.d.ts +0 -1
  60. package/dist/plugin.d.ts +0 -1
  61. package/dist/plunge-timings.d.ts +0 -1
  62. package/dist/preview-tips.d.ts +0 -1
  63. package/dist/pulumi-up.d.ts +0 -1
  64. package/dist/release-copy.d.ts +0 -1
  65. package/dist/review-stack.d.ts +0 -1
  66. package/dist/run.d.ts +0 -1
  67. package/dist/serializer.d.ts +0 -1
  68. package/dist/stack-export-snapshot.d.ts +0 -1
  69. package/dist/stack-ops.d.ts +0 -1
  70. package/dist/stack-outputs.d.ts +0 -1
  71. package/dist/stack-references.d.ts +0 -1
  72. package/dist/trace-facts.d.ts +0 -1
  73. package/dist/values.d.ts +0 -1
  74. package/dist/workspace-member.d.ts +0 -1
  75. package/package.json +3 -4
  76. package/dist/adopt.d.ts.map +0 -1
  77. package/dist/capability-plugin.d.ts.map +0 -1
  78. package/dist/change-set.d.ts.map +0 -1
  79. package/dist/changed-units.d.ts.map +0 -1
  80. package/dist/check-step.d.ts.map +0 -1
  81. package/dist/ci-setup.d.ts.map +0 -1
  82. package/dist/codegen/docs-cli.d.ts.map +0 -1
  83. package/dist/codegen/docs.d.ts.map +0 -1
  84. package/dist/codegen/package.d.ts.map +0 -1
  85. package/dist/composites/pulumi-adopt-op.d.ts.map +0 -1
  86. package/dist/composites/pulumi-watch-op.d.ts.map +0 -1
  87. package/dist/config.d.ts.map +0 -1
  88. package/dist/describe-resources.d.ts.map +0 -1
  89. package/dist/drift-read.d.ts.map +0 -1
  90. package/dist/drift-record.d.ts.map +0 -1
  91. package/dist/engine-events.d.ts.map +0 -1
  92. package/dist/engine-graph.d.ts.map +0 -1
  93. package/dist/exit-codes.d.ts.map +0 -1
  94. package/dist/index.d.ts.map +0 -1
  95. package/dist/init-templates.d.ts.map +0 -1
  96. package/dist/lint/audit-catalog.d.ts.map +0 -1
  97. package/dist/lint/post-synth/index.d.ts.map +0 -1
  98. package/dist/lint/post-synth/member-read-helpers.d.ts.map +0 -1
  99. package/dist/lint/post-synth/pul001.d.ts.map +0 -1
  100. package/dist/lint/post-synth/pul002.d.ts.map +0 -1
  101. package/dist/lint/post-synth/pul003.d.ts.map +0 -1
  102. package/dist/lint/post-synth/pul004.d.ts.map +0 -1
  103. package/dist/lint/post-synth/pul005.d.ts.map +0 -1
  104. package/dist/lint/post-synth/pul006.d.ts.map +0 -1
  105. package/dist/lint/post-synth/pul007.d.ts.map +0 -1
  106. package/dist/lint/post-synth/pul008.d.ts.map +0 -1
  107. package/dist/lint/post-synth/pul009.d.ts.map +0 -1
  108. package/dist/lint/post-synth/pul010.d.ts.map +0 -1
  109. package/dist/lint/post-synth/pul011.d.ts.map +0 -1
  110. package/dist/lint/post-synth/pul012.d.ts.map +0 -1
  111. package/dist/lint/post-synth/pul013.d.ts.map +0 -1
  112. package/dist/lint/post-synth/pul014.d.ts.map +0 -1
  113. package/dist/lint/post-synth/pul015.d.ts.map +0 -1
  114. package/dist/lint/rules/index.d.ts.map +0 -1
  115. package/dist/lint/rules/member-dir-absolute.d.ts.map +0 -1
  116. package/dist/lock-rows.d.ts.map +0 -1
  117. package/dist/lsp/completions.d.ts.map +0 -1
  118. package/dist/lsp/documents.d.ts.map +0 -1
  119. package/dist/lsp/hover.d.ts.map +0 -1
  120. package/dist/lsp/keys.d.ts.map +0 -1
  121. package/dist/lsp/object-path.d.ts.map +0 -1
  122. package/dist/lsp/yaml-cursor.d.ts.map +0 -1
  123. package/dist/member-engine.d.ts.map +0 -1
  124. package/dist/member-outputs.d.ts.map +0 -1
  125. package/dist/op/activities/index.d.ts.map +0 -1
  126. package/dist/op/activities/pulumi-adopt.d.ts.map +0 -1
  127. package/dist/op/activities/pulumi.d.ts.map +0 -1
  128. package/dist/op/activity-contracts.d.ts.map +0 -1
  129. package/dist/op/builders.d.ts.map +0 -1
  130. package/dist/package-cli.d.ts.map +0 -1
  131. package/dist/plan-shape.d.ts.map +0 -1
  132. package/dist/planned-output-changes.d.ts.map +0 -1
  133. package/dist/plugin.d.ts.map +0 -1
  134. package/dist/plunge-timings.d.ts.map +0 -1
  135. package/dist/preview-tips.d.ts.map +0 -1
  136. package/dist/pulumi-up.d.ts.map +0 -1
  137. package/dist/release-copy.d.ts.map +0 -1
  138. package/dist/review-stack.d.ts.map +0 -1
  139. package/dist/run.d.ts.map +0 -1
  140. package/dist/serializer.d.ts.map +0 -1
  141. package/dist/stack-export-snapshot.d.ts.map +0 -1
  142. package/dist/stack-ops.d.ts.map +0 -1
  143. package/dist/stack-outputs.d.ts.map +0 -1
  144. package/dist/stack-references.d.ts.map +0 -1
  145. package/dist/trace-facts.d.ts.map +0 -1
  146. package/dist/values.d.ts.map +0 -1
  147. package/dist/workspace-member.d.ts.map +0 -1
  148. package/src/adopt.ts +0 -202
  149. package/src/capability-plugin.ts +0 -34
  150. package/src/change-set.test.ts +0 -245
  151. package/src/change-set.ts +0 -508
  152. package/src/changed-units.test.ts +0 -87
  153. package/src/changed-units.ts +0 -96
  154. package/src/check-step.test.ts +0 -191
  155. package/src/check-step.ts +0 -316
  156. package/src/ci-setup.test.ts +0 -234
  157. package/src/ci-setup.ts +0 -224
  158. package/src/codegen/docs-cli.ts +0 -4
  159. package/src/codegen/docs.ts +0 -58
  160. package/src/codegen/package.ts +0 -63
  161. package/src/composites/pulumi-adopt-op.test.ts +0 -258
  162. package/src/composites/pulumi-adopt-op.ts +0 -193
  163. package/src/composites/pulumi-watch-op.test.ts +0 -42
  164. package/src/composites/pulumi-watch-op.ts +0 -85
  165. package/src/config.ts +0 -43
  166. package/src/describe-resources.test.ts +0 -112
  167. package/src/describe-resources.ts +0 -118
  168. package/src/drift-read.test.ts +0 -178
  169. package/src/drift-read.ts +0 -94
  170. package/src/drift-record.test.ts +0 -197
  171. package/src/drift-record.ts +0 -326
  172. package/src/engine-events.test.ts +0 -160
  173. package/src/engine-events.ts +0 -395
  174. package/src/engine-graph.test.ts +0 -141
  175. package/src/engine-graph.ts +0 -149
  176. package/src/exit-codes.test.ts +0 -21
  177. package/src/exit-codes.ts +0 -71
  178. package/src/index.ts +0 -139
  179. package/src/init-templates.ts +0 -85
  180. package/src/lint/audit-catalog.test.ts +0 -33
  181. package/src/lint/audit-catalog.ts +0 -174
  182. package/src/lint/post-synth/index.ts +0 -35
  183. package/src/lint/post-synth/member-read-helpers.ts +0 -122
  184. package/src/lint/post-synth/post-synth.test.ts +0 -245
  185. package/src/lint/post-synth/pul001.ts +0 -38
  186. package/src/lint/post-synth/pul002.ts +0 -38
  187. package/src/lint/post-synth/pul003.ts +0 -43
  188. package/src/lint/post-synth/pul004.ts +0 -32
  189. package/src/lint/post-synth/pul005.ts +0 -31
  190. package/src/lint/post-synth/pul006.ts +0 -31
  191. package/src/lint/post-synth/pul007.ts +0 -35
  192. package/src/lint/post-synth/pul008.ts +0 -35
  193. package/src/lint/post-synth/pul009.ts +0 -32
  194. package/src/lint/post-synth/pul010.ts +0 -42
  195. package/src/lint/post-synth/pul011.ts +0 -38
  196. package/src/lint/post-synth/pul012.ts +0 -35
  197. package/src/lint/post-synth/pul013.ts +0 -35
  198. package/src/lint/post-synth/pul014.ts +0 -32
  199. package/src/lint/post-synth/pul015.ts +0 -39
  200. package/src/lint/rules/index.ts +0 -7
  201. package/src/lint/rules/member-dir-absolute.test.ts +0 -37
  202. package/src/lint/rules/member-dir-absolute.ts +0 -83
  203. package/src/lock-rows.test.ts +0 -60
  204. package/src/lock-rows.ts +0 -56
  205. package/src/lsp/completions.test.ts +0 -69
  206. package/src/lsp/completions.ts +0 -119
  207. package/src/lsp/documents.ts +0 -48
  208. package/src/lsp/hover.test.ts +0 -56
  209. package/src/lsp/hover.ts +0 -83
  210. package/src/lsp/keys.ts +0 -169
  211. package/src/lsp/object-path.ts +0 -71
  212. package/src/lsp/yaml-cursor.ts +0 -85
  213. package/src/member-engine.test.ts +0 -112
  214. package/src/member-engine.ts +0 -97
  215. package/src/member-outputs.test.ts +0 -339
  216. package/src/member-outputs.ts +0 -157
  217. package/src/op/activities/index.ts +0 -36
  218. package/src/op/activities/pulumi-adopt.ts +0 -345
  219. package/src/op/activities/pulumi.ts +0 -136
  220. package/src/op/activity-contracts.ts +0 -129
  221. package/src/op/builders.ts +0 -67
  222. package/src/package-cli.ts +0 -14
  223. package/src/plan-shape.test.ts +0 -91
  224. package/src/plan-shape.ts +0 -105
  225. package/src/planned-output-changes.test.ts +0 -85
  226. package/src/planned-output-changes.ts +0 -141
  227. package/src/plugin.test.ts +0 -96
  228. package/src/plugin.ts +0 -272
  229. package/src/plunge-timings.test.ts +0 -241
  230. package/src/plunge-timings.ts +0 -115
  231. package/src/plunge-up-failed.test.ts +0 -54
  232. package/src/pr-note.test.ts +0 -87
  233. package/src/preview-generated.test.ts +0 -124
  234. package/src/preview-tips.test.ts +0 -134
  235. package/src/preview-tips.ts +0 -128
  236. package/src/pulumi-up.test.ts +0 -581
  237. package/src/pulumi-up.ts +0 -1102
  238. package/src/pulumi-urn-node.test.ts +0 -94
  239. package/src/release-copy.test.ts +0 -162
  240. package/src/release-copy.ts +0 -223
  241. package/src/review-stack.test.ts +0 -254
  242. package/src/review-stack.ts +0 -266
  243. package/src/run-plan-flags.test.ts +0 -53
  244. package/src/run.test.ts +0 -540
  245. package/src/run.ts +0 -1129
  246. package/src/serializer.test.ts +0 -9
  247. package/src/serializer.ts +0 -15
  248. package/src/skills/chant-pulumi-plunge.md +0 -51
  249. package/src/skills/chant-pulumi-stack-export.md +0 -54
  250. package/src/skills/chant-pulumi.md +0 -83
  251. package/src/stack-export-snapshot.test.ts +0 -192
  252. package/src/stack-export-snapshot.ts +0 -312
  253. package/src/stack-ops.fake-binary.test.ts +0 -323
  254. package/src/stack-ops.test.ts +0 -511
  255. package/src/stack-ops.ts +0 -1082
  256. package/src/stack-outputs.ts +0 -66
  257. package/src/stack-references.test.ts +0 -96
  258. package/src/stack-references.ts +0 -110
  259. package/src/testdata/plunge-drift/README.md +0 -10
  260. package/src/testdata/plunge-drift/assets-drifted.ndjson +0 -3
  261. package/src/testdata/plunge-drift/component-unsupported.ndjson +0 -3
  262. package/src/testdata/plunge-drift/role-in-sync.ndjson +0 -3
  263. package/src/testdata/plunge-drift/settled-empty.ndjson +0 -2
  264. package/src/testdata/plunge-graph/Pulumi.yaml +0 -4
  265. package/src/testdata/plunge-graph/README.md +0 -12
  266. package/src/testdata/plunge-graph/engine-graph.json +0 -158
  267. package/src/testdata/plunge-graph/stack-export.json +0 -49
  268. package/src/testdata/plunge-member/Pulumi.yaml +0 -4
  269. package/src/testdata/plunge-member/README.md +0 -3
  270. package/src/testdata/plunge-member/stack-export.json +0 -480
  271. package/src/testdata/plunge-outputs/Pulumi.yaml +0 -9
  272. package/src/testdata/plunge-outputs/README.md +0 -7
  273. package/src/testdata/plunge-outputs/stack-export.json +0 -2003
  274. package/src/testdata/plunge-outputs/stack-output.json +0 -19
  275. package/src/testdata/pulumi-member/Pulumi.yaml +0 -2
  276. package/src/testdata/pulumi-member/README.md +0 -50
  277. package/src/testdata/pulumi-member/recording/Pulumi.dev.yaml +0 -19
  278. package/src/testdata/pulumi-member/recording/Pulumi.yaml +0 -7
  279. package/src/testdata/pulumi-member/recording/index.js +0 -47
  280. package/src/testdata/pulumi-member/recording/package-lock.json +0 -2707
  281. package/src/testdata/pulumi-member/recording/package.json +0 -9
  282. package/src/testdata/pulumi-member/stack-export.json +0 -746
  283. package/src/testdata/pulumi-outputs/Pulumi.yaml +0 -7
  284. package/src/testdata/pulumi-outputs/README.md +0 -9
  285. package/src/testdata/pulumi-outputs/preview-replaced.json +0 -2894
  286. package/src/testdata/pulumi-outputs/preview-settled.json +0 -2894
  287. package/src/testdata/pulumi-outputs/stack-export.json +0 -1919
  288. package/src/testdata/pulumi-outputs/stack-output.json +0 -19
  289. package/src/testdata/pulumi-preview/Pulumi.yaml +0 -7
  290. package/src/testdata/pulumi-preview/README.md +0 -9
  291. package/src/testdata/pulumi-preview/preview-create.json +0 -992
  292. package/src/testdata/pulumi-preview/preview.json +0 -2894
  293. package/src/testdata/pulumi-preview/stack-export.json +0 -1919
  294. package/src/testdata/pulumi-refresh/Pulumi.yaml +0 -7
  295. package/src/testdata/pulumi-refresh/README.md +0 -14
  296. package/src/testdata/pulumi-refresh/all.json +0 -3742
  297. package/src/testdata/pulumi-refresh/bucket-edited.json +0 -468
  298. package/src/testdata/pulumi-refresh/policy-deleted.json +0 -95
  299. package/src/testdata/pulumi-refresh/queue-edited.json +0 -250
  300. package/src/testdata/pulumi-refresh/role-same.json +0 -242
  301. package/src/testdata/pulumi-refresh/secret-edited.json +0 -247
  302. package/src/testdata/pulumi-refresh/stack-export.json +0 -1907
  303. package/src/testdata/pulumi-stream/README.md +0 -16
  304. package/src/testdata/pulumi-stream/preview-stream.ndjson +0 -42
  305. package/src/testdata/pulumi-stream/up-failed-plunge.ndjson +0 -5
  306. package/src/testdata/pulumi-unexported/Pulumi.yaml +0 -2
  307. package/src/testdata/pulumi-urn-node/Pulumi.yaml +0 -7
  308. package/src/testdata/pulumi-urn-node/README.md +0 -9
  309. package/src/testdata/pulumi-urn-node/preview.json +0 -2894
  310. package/src/testdata/pulumi-urn-node/stack-export.json +0 -1919
  311. package/src/trace-facts.test.ts +0 -38
  312. package/src/trace-facts.ts +0 -83
  313. package/src/values.ts +0 -147
  314. package/src/workspace-kinds.test.ts +0 -47
  315. package/src/workspace-member.test.ts +0 -127
  316. package/src/workspace-member.ts +0 -304
package/src/stack-ops.ts DELETED
@@ -1,1082 +0,0 @@
1
- /**
2
- * Gated stack operations (#4578): a stack's export, a stuck lock's release,
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.
16
- *
17
- * ## The request
18
- *
19
- * Each operation is a `GatedRequest` under the op {@link PULUMI_STACK_OPS_OP}
20
- * (or the caller's), its digest `gatedRequestDigest` over the op and the
21
- * request, so chant computes what an approval binds:
22
- *
23
- * | Operation | kind | subject (the gate) | fields |
24
- * |---|---|---|---|
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) |
28
- * | action | `stack-action` | `action:<stack>:<name>` (the URN without a name) | `stack`, `urn`, `engine`, `preview` (the preview's digest), `name` when given |
29
- *
30
- * The first call records the pending fact and answers `waiting` with the
31
- * `chant approve` command. A later call with the same request reuses the
32
- * standing request's `at`, so it digests the same and finds the approval.
33
- * The requester's own approval never counts (`refused`). Once approved, the
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.
37
- *
38
- * ## What runs
39
- *
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.
70
- *
71
- * - action (#4654): a day-2 action is a `command:` resource
72
- * (`command:local:Command`, `command:remote:Command`) whose replacement is
73
- * the operation. Its type is checked before anything runs (`action-type`).
74
- * Each call previews `preview --json --target <urn> --replace <urn>`, and
75
- * refuses (`action-scope`) unless the preview changes that URN alone, by
76
- * a replacement. The request binds the preview's digest, so a preview
77
- * that moved after the approval asks again. Once approved, `up --yes
78
- * --target <urn> --replace <urn> --stack <s>` under the stack's engine,
79
- * and the finished line keeps chant's `applied | failed` with
80
- * `detail.result` `ok` or `failed`, the exit code and the output's last
81
- * lines. A request that applied answers `spent` to the same call, unless
82
- * the caller asks `anew`.
83
- *
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.
87
- */
88
- import { createHash } from "node:crypto";
89
- import { existsSync, readdirSync, readFileSync } from "node:fs";
90
- import { isAbsolute, join, resolve } from "node:path";
91
- import type { ChangeSetPart } from "@intentius/chant/change-set";
92
- import type { ForgeOverrides } from "@intentius/chant/forge-flags";
93
- import { chantGatedLedger, gatedOp, type GatedOpAct, type GatedRequestLedger } from "@intentius/chant/lifecycle/gated-op";
94
- import type { GatedRequest, GatedRequestRules } from "@intentius/chant/lifecycle/gated-request";
95
- import type { ForgeTargetOptions } from "@intentius/chant/pr-forge";
96
- import { exportStateVersion, StateExportError, type StateVersionSource } from "@intentius/chant/state-export";
97
- import { runStateMigration, type MigrationCheck, type MigrationRootPlan, type StateMigrationEngine } from "@intentius/chant/state-migration";
98
- import { describeRun, forgeLiveRunsOf, releaseStateLock, type LiveRun, type LockInfo, type StateLockSource } from "@intentius/chant/state-unlock";
99
- import { parsePulumiUrn, pulumiNodeKey } from "@intentius/chant/pulumi-urn";
100
- import { pulumiStackBackend } from "./adopt";
101
- import { pulumiExportResources, pulumiPreviewDigest, pulumiSteps, PULUMI_UNCHANGED_OPS } from "./change-set";
102
- import { pulumiMemberEngine, type PulumiMemberEngine } from "./member-engine";
103
- import {
104
- defaultPlungeRunner,
105
- defaultPulumiRunner,
106
- plungeMoveArgs,
107
- previewPulumiMemberRead,
108
- pulumiActionPreviewArgs,
109
- pulumiActionUpArgs,
110
- pulumiCancelArgs,
111
- pulumiRunFailure,
112
- pulumiStackExportVersionArgs,
113
- pulumiStackHistoryArgs,
114
- pulumiStateMoveArgs,
115
- runAllowedPlunge,
116
- runAllowedPulumi,
117
- runGatedPlunge,
118
- runGatedPulumi,
119
- runStackOpReadPulumi,
120
- type PulumiRunner,
121
- } from "./run";
122
- import { isObject } from "./values";
123
-
124
- /** The op the requests are recorded under, unless the caller names its own. */
125
- export const PULUMI_STACK_OPS_OP = "pulumi-stack-ops";
126
-
127
- export type PulumiStackOpKind = "stack-export" | "stack-cancel" | "stack-move" | "stack-action";
128
-
129
- /** chant's gated-request ledger (#4551), injectable for tests: core's `GatedRequestLedger`. */
130
- export type GatedRequestApi = GatedRequestLedger;
131
-
132
- /** What every operation takes. */
133
- export interface PulumiStackOpCommon {
134
- /** The requester, as the ledger names identities. Their own approval never counts. */
135
- by: string;
136
- /** Which approvals count: the block op waves read at base. */
137
- rules: GatedRequestRules;
138
- /** The op the request is recorded under. Default {@link PULUMI_STACK_OPS_OP}. */
139
- op?: string;
140
- /** Where the workspace ledger is read and written. Default the process's cwd. */
141
- ledgerCwd?: string;
142
- /** How long the pending fact stands. Default 48h. */
143
- expiry?: string;
144
- /** The ref the rules are read at. */
145
- base?: string;
146
- now?: string;
147
- run?: PulumiRunner;
148
- plunge?: PulumiRunner;
149
- env?: Record<string, string | undefined>;
150
- gated?: GatedRequestApi;
151
- /**
152
- * The command a waiting or refused request prints (#4911), as the product
153
- * words it: a function of the gate (the request's subject) and the
154
- * digest, which core's adapters take as `words.approveCommand`, or a
155
- * template whose `{op}`, `{gate}`, `{digest}` and `{sign}` chant fills,
156
- * `{sign}` being `--sign` when `rules.mode` is `sealed`. Default core's
157
- * line.
158
- */
159
- approveCommand?: string | ((subject: string, digest: string) => string);
160
- }
161
-
162
- /** The approve line `common` asks for (#4911), as core's adapters take `words.approveCommand`; undefined for core's own. */
163
- export function stackOpApproveCommand(common: Pick<PulumiStackOpCommon, "approveCommand" | "rules" | "op">): ((subject: string, digest: string) => string) | undefined {
164
- const given = common.approveCommand;
165
- if (given === undefined) return undefined;
166
- if (typeof given === "function") return given;
167
- const op = common.op ?? PULUMI_STACK_OPS_OP;
168
- const sign = common.rules.mode === "sealed" ? "--sign" : "";
169
- return (gate, digest) =>
170
- given
171
- .replace(/\{(op|gate|digest|sign)\}/g, (_, k: string) => ({ op, gate, digest, sign })[k as "op"])
172
- .replace(/\s+/g, " ")
173
- .trim();
174
- }
175
-
176
- /** The words core's walks take: the op, the kind, and the product's approve line when it gives one. */
177
- function wordsOf(common: PulumiStackOpCommon, kind: PulumiStackOpKind) {
178
- const approveCommand = stackOpApproveCommand(common);
179
- return { op: common.op ?? PULUMI_STACK_OPS_OP, kind, ...(approveCommand ? { approveCommand } : {}) };
180
- }
181
-
182
- /** Which of core's checks stopped an operation that was approved (#4808): a state that moved between the plan and the write. */
183
- export type PulumiStackOpCheck = "moved";
184
-
185
- /** How a call ended. Only `done` and `failed` ran anything. */
186
- export type PulumiStackOpOutcome<T> =
187
- | { status: "waiting"; digest: string; request: GatedRequest; command: string }
188
- /** An approval stands and does not count, such as the requester's own. */
189
- | { status: "refused"; digest: string; request: GatedRequest; by: string; reason: string; command: string }
190
- /** It ran already under an approval; a request runs once. */
191
- | { status: "spent"; digest: string; request: GatedRequest }
192
- | { status: "done"; digest: string; request: GatedRequest; result: T; approvedBy?: string; recorded?: boolean }
193
- | { status: "failed"; digest: string; request: GatedRequest; error: string; check?: PulumiStackOpCheck; recorded?: boolean };
194
-
195
- /** Why an operation was refused without acting (#4808). `held` was approved and stays unspent. */
196
- export type PulumiStackOpRefusal = "live-run" | "held" | "lock-gone";
197
-
198
- /** An operation core's checks refused before it acted: `code` says which, `runs` names the live runs. */
199
- export class PulumiStackOpRefused extends Error {
200
- readonly code: PulumiStackOpRefusal;
201
- readonly runs: LiveRun[];
202
- readonly digest?: string;
203
- constructor(code: PulumiStackOpRefusal, message: string, extra: { runs?: LiveRun[]; digest?: string } = {}) {
204
- super(`${code}: ${message}`);
205
- this.name = "PulumiStackOpRefused";
206
- this.code = code;
207
- this.runs = extra.runs ?? [];
208
- if (extra.digest) this.digest = extra.digest;
209
- }
210
- }
211
-
212
- /** The gated-request settings core's walks take, from the common options. */
213
- function gatedSettings(common: PulumiStackOpCommon) {
214
- return {
215
- rules: common.rules,
216
- ...(common.ledgerCwd ? { cwd: common.ledgerCwd } : {}),
217
- ...(common.expiry ? { expiry: common.expiry } : {}),
218
- ...(common.base ? { base: common.base } : {}),
219
- ...(common.now ? { now: common.now } : {}),
220
- ...(common.gated ? { ledger: common.gated } : {}),
221
- };
222
- }
223
-
224
- /** 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. */
225
- async function askedRequest(common: PulumiStackOpCommon, digest: string, fallback: Omit<GatedRequest, "at">): Promise<GatedRequest> {
226
- const read = digest ? await (common.gated ?? chantGatedLedger).readGatedRequests(common.op ?? PULUMI_STACK_OPS_OP, common.ledgerCwd ? { cwd: common.ledgerCwd } : undefined).catch(() => []) : [];
227
- return read.find((g) => g.digest === digest)?.request ?? { ...fallback, at: "" };
228
- }
229
-
230
- function stackDirOf(dir: string, cwd?: string): string {
231
- return isAbsolute(dir) ? dir : resolve(cwd ?? process.cwd(), dir);
232
- }
233
-
234
- function engineOf(dir: string, engine: PulumiMemberEngine | undefined, env?: Record<string, string | undefined>): PulumiMemberEngine {
235
- return pulumiMemberEngine(dir, engine, env ? { env } : {}).engine;
236
- }
237
-
238
- function why(err: unknown, binary: string): string {
239
- const f = pulumiRunFailure(err);
240
- return f.missingBinary ? `the ${binary} binary was not found on PATH` : (f.stderr?.trim() || f.message).split("\n").slice(-3).join("\n");
241
- }
242
-
243
- const sha256 = (text: string): string => `sha256:${createHash("sha256").update(text).digest("hex")}`;
244
-
245
- /** Where a stack's state is, as messages and the record name it: the stack and its backend's URL, never a credential. */
246
- function stackLocation(dir: string, stack: string, env: Record<string, string | undefined>): string {
247
- const backend = pulumiStackBackend(dir, { env });
248
- return `stack ${stack}${backend ? ` at ${backend.url}` : ""}`;
249
- }
250
-
251
- /** The stack's export now, under its engine's read form. */
252
- async function exportNow(opts: { dir: string; stack: string; engine: PulumiMemberEngine; run?: PulumiRunner; plunge?: PulumiRunner }): Promise<string> {
253
- const args = ["stack", "export", "--stack", opts.stack];
254
- try {
255
- const { stdout } = opts.engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, opts.dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir);
256
- return stdout;
257
- } catch (err) {
258
- throw new Error(`${opts.engine} ${args.join(" ")} failed: ${why(err, opts.engine)}`);
259
- }
260
- }
261
-
262
- // ── export ───────────────────────────────────────────────────────────────
263
-
264
- /** The CI variables that mark a job, where an export would become an artifact. Core's list (`@intentius/chant/state-export`). */
265
- export { CI_MARKERS, enclosingWorkTree } from "@intentius/chant/state-export";
266
-
267
- /** A version id that is an update's number, as `stack history` and `stack export --version` take it. */
268
- const UPDATE_NUMBER = /^[1-9][0-9]*$/;
269
-
270
- /**
271
- * A stack's state read by version (#4808), core's `StateVersionSource` for
272
- * `exportStateVersion`. On a backend that numbers its updates the version
273
- * is the newest update's number (`stack history --json --page-size 1`), a
274
- * version is held when it is between 1 and that number, and one is read
275
- * with `stack export --version <n>`. A backend that numbers none (a file
276
- * backend answers `0`, plunge keeps no history chant reads) has one version,
277
- * the one it holds now, named by its export's `sha256:` digest; reading it
278
- * exports again and refuses an export whose digest moved. `read` keeps the
279
- * last export's size and resource count for the caller.
280
- */
281
- export function pulumiStackVersionSource(opts: { dir: string; stack: string; engine: PulumiMemberEngine; run?: PulumiRunner; plunge?: PulumiRunner; env?: Record<string, string | undefined> }): StateVersionSource & { read?: { bytes: number; resources: number } } {
282
- const location = stackLocation(opts.dir, opts.stack, opts.env ?? process.env);
283
- const newest = async (): Promise<number | undefined> => {
284
- if (opts.engine === "plunge") return undefined;
285
- let stdout: string;
286
- try {
287
- ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, pulumiStackHistoryArgs(opts.stack), opts.dir));
288
- } catch {
289
- // A history that cannot be read numbers nothing; the export by digest still stands.
290
- return undefined;
291
- }
292
- try {
293
- const doc = JSON.parse(stdout) as unknown;
294
- const first = Array.isArray(doc) ? doc[0] : undefined;
295
- const v = isObject(first) && typeof first.version === "number" ? first.version : 0;
296
- return v > 0 ? v : undefined;
297
- } catch {
298
- return undefined;
299
- }
300
- };
301
- const checked = (body: string, what: string): string => {
302
- let resources: number;
303
- try {
304
- resources = pulumiExportResources(JSON.parse(body)).length;
305
- } catch {
306
- throw new StateExportError(`${what} printed no JSON`);
307
- }
308
- source.read = { bytes: Buffer.byteLength(body), resources };
309
- return body;
310
- };
311
- const source: StateVersionSource & { read?: { bytes: number; resources: number } } = {
312
- location,
313
- async current() {
314
- const n = await newest();
315
- if (n !== undefined) return { exists: true, versionId: String(n) };
316
- return { exists: true, versionId: sha256(await exportNow(opts)) };
317
- },
318
- async hasVersion(id) {
319
- if (UPDATE_NUMBER.test(id)) {
320
- const n = await newest();
321
- return n !== undefined && Number(id) <= n;
322
- }
323
- return id.startsWith("sha256:") && (await newest()) === undefined && sha256(await exportNow(opts)) === id;
324
- },
325
- async readVersion(id) {
326
- if (UPDATE_NUMBER.test(id)) {
327
- const args = pulumiStackExportVersionArgs(opts.stack, id);
328
- let stdout: string;
329
- try {
330
- ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir));
331
- } catch (err) {
332
- throw new StateExportError(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
333
- }
334
- return checked(stdout, `pulumi ${args.join(" ")}`);
335
- }
336
- const body = await exportNow(opts);
337
- if (sha256(body) !== id) 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`);
338
- return checked(body, `${opts.engine} stack export --stack ${opts.stack}`);
339
- },
340
- };
341
- return source;
342
- }
343
-
344
- export interface PulumiStackExportOptions extends PulumiStackOpCommon {
345
- /** The stack's directory, where `Pulumi.yaml` is. */
346
- dir: string;
347
- cwd?: string;
348
- stack: string;
349
- engine?: PulumiMemberEngine;
350
- /** Where the export is written on the requester's machine: outside every git working tree, and not there yet. */
351
- out: string;
352
- /** The version to export (#4808): an update's number on a backend that numbers them, else the `sha256:` digest of the export now. Default the version the stack holds now. */
353
- version?: string;
354
- }
355
-
356
- export interface PulumiStackExportResult {
357
- file: string;
358
- /** The hex SHA-256 of the bytes written. */
359
- sha256: string;
360
- bytes: number;
361
- resources: number;
362
- /** The version exported (#4808). */
363
- version: string;
364
- }
365
-
366
- /**
367
- * A stack's export, one version of it, delivered to the requester's machine
368
- * after a second identity approves it: core's `exportStateVersion` over
369
- * {@link pulumiStackVersionSource}. Refused in CI, for a destination inside
370
- * a git working tree or over a file, and for a version the stack does not
371
- * have, before anything is asked.
372
- */
373
- export async function gatedStackExport(opts: PulumiStackExportOptions): Promise<PulumiStackOpOutcome<PulumiStackExportResult>> {
374
- const env = opts.env ?? process.env;
375
- const dir = stackDirOf(opts.dir, opts.cwd);
376
- const engine = engineOf(dir, opts.engine, env);
377
- const source = pulumiStackVersionSource({ dir, stack: opts.stack, engine, env, ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}) });
378
- const out = resolve(opts.out);
379
- const r = await exportStateVersion({
380
- subject: opts.stack,
381
- by: opts.by,
382
- source,
383
- out,
384
- ...(opts.version ? { version: opts.version } : {}),
385
- words: wordsOf(opts, "stack-export"),
386
- env,
387
- ...gatedSettings(opts),
388
- });
389
- const request = await askedRequest(opts, r.digest, { kind: "stack-export", subject: opts.stack, by: opts.by, fields: { location: r.location, version_id: r.version } });
390
- switch (r.status) {
391
- case "waiting":
392
- return { status: "waiting", digest: r.digest, request, command: r.command };
393
- case "refused":
394
- return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
395
- case "spent":
396
- return { status: "spent", digest: r.digest, request };
397
- case "failed":
398
- return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
399
- case "written":
400
- return {
401
- status: "done",
402
- digest: r.digest,
403
- request,
404
- approvedBy: r.approvedBy,
405
- recorded: r.recorded,
406
- result: { file: r.file, sha256: r.contentDigest.replace(/^sha256:/, ""), bytes: source.read?.bytes ?? 0, resources: source.read?.resources ?? 0, version: r.version },
407
- };
408
- }
409
- }
410
-
411
- // ── cancel ───────────────────────────────────────────────────────────────
412
-
413
- /** The two lock directories of a DIY backend at `root` for a stack: project-scoped first, then the older layout. */
414
- function diyLockDirs(root: string, project: string | undefined, stack: string): string[] {
415
- return [...(project ? [join(root, ".pulumi", "locks", "organization", project, stack)] : []), join(root, ".pulumi", "locks", stack)];
416
- }
417
-
418
- /**
419
- * The lock ids a DIY backend at `root` holds for a stack: the file names
420
- * under `.pulumi/locks/organization/<project>/<stack>/` (project-scoped
421
- * stacks) and `.pulumi/locks/<stack>/` (the older layout), without `.json`.
422
- */
423
- export function diyStackLockIds(root: string, project: string | undefined, stack: string): string[] {
424
- const ids = new Set<string>();
425
- for (const d of diyLockDirs(root, project, stack)) {
426
- if (!existsSync(d)) continue;
427
- for (const f of readdirSync(d)) if (f.endsWith(".json")) ids.add(f.slice(0, -".json".length));
428
- }
429
- return [...ids].sort();
430
- }
431
-
432
- /**
433
- * One DIY lock as core's `LockInfo` (#4808): its id, and from the lock
434
- * file Pulumi writes (`pid`, `username`, `hostname`, `timestamp`) who took
435
- * it and when, so the live-run check knows which runs could hold it.
436
- * Undefined when the stack holds no lock of that id.
437
- */
438
- export function diyStackLock(root: string, project: string | undefined, stack: string, id: string): LockInfo | undefined {
439
- for (const d of diyLockDirs(root, project, stack)) {
440
- const file = join(d, `${id}.json`);
441
- if (!existsSync(file)) continue;
442
- let doc: unknown;
443
- try {
444
- doc = JSON.parse(readFileSync(file, "utf-8"));
445
- } catch {
446
- doc = undefined;
447
- }
448
- const s = (k: string): string | undefined => (isObject(doc) && typeof doc[k] === "string" && doc[k] !== "" ? (doc[k] as string) : undefined);
449
- const who = s("username") && s("hostname") ? `${s("username")}@${s("hostname")}` : s("username");
450
- return { ID: id, ...(who ? { Who: who } : {}), ...(s("timestamp") ? { Created: s("timestamp")! } : {}) };
451
- }
452
- return undefined;
453
- }
454
-
455
- /** A stack's current lock, as {@link pulumiStackLockIds} reads it (#4615). */
456
- export interface PulumiStackLocks {
457
- /** Whether the backend was read: a `file://` backend chant can list. False for Pulumi Cloud, a bucket, or no backend found. */
458
- checked: boolean;
459
- /** The backend URL the stack resolves to, when one was found. */
460
- backend?: string;
461
- /** The lock ids the stack holds now, sorted. Empty when it holds none, or when `checked` is false. */
462
- ids: string[];
463
- }
464
-
465
- /** The DIY root and project of a stack on a `file://` backend, or undefined for any other backend. */
466
- async function diyRootOf(dir: string, env: Record<string, string | undefined>, project?: string): Promise<{ root?: string; project?: string; backend?: string }> {
467
- const backend = pulumiStackBackend(dir, { env });
468
- const m = backend ? /^file:\/\/(.*)$/.exec(backend.url) : null;
469
- if (!m) return backend ? { backend: backend.url } : {};
470
- const root = isAbsolute(m[1]!) ? m[1]! : resolve(dir, m[1]!);
471
- let name = project;
472
- if (!name) {
473
- const { pulumiYamlName } = await import("./lint/post-synth/member-read-helpers");
474
- name = pulumiYamlName(dir);
475
- }
476
- return { root, backend: backend!.url, ...(name ? { project: name } : {}) };
477
- }
478
-
479
- /**
480
- * The lock ids a stack holds now (#4615), for a caller that needs the id
481
- * `gatedStackCancel` asks for: the stack's backend from its directory (the
482
- * environment's `PULUMI_BACKEND_URL`, else `Pulumi.yaml`'s `backend.url`),
483
- * and on a `file://` backend the lock files {@link diyStackLockIds} lists.
484
- * Any other backend answers `checked: false`. A stack on plunge keeps no
485
- * stack lock, so it answers `checked: true` with no ids.
486
- */
487
- export async function pulumiStackLockIds(opts: { dir: string; stack: string; cwd?: string; project?: string; engine?: PulumiMemberEngine; env?: NodeJS.ProcessEnv }): Promise<PulumiStackLocks> {
488
- const env = opts.env ?? process.env;
489
- const dir = stackDirOf(opts.dir, opts.cwd);
490
- if (engineOf(dir, opts.engine, env) === "plunge") return { checked: true, ids: [] };
491
- const at = await diyRootOf(dir, env, opts.project);
492
- if (!at.root) return { checked: false, ...(at.backend ? { backend: at.backend } : {}), ids: [] };
493
- return { checked: true, ...(at.backend ? { backend: at.backend } : {}), ids: diyStackLockIds(at.root, at.project, opts.stack) };
494
- }
495
-
496
- /** Why {@link pulumiStackLockToCancel} names no lock (#4911). */
497
- export type PulumiLockToCancelRefusal = "read-failed" | "not-listed" | "no-lock" | "many-locks";
498
-
499
- /** The lock a cancel releases, or why none can be named without the caller's id. */
500
- export type PulumiLockToCancel =
501
- | { lockId: string; read: boolean }
502
- | { refusal: PulumiLockToCancelRefusal; message: string; backend?: string; ids?: string[] };
503
-
504
- /**
505
- * The lock id a cancel asks to release (#4911): `given` when the caller
506
- * names one, else the one lock {@link pulumiStackLockIds} finds on the
507
- * stack's `file://` backend. No lock, two locks, a backend chant cannot
508
- * list, or a read that failed answers a `refusal` with chant's message; a
509
- * product words it from the code, the `backend` and the `ids`.
510
- */
511
- export async function pulumiStackLockToCancel(given: string | undefined, stack: { dir: string; stack: string; cwd?: string; project?: string; engine?: PulumiMemberEngine; env?: NodeJS.ProcessEnv }): Promise<PulumiLockToCancel> {
512
- if (given) return { lockId: given, read: false };
513
- let locks: PulumiStackLocks;
514
- try {
515
- locks = await pulumiStackLockIds(stack);
516
- } catch (e) {
517
- return { refusal: "read-failed", message: `a cancel names the lock it releases, and reading stack ${stack.stack}'s lock failed: ${(e as Error).message}` };
518
- }
519
- const backend = locks.backend ? { backend: locks.backend } : {};
520
- if (!locks.checked) return { refusal: "not-listed", ...backend, message: `a cancel names the lock it releases here: chant reads a stack's lock from a file:// backend only, and stack ${stack.stack}'s backend is ${locks.backend ?? "none chant can find"}` };
521
- if (locks.ids.length === 0) return { refusal: "no-lock", ...backend, ids: [], message: `stack ${stack.stack} holds no lock now, so there is nothing to cancel` };
522
- if (locks.ids.length > 1) return { refusal: "many-locks", ...backend, ids: locks.ids, message: `stack ${stack.stack} holds ${locks.ids.length} locks (${locks.ids.join(", ")}); name the one to release` };
523
- return { lockId: locks.ids[0]!, read: true };
524
- }
525
-
526
- export interface PulumiStackCancelOptions extends PulumiStackOpCommon {
527
- dir: string;
528
- cwd?: string;
529
- stack: string;
530
- engine?: PulumiMemberEngine;
531
- /** The lock the approver approves releasing. */
532
- lockId: string;
533
- /** The project, for a DIY backend's lock path. Default `Pulumi.yaml`'s `name`. */
534
- project?: string;
535
- /** Reads the stack's current lock id on a backend chant cannot read itself. */
536
- readLockId?: () => Promise<string | undefined>;
537
- /**
538
- * The repository's runs that have not finished (#4808), read before the
539
- * request and again just before the spend: while one that began before
540
- * the lock was taken is alive, nothing is released. A throw refuses the
541
- * release. Default core's `forgeLiveRunsOf` of the forge {@link forge}
542
- * names over the environment (`forgeTargetWith`); with no CI variables
543
- * and no `forge.repo`, the stack directory's origin remote names the
544
- * forge and the repository (#4920).
545
- */
546
- liveRuns?: () => Promise<LiveRun[]>;
547
- /** The forge whose runs are read when no `liveRuns` is given: `--forge`, `--repo` and the rest a product's flags give. */
548
- forge?: ForgeTargetOptions & ForgeOverrides;
549
- commit?: string;
550
- }
551
-
552
- export interface PulumiStackCancelResult {
553
- /** Whether the current lock was read and found to be the approved one before `cancel` ran. */
554
- lockChecked: boolean;
555
- /** How many of the repository's runs were alive at the check, none of them able to hold the lock. */
556
- liveRuns: number;
557
- }
558
-
559
- /**
560
- * Release a stuck lock after an approval of its lock id, while no run that
561
- * may hold it is alive: core's `releaseStateLock` over the stack's lock.
562
- * Refused for plunge, which keeps no stack lock. On a backend chant cannot
563
- * list and with no `readLockId`, the lock is the one the caller names and
564
- * `lockChecked` is false.
565
- */
566
- export async function gatedStackCancel(opts: PulumiStackCancelOptions): Promise<PulumiStackOpOutcome<PulumiStackCancelResult>> {
567
- const env = opts.env ?? process.env;
568
- const dir = stackDirOf(opts.dir, opts.cwd);
569
- const engine = engineOf(dir, opts.engine, env);
570
- if (engine === "plunge") 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`);
571
- if (!opts.lockId || opts.lockId.startsWith("-")) throw new Error("a cancel names the lock id it releases");
572
-
573
- const at: { root?: string; project?: string; backend?: string } = opts.readLockId ? {} : await diyRootOf(dir, env, opts.project);
574
- const checked = opts.readLockId !== undefined || at.root !== undefined;
575
- const heldIds = async (): Promise<string[]> => {
576
- if (opts.readLockId) {
577
- const id = await opts.readLockId();
578
- return id ? [id] : [];
579
- }
580
- return at.root ? diyStackLockIds(at.root, at.project, opts.stack) : [];
581
- };
582
- if (checked) {
583
- const ids = await heldIds();
584
- if (!ids.includes(opts.lockId)) {
585
- throw new PulumiStackOpRefused(
586
- "lock-gone",
587
- `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`,
588
- );
589
- }
590
- }
591
- const location = at.root ? `${at.backend} lock of stack ${opts.stack}` : stackLocation(dir, opts.stack, env);
592
- let released = false;
593
- const lock: StateLockSource = {
594
- location,
595
- async read() {
596
- // A backend chant cannot list holds the lock the caller names until the release ran.
597
- if (!checked) return released ? undefined : { ID: opts.lockId };
598
- if (!(await heldIds()).includes(opts.lockId)) return undefined;
599
- return (at.root ? diyStackLock(at.root, at.project, opts.stack, opts.lockId) : undefined) ?? { ID: opts.lockId };
600
- },
601
- async release() {
602
- const args = pulumiCancelArgs({ stack: opts.stack });
603
- try {
604
- await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
605
- } catch (err) {
606
- throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
607
- }
608
- released = true;
609
- },
610
- };
611
- const r = await releaseStateLock({
612
- subject: opts.stack,
613
- by: opts.by,
614
- lock,
615
- // #4911, #4920: core's reader of the forge's runs, the origin remote naming the forge on a laptop.
616
- liveRuns: opts.liveRuns ?? forgeLiveRunsOf(env, opts.forge ?? {}, { cwd: dir }),
617
- words: wordsOf(opts, "stack-cancel"),
618
- ...(opts.commit ? { commit: opts.commit } : {}),
619
- ...gatedSettings(opts),
620
- });
621
- const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-cancel", subject: opts.stack, by: opts.by, fields: { location, id: opts.lockId } });
622
- switch (r.status) {
623
- case "free":
624
- 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`);
625
- case "alive":
626
- 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 });
627
- case "held":
628
- throw new PulumiStackOpRefused("held", `${r.reason}; the approval stands unspent, so run the cancel again once that run finished`, { digest: r.digest });
629
- case "waiting":
630
- return { status: "waiting", digest: r.digest, request, command: r.command };
631
- case "refused":
632
- return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
633
- case "spent":
634
- return { status: "spent", digest: r.digest, request };
635
- case "failed":
636
- return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
637
- case "released":
638
- return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { lockChecked: checked, liveRuns: r.liveRuns } };
639
- }
640
- }
641
-
642
- // ── move ─────────────────────────────────────────────────────────────────
643
-
644
- /** One side of a move. */
645
- export interface PulumiMoveStack {
646
- /** The member's name, for messages and the record. */
647
- member: string;
648
- /** The stack's directory, where `Pulumi.yaml` is. */
649
- dir: string;
650
- /** The stack, as `--source` or `--dest` takes it (`<org>/<project>/<stack>` across projects). */
651
- stack: string;
652
- /**
653
- * The stack's project (#4911). Given on both sides with a bare `stack`,
654
- * the move names the destination as `--dest` takes it itself
655
- * ({@link pulumiMoveDestStack}).
656
- */
657
- project?: string;
658
- }
659
-
660
- /**
661
- * The destination as `pulumi state move --dest` takes it (#4911): the bare
662
- * stack in the source's project, else `<org>/<project>/<stack>`. A DIY
663
- * backend's organization is always `organization`; on Pulumi Cloud (no
664
- * backend, or an http(s) one) it is `org` when given. A stack already
665
- * qualified is kept.
666
- */
667
- export function pulumiMoveDestStack(source: { project: string }, dest: { project: string; stack: string; backend?: string }, opts: { org?: string } = {}): string {
668
- if (dest.stack.includes("/") || dest.project === source.project) return dest.stack;
669
- const cloud = !dest.backend || /^https?:\/\//.test(dest.backend);
670
- return `${(cloud ? opts.org : undefined) ?? "organization"}/${dest.project}/${dest.stack}`;
671
- }
672
-
673
- export interface PulumiStackMoveOptions extends PulumiStackOpCommon {
674
- source: PulumiMoveStack;
675
- dest: PulumiMoveStack;
676
- /** The source URNs to move. */
677
- urns: string[];
678
- cwd?: string;
679
- engine?: PulumiMemberEngine;
680
- runId?: string;
681
- commit?: string;
682
- /** The Pulumi Cloud organization a destination in another project is named under ({@link pulumiMoveDestStack}). */
683
- org?: string;
684
- }
685
-
686
- export interface PulumiStackMoveResult {
687
- engine: PulumiMemberEngine;
688
- moved: string[];
689
- /** What the move printed: plunge's outcome document, parsed, on plunge. */
690
- outcome?: unknown;
691
- }
692
-
693
- /** The entries of a preview that change anything. */
694
- function changing(part: ChangeSetPart): { address: string; type: string; action: string }[] {
695
- return part.entries.filter((e) => e.mayAppear === true || ["create", "update", "replace", "delete", "forget"].includes(e.action)).map((e) => ({ address: e.address, type: e.type, action: e.mayAppear ? "may-appear" : e.action }));
696
- }
697
-
698
- /**
699
- * What stands between the two previews and "no change once the move is
700
- * made": each changing entry that is not a moved resource's delete in the
701
- * source or its create, by type and name, in the destination. Empty when the
702
- * move leaves both previewing no change.
703
- */
704
- export function moveLeftovers(urns: readonly string[], source: ChangeSetPart, dest: ChangeSetPart): string[] {
705
- const keys = new Set(urns.map((u) => pulumiNodeKey(u) ?? u));
706
- const out: string[] = [];
707
- const sourceDeletes = new Set<string>();
708
- for (const e of changing(source)) {
709
- const key = pulumiNodeKey(e.address) ?? e.address;
710
- if (e.action === "delete" && urns.includes(e.address)) sourceDeletes.add(key);
711
- else out.push(`${source.member.member}: ${e.action} ${e.address}`);
712
- }
713
- const destCreates = new Set<string>();
714
- for (const e of changing(dest)) {
715
- const key = pulumiNodeKey(e.address) ?? e.address;
716
- if (e.action === "create" && keys.has(key)) destCreates.add(key);
717
- else out.push(`${dest.member.member}: ${e.action} ${e.address}`);
718
- }
719
- for (const k of keys) {
720
- if (!sourceDeletes.has(k)) out.push(`${source.member.member}: its preview does not delete ${k}, so its program still declares it`);
721
- if (!destCreates.has(k)) out.push(`${dest.member.member}: its preview does not create ${k}, so its program does not declare it yet`);
722
- }
723
- return out;
724
- }
725
-
726
- /** plunge's move document's status and refusals, when it printed one. */
727
- function moveView(text: string | undefined): { status: string; refusals: { urn?: string; reason: string }[]; error?: string; doc: unknown } | undefined {
728
- if (!text) return undefined;
729
- try {
730
- const doc = JSON.parse(text) as unknown;
731
- if (!isObject(doc) || typeof doc.status !== "string") return undefined;
732
- const refusals = (Array.isArray(doc.refusals) ? doc.refusals : []).filter(isObject).map((r) => ({ ...(typeof r.urn === "string" ? { urn: r.urn } : {}), reason: typeof r.reason === "string" ? r.reason : "" }));
733
- return { status: doc.status, refusals, ...(typeof doc.error === "string" ? { error: doc.error } : {}), doc };
734
- } catch {
735
- return undefined;
736
- }
737
- }
738
-
739
- /**
740
- * Move resources between two stacks after an approval: core's
741
- * `runStateMigration` (#4808) with the two stacks as its roots. Each call
742
- * plans: both previews, plunge's plan on plunge, and each stack's export
743
- * digest as its state before. The request binds that plan. Approved, the
744
- * engine reads each export again and refuses a state that moved, runs
745
- * `pulumi state move` (plunge's marker move on plunge), and previews both
746
- * stacks again. A Pulumi move's new states are the engine's to write, so
747
- * each root's `after` digest binds what the move does to it (the stacks and
748
- * the URNs), not bytes. Pulumi takes each stack's lock inside the move
749
- * itself; chant takes none, and refuses while a `file://` backend shows
750
- * either stack locked. Refused before anything is asked for an empty or
751
- * non-URN list, two engines, or a plan that changes more than the move.
752
- */
753
- export async function gatedStackMove(opts: PulumiStackMoveOptions): Promise<PulumiStackOpOutcome<PulumiStackMoveResult>> {
754
- const env = opts.env ?? process.env;
755
- if (opts.urns.length === 0 || !opts.urns.every((u) => u.startsWith("urn:pulumi:"))) throw new Error("a move names the source URNs it moves, each urn:pulumi:...");
756
- if (opts.source.member === opts.dest.member) throw new Error(`a move is between two members, and both sides are ${opts.source.member}`);
757
- const sourceDir = stackDirOf(opts.source.dir, opts.cwd);
758
- const destDir = stackDirOf(opts.dest.dir, opts.cwd);
759
- const engine = engineOf(sourceDir, opts.engine, env);
760
- const destEngine = engineOf(destDir, opts.engine, env);
761
- if (engine !== destEngine) throw new Error(`${opts.source.member} runs on ${engine} and ${opts.dest.member} on ${destEngine}; a move needs both stacks on one engine`);
762
- const urns = [...new Set(opts.urns)].sort();
763
- const runners = { ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}), engine };
764
- // #4911: with both projects, the destination's --dest name is the lexicon's to decide.
765
- const destBackend = opts.source.project && opts.dest.project ? pulumiStackBackend(destDir, { env })?.url : undefined;
766
- const destStack =
767
- opts.source.project && opts.dest.project
768
- ? pulumiMoveDestStack({ project: opts.source.project }, { project: opts.dest.project, stack: opts.dest.stack, ...(destBackend ? { backend: destBackend } : {}) }, opts.org ? { org: opts.org } : {})
769
- : opts.dest.stack;
770
- const sides = [
771
- { ...opts.source, dir: sourceDir },
772
- { ...opts.dest, stack: destStack, dir: destDir },
773
- ];
774
- const side = (member: string) => sides.find((s) => s.member === member)!;
775
-
776
- const previews = async (): Promise<{ source: ChangeSetPart; dest: ChangeSetPart }> => {
777
- const [s, d] = await Promise.all(sides.map((x) => previewPulumiMemberRead({ member: x.member, dir: x.dir, stack: x.stack, ...runners })));
778
- for (const p of [s!.part, d!.part]) {
779
- if (p.member.status === "failed") throw new Error(`the preview of ${p.member.member} failed: ${p.member.error ?? "no error printed"}`);
780
- }
781
- return { source: s!.part, dest: d!.part };
782
- };
783
-
784
- // The plan: previews that change only the moved resources, plunge's own plan, each state's digest now.
785
- const before = await previews();
786
- const left = moveLeftovers(urns, before.source, before.dest);
787
- if (left.length > 0) 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("; ")}`);
788
- if (engine === "plunge") {
789
- const args = plungeMoveArgs({ source: opts.source.stack, dest: destStack, urns });
790
- let view: ReturnType<typeof moveView>;
791
- try {
792
- view = moveView((await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir)).stdout);
793
- } catch (err) {
794
- view = moveView(pulumiRunFailure(err).stdout);
795
- if (!view) throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
796
- }
797
- if (!view || view.status !== "planned") {
798
- const reasons = view?.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
799
- throw new Error(`refusing to move: plunge's plan is ${view?.status ?? "missing"}${reasons ? `: ${reasons}` : ""}`);
800
- }
801
- }
802
- const digestOf = async (member: string): Promise<string> => sha256(await exportNow({ ...side(member), ...runners }));
803
- const move = { source: opts.source.stack, dest: destStack, urns };
804
- const proof: MigrationCheck = { changes: [], summary: `the previews change only the ${urns.length} moved resource(s)` };
805
- const roots: MigrationRootPlan[] = [];
806
- for (const s of sides) {
807
- 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 });
808
- }
809
-
810
- let outcome: unknown;
811
- const migration: StateMigrationEngine = {
812
- async lock() {
813
- for (const s of sides) {
814
- const locks = engine === "plunge" ? { checked: false, ids: [] } : await pulumiStackLockIds({ dir: s.dir, stack: s.stack.split("/").at(-1)!, engine, env });
815
- if (locks.ids.length > 0) throw new Error(`${s.member} holds lock ${locks.ids.join(", ")}: an update is running on it, so nothing was moved`);
816
- }
817
- return async () => undefined;
818
- },
819
- async current(root) {
820
- return { digest: await digestOf(root) };
821
- },
822
- async write() {
823
- if (engine === "plunge") {
824
- const args = plungeMoveArgs({ ...move, yes: true });
825
- try {
826
- const { stdout } = await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir);
827
- outcome = moveView(stdout)?.doc;
828
- } catch (err) {
829
- const view = moveView(pulumiRunFailure(err).stdout);
830
- if (view) {
831
- const reasons = view.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
832
- throw new Error(`plunge stack move ${view.status}: ${reasons || view.error || "no reason printed"}${view.status === "interrupted" ? "; run the move again to finish it" : ""}`);
833
- }
834
- throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
835
- }
836
- return;
837
- }
838
- const args = pulumiStateMoveArgs(move);
839
- try {
840
- await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, sourceDir);
841
- } catch (err) {
842
- throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
843
- }
844
- },
845
- async verify(root) {
846
- const s = side(root);
847
- const { part } = await previewPulumiMemberRead({ member: s.member, dir: s.dir, stack: s.stack, ...runners });
848
- if (part.member.status === "failed") return { changes: [`the preview failed: ${part.member.error ?? "no error printed"}`], summary: "preview failed" };
849
- const changes = changing(part).map((e) => `${e.action} ${e.address}`);
850
- return { changes, summary: changes.length === 0 ? "no change" : `${changes.length} change(s)` };
851
- },
852
- };
853
-
854
- const subject = `move:${opts.source.stack}:${destStack}`;
855
- const fields = { source: opts.source.stack, dest: destStack, engine, urns: urns.join(",") };
856
- const r = await runStateMigration({
857
- name: subject,
858
- by: opts.by,
859
- roots,
860
- engine: migration,
861
- words: wordsOf(opts, "stack-move"),
862
- fields,
863
- detail: (res) => ({ urns: urns.length, engine, afterNoChange: res.status === "applied" }),
864
- description: `move of ${urns.length} resource(s) from ${opts.source.stack} to ${destStack}`,
865
- ...(opts.runId ? { runId: opts.runId } : {}),
866
- ...(opts.commit ? { commit: opts.commit } : {}),
867
- ...gatedSettings(opts),
868
- });
869
- const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-move", subject, by: opts.by, fields });
870
- switch (r.status) {
871
- case "proof-failed":
872
- throw new Error(`refusing to move: ${r.failing.join(", ")} plan changes`);
873
- case "waiting":
874
- return { status: "waiting", digest: r.digest, request, command: r.command };
875
- case "refused":
876
- return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
877
- case "spent":
878
- return { status: "spent", digest: r.digest, request };
879
- case "approval-moved":
880
- // An approval of an earlier request for these stacks stands, but their state moved since it (#4806), so it
881
- // doesn't count for this one, and this request waits for its own.
882
- return { status: "waiting", digest: r.digest, request, command: r.command };
883
- case "moved":
884
- return {
885
- status: "failed",
886
- digest: r.digest,
887
- request,
888
- check: "moved",
889
- recorded: r.recorded,
890
- 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`,
891
- };
892
- case "failed": {
893
- const still = (r.result?.roots ?? []).flatMap((x) => (x.verify?.changes ?? []).map((c) => `${x.root}: ${c}`));
894
- 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 };
895
- }
896
- case "applied":
897
- return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { engine, moved: urns, ...(outcome !== undefined ? { outcome } : {}) } };
898
- }
899
- }
900
-
901
- // ── action ───────────────────────────────────────────────────────────────
902
-
903
- /** Why a stack action was refused before anything was asked (#4654). */
904
- export type PulumiStackActionRefusal = "action-urn" | "action-type" | "action-scope";
905
-
906
- /** A stack action refused before its request: `code` says why, `urns` names what the preview changed besides the action, for `action-scope`. */
907
- export class PulumiStackActionRefused extends Error {
908
- readonly code: PulumiStackActionRefusal;
909
- readonly urns: string[];
910
- constructor(code: PulumiStackActionRefusal, message: string, urns: string[] = []) {
911
- super(`${code}: ${message}`);
912
- this.name = "PulumiStackActionRefused";
913
- this.code = code;
914
- this.urns = urns;
915
- }
916
- }
917
-
918
- /** The resource types an action may name: the command provider's (`command:local:Command`, `command:remote:Command`). */
919
- export const PULUMI_ACTION_TYPE_PREFIX = "command:";
920
-
921
- /** An action's name as a caller's config gives it, for the request's subject. */
922
- const ACTION_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$/;
923
-
924
- /** The subject an action's request is asked and approved under: `action:<stack>:<name>`, or the URN in place of a name. */
925
- export const stackActionSubject = (stack: string, nameOrUrn: string): string => `action:${stack}:${nameOrUrn}`;
926
-
927
- export interface PulumiStackActionOptions extends PulumiStackOpCommon {
928
- /** The stack's directory, where `Pulumi.yaml` is. */
929
- dir: string;
930
- cwd?: string;
931
- /** The stack, as `--stack` takes it. */
932
- stack: string;
933
- engine?: PulumiMemberEngine;
934
- /** The `command:` resource whose replacement is the action. */
935
- urn: string;
936
- /** The action's name in the caller's config, which the subject carries in place of the URN. */
937
- name?: string;
938
- /** Ask anew even when the same request applied already. Absent, such a call answers `spent`, so a retried job never runs the action twice. */
939
- anew?: boolean;
940
- }
941
-
942
- export interface PulumiStackActionResult {
943
- urn: string;
944
- engine: PulumiMemberEngine;
945
- /** The preview's digest the request bound. */
946
- preview: string;
947
- /** The update's exit code: 0, since a failed update ends `failed`. */
948
- exit: number;
949
- /** The update's last lines of output. */
950
- tail: string;
951
- }
952
-
953
- /** The last `n` lines of `text`, trimmed. */
954
- const lastLines = (text: string | undefined, n: number): string =>
955
- (text ?? "").trim().split("\n").slice(-n).join("\n");
956
-
957
- /**
958
- * Check an action's URN before anything runs: a Pulumi URN on `stack` whose
959
- * type is a command provider's. Throws {@link PulumiStackActionRefused}.
960
- */
961
- export function checkStackActionUrn(stack: string, urn: string): void {
962
- const parsed = parsePulumiUrn(urn);
963
- if (!parsed) throw new PulumiStackActionRefused("action-urn", `${JSON.stringify(urn)} is not a resource URN (urn:pulumi:<stack>::<project>::<type>::<name>)`);
964
- const stackName = stack.split("/").at(-1);
965
- if (parsed.stack !== stackName) throw new PulumiStackActionRefused("action-urn", `${urn} names stack ${parsed.stack}, and the action runs on ${stack}`);
966
- if (!parsed.type.startsWith(PULUMI_ACTION_TYPE_PREFIX)) {
967
- throw new PulumiStackActionRefused(
968
- "action-type",
969
- `${urn} is a ${parsed.type}, and an action is a command resource (command:local:Command or command:remote:Command), whose replacement runs it; replacing any other resource is an update`,
970
- );
971
- }
972
- }
973
-
974
- /**
975
- * What a preview changes besides the action's replacement (#4654): each URN
976
- * with a changing step other than `urn`, and `urn` itself when it changes
977
- * other than by replacement or is not replaced at all. Empty when the
978
- * preview replaces `urn` and nothing else.
979
- */
980
- export function stackActionScope(urn: string, preview: unknown): { others: string[]; problem?: string } {
981
- const steps = pulumiSteps(preview) ?? [];
982
- const others = new Set<string>();
983
- let replaced = false;
984
- let problem: string | undefined;
985
- for (const s of steps) {
986
- const op = s.op ?? "";
987
- if (PULUMI_UNCHANGED_OPS.has(op)) continue;
988
- if (s.urn !== urn) {
989
- others.add(s.urn!);
990
- continue;
991
- }
992
- if (op === "replace" || op === "create-replacement" || op === "delete-replaced") replaced = true;
993
- else problem = `the preview shows ${op} of ${urn}, not its replacement`;
994
- }
995
- if (!problem && !replaced) problem = `the preview does not replace ${urn}`;
996
- return { others: [...others].sort(), ...(problem ? { problem } : {}) };
997
- }
998
-
999
- /**
1000
- * A day-2 action on a stack (#4654): the replacement of one `command:`
1001
- * resource, previewed, asked for under a gated request, and run once a
1002
- * second identity approves. Refused before anything runs for a URN that is
1003
- * not a command resource's (`action-type`), and before anything is asked for
1004
- * a preview that changes more than that replacement (`action-scope`).
1005
- */
1006
- export async function gatedStackAction(opts: PulumiStackActionOptions): Promise<PulumiStackOpOutcome<PulumiStackActionResult>> {
1007
- checkStackActionUrn(opts.stack, opts.urn);
1008
- if (opts.name !== undefined && !ACTION_NAME.test(opts.name)) throw new Error(`an action's name is letters, digits, "_", "." and "-", not ${JSON.stringify(opts.name)}`);
1009
- const env = opts.env ?? process.env;
1010
- const dir = stackDirOf(opts.dir, opts.cwd);
1011
- const engine = engineOf(dir, opts.engine, env);
1012
- const target = { stack: opts.stack, urn: opts.urn };
1013
-
1014
- const previewArgs = pulumiActionPreviewArgs(target);
1015
- let stdout: string;
1016
- try {
1017
- ({ stdout } = engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, previewArgs, dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, previewArgs, dir));
1018
- } catch (err) {
1019
- throw new Error(`${engine} ${previewArgs.join(" ")} failed: ${why(err, engine)}`);
1020
- }
1021
- let preview: unknown;
1022
- try {
1023
- preview = JSON.parse(stdout);
1024
- } catch {
1025
- throw new Error(`${engine} ${previewArgs.join(" ")} printed no JSON`);
1026
- }
1027
- const scope = stackActionScope(opts.urn, preview);
1028
- if (scope.others.length > 0) {
1029
- throw new PulumiStackActionRefused(
1030
- "action-scope",
1031
- `the preview of ${opts.stack} replacing ${opts.urn} also changes ${scope.others.join(", ")}, and an action replaces its command resource alone; nothing was asked for`,
1032
- scope.others,
1033
- );
1034
- }
1035
- if (scope.problem) throw new PulumiStackActionRefused("action-scope", `${scope.problem}; nothing was asked for`);
1036
-
1037
- const digest = pulumiPreviewDigest(preview, { changedOnly: true });
1038
- const subject = stackActionSubject(opts.stack, opts.name ?? opts.urn);
1039
- const fields: Record<string, string> = { stack: opts.stack, urn: opts.urn, engine, preview: digest, ...(opts.name ? { name: opts.name } : {}) };
1040
- // core's gatedOp (#4808); reuseApplied makes a retried call with the same request answer `spent`.
1041
- const r = await gatedOp<{ result: PulumiStackActionResult; error?: string }>(
1042
- {
1043
- op: opts.op ?? PULUMI_STACK_OPS_OP,
1044
- request: { kind: "stack-action", subject, by: opts.by, fields },
1045
- description: `action ${opts.name ?? opts.urn} on stack ${opts.stack}: replace ${opts.urn}, requested by ${opts.by}`,
1046
- ...(opts.anew ? {} : { reuseApplied: true }),
1047
- ...gatedSettings(opts),
1048
- },
1049
- (async () => {
1050
- const args = pulumiActionUpArgs(target);
1051
- try {
1052
- const done = engine === "plunge" ? await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, dir) : await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
1053
- const tail = lastLines(done.stdout, 10);
1054
- return { output: { result: { urn: opts.urn, engine, preview: digest, exit: 0, tail } }, detail: { result: "ok", exit: 0, tail: tail.slice(-400), urn: opts.urn } };
1055
- } catch (err) {
1056
- const f = pulumiRunFailure(err);
1057
- const exit = f.exitCode ?? 1;
1058
- const tail = lastLines(`${f.stdout ?? ""}\n${f.stderr ?? ""}`, 10);
1059
- const error = `${engine} ${args.join(" ")} failed: ${why(err, engine)}`;
1060
- 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 };
1061
- }
1062
- }) as GatedOpAct<{ result: PulumiStackActionResult; error?: string }>,
1063
- );
1064
- const approve = stackOpApproveCommand(opts);
1065
- const command = (fallback: string): string => (approve ? approve(subject, r.digest) : fallback);
1066
- switch (r.status) {
1067
- case "waiting":
1068
- return { status: "waiting", digest: r.digest, request: r.request, command: command(r.command) };
1069
- case "refused":
1070
- return { status: "refused", digest: r.digest, request: r.request, by: r.by, reason: r.reason, command: command(r.command) };
1071
- case "spent":
1072
- return { status: "spent", digest: r.digest, request: r.request };
1073
- case "held":
1074
- return { status: "failed", digest: r.digest, request: r.request, error: r.reason, recorded: false };
1075
- case "failed":
1076
- return { status: "failed", digest: r.digest, request: r.request, error: r.error.message, recorded: r.recorded };
1077
- case "done":
1078
- return r.output.error !== undefined
1079
- ? { status: "failed", digest: r.digest, request: r.request, error: r.output.error, recorded: r.recorded }
1080
- : { status: "done", digest: r.digest, request: r.request, result: r.output.result, approvedBy: r.approvedBy, recorded: r.recorded };
1081
- }
1082
- }