@reventlessdev/reventless-seed-aws 1.0.0-alpha.2 → 1.0.0-alpha.21

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 (111) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/.sourcedirs.json +1 -0
  4. package/lib/bs/compiler-info.json +2 -2
  5. package/lib/bs/src/ReventlessSeedAws.ast +0 -0
  6. package/lib/bs/src/ReventlessSeedAws.cmi +0 -0
  7. package/lib/bs/src/ReventlessSeedAws.cmj +0 -0
  8. package/lib/bs/src/ReventlessSeedAws.cmt +0 -0
  9. package/lib/bs/src/ReventlessSeedAws.res +87 -75
  10. package/lib/bs/src/ReventlessSeedAws.res.mjs +34 -30
  11. package/lib/bs/src/ReventlessSeedAws_Quiesce.ast +0 -0
  12. package/lib/bs/src/ReventlessSeedAws_Quiesce.cmi +0 -0
  13. package/lib/bs/src/ReventlessSeedAws_Quiesce.cmj +0 -0
  14. package/lib/bs/src/ReventlessSeedAws_Quiesce.cmt +0 -0
  15. package/lib/bs/src/ReventlessSeedAws_Quiesce.res +287 -0
  16. package/lib/bs/src/ReventlessSeedAws_Quiesce.res.mjs +205 -0
  17. package/lib/bs/src/ReventlessSeedAws_Reconcile.ast +0 -0
  18. package/lib/bs/src/ReventlessSeedAws_Reconcile.cmi +0 -0
  19. package/lib/bs/src/ReventlessSeedAws_Reconcile.cmj +0 -0
  20. package/lib/bs/src/ReventlessSeedAws_Reconcile.cmt +0 -0
  21. package/lib/bs/src/ReventlessSeedAws_Reconcile.res +385 -0
  22. package/lib/bs/src/ReventlessSeedAws_Reconcile.res.mjs +318 -0
  23. package/lib/bs/src/ReventlessSeedAws_Reset.ast +0 -0
  24. package/lib/bs/src/ReventlessSeedAws_Reset.cmi +0 -0
  25. package/lib/bs/src/ReventlessSeedAws_Reset.cmj +0 -0
  26. package/lib/bs/src/ReventlessSeedAws_Reset.cmt +0 -0
  27. package/lib/bs/src/ReventlessSeedAws_Reset.res +1098 -0
  28. package/lib/bs/src/ReventlessSeedAws_Reset.res.mjs +991 -0
  29. package/lib/bs/tests/EndpointResolutionTest.ast +0 -0
  30. package/lib/bs/tests/EndpointResolutionTest.cmi +0 -0
  31. package/lib/bs/tests/EndpointResolutionTest.cmj +0 -0
  32. package/lib/bs/tests/EndpointResolutionTest.cmt +0 -0
  33. package/lib/bs/tests/EndpointResolutionTest.res +83 -0
  34. package/lib/bs/tests/EndpointResolutionTest.res.mjs +115 -0
  35. package/lib/bs/tests/ObjectStoreReconcileTest.ast +0 -0
  36. package/lib/bs/tests/ObjectStoreReconcileTest.cmi +0 -0
  37. package/lib/bs/tests/ObjectStoreReconcileTest.cmj +0 -0
  38. package/lib/bs/tests/ObjectStoreReconcileTest.cmt +0 -0
  39. package/lib/bs/tests/ObjectStoreReconcileTest.res +84 -0
  40. package/lib/bs/tests/ObjectStoreReconcileTest.res.mjs +102 -0
  41. package/lib/bs/tests/ObjectStoreResetTest.ast +0 -0
  42. package/lib/bs/tests/ObjectStoreResetTest.cmi +0 -0
  43. package/lib/bs/tests/ObjectStoreResetTest.cmj +0 -0
  44. package/lib/bs/tests/ObjectStoreResetTest.cmt +0 -0
  45. package/lib/bs/tests/ObjectStoreResetTest.res +170 -0
  46. package/lib/bs/tests/ObjectStoreResetTest.res.mjs +211 -0
  47. package/lib/bs/tests/QuiesceResetTest.ast +0 -0
  48. package/lib/bs/tests/QuiesceResetTest.cmi +0 -0
  49. package/lib/bs/tests/QuiesceResetTest.cmj +0 -0
  50. package/lib/bs/tests/QuiesceResetTest.cmt +0 -0
  51. package/lib/bs/tests/QuiesceResetTest.res +133 -0
  52. package/lib/bs/tests/QuiesceResetTest.res.mjs +141 -0
  53. package/lib/ocaml/.compiler.log +2 -2
  54. package/lib/ocaml/EndpointResolutionTest.ast +0 -0
  55. package/lib/ocaml/EndpointResolutionTest.cmi +0 -0
  56. package/lib/ocaml/EndpointResolutionTest.cmj +0 -0
  57. package/lib/ocaml/EndpointResolutionTest.cmt +0 -0
  58. package/lib/ocaml/EndpointResolutionTest.res +83 -0
  59. package/lib/ocaml/ObjectStoreReconcileTest.ast +0 -0
  60. package/lib/ocaml/ObjectStoreReconcileTest.cmi +0 -0
  61. package/lib/ocaml/ObjectStoreReconcileTest.cmj +0 -0
  62. package/lib/ocaml/ObjectStoreReconcileTest.cmt +0 -0
  63. package/lib/ocaml/ObjectStoreReconcileTest.res +84 -0
  64. package/lib/ocaml/ObjectStoreResetTest.ast +0 -0
  65. package/lib/ocaml/ObjectStoreResetTest.cmi +0 -0
  66. package/lib/ocaml/ObjectStoreResetTest.cmj +0 -0
  67. package/lib/ocaml/ObjectStoreResetTest.cmt +0 -0
  68. package/lib/ocaml/ObjectStoreResetTest.res +170 -0
  69. package/lib/ocaml/QuiesceResetTest.ast +0 -0
  70. package/lib/ocaml/QuiesceResetTest.cmi +0 -0
  71. package/lib/ocaml/QuiesceResetTest.cmj +0 -0
  72. package/lib/ocaml/QuiesceResetTest.cmt +0 -0
  73. package/lib/ocaml/QuiesceResetTest.res +133 -0
  74. package/lib/ocaml/ReventlessSeedAws.ast +0 -0
  75. package/lib/ocaml/ReventlessSeedAws.cmi +0 -0
  76. package/lib/ocaml/ReventlessSeedAws.cmj +0 -0
  77. package/lib/ocaml/ReventlessSeedAws.cmt +0 -0
  78. package/lib/ocaml/ReventlessSeedAws.res +87 -75
  79. package/lib/ocaml/ReventlessSeedAws_Quiesce.ast +0 -0
  80. package/lib/ocaml/ReventlessSeedAws_Quiesce.cmi +0 -0
  81. package/lib/ocaml/ReventlessSeedAws_Quiesce.cmj +0 -0
  82. package/lib/ocaml/ReventlessSeedAws_Quiesce.cmt +0 -0
  83. package/lib/ocaml/ReventlessSeedAws_Quiesce.res +287 -0
  84. package/lib/ocaml/ReventlessSeedAws_Reconcile.ast +0 -0
  85. package/lib/ocaml/ReventlessSeedAws_Reconcile.cmi +0 -0
  86. package/lib/ocaml/ReventlessSeedAws_Reconcile.cmj +0 -0
  87. package/lib/ocaml/ReventlessSeedAws_Reconcile.cmt +0 -0
  88. package/lib/ocaml/ReventlessSeedAws_Reconcile.res +385 -0
  89. package/lib/ocaml/ReventlessSeedAws_Reset.ast +0 -0
  90. package/lib/ocaml/ReventlessSeedAws_Reset.cmi +0 -0
  91. package/lib/ocaml/ReventlessSeedAws_Reset.cmj +0 -0
  92. package/lib/ocaml/ReventlessSeedAws_Reset.cmt +0 -0
  93. package/lib/ocaml/ReventlessSeedAws_Reset.res +1098 -0
  94. package/package.json +7 -4
  95. package/rescript.json +9 -1
  96. package/src/ReventlessSeedAws.res +87 -75
  97. package/src/ReventlessSeedAws.res.mjs +34 -30
  98. package/src/ReventlessSeedAws_Quiesce.res +287 -0
  99. package/src/ReventlessSeedAws_Quiesce.res.mjs +205 -0
  100. package/src/ReventlessSeedAws_Reconcile.res +385 -0
  101. package/src/ReventlessSeedAws_Reconcile.res.mjs +318 -0
  102. package/src/ReventlessSeedAws_Reset.res +1098 -0
  103. package/src/ReventlessSeedAws_Reset.res.mjs +991 -0
  104. package/tests/EndpointResolutionTest.res +83 -0
  105. package/tests/EndpointResolutionTest.res.mjs +115 -0
  106. package/tests/ObjectStoreReconcileTest.res +84 -0
  107. package/tests/ObjectStoreReconcileTest.res.mjs +102 -0
  108. package/tests/ObjectStoreResetTest.res +170 -0
  109. package/tests/ObjectStoreResetTest.res.mjs +211 -0
  110. package/tests/QuiesceResetTest.res +133 -0
  111. package/tests/QuiesceResetTest.res.mjs +141 -0
@@ -0,0 +1,1098 @@
1
+ // AWS "reset" for the seed harness: truncate a deployed stack's durable stores
2
+ // — every DynamoDB table (EventLog, DcbEventLog, QueryDb) and every S3 bucket
3
+ // (tasks, served images) the framework created for the stack — leaving the
4
+ // infrastructure in place so the stack reads empty and is re-seedable. It is the
5
+ // exact inverse of seeding: `Seed.Runner.assertStoreEmpty` refuses to seed a
6
+ // non-empty store; this makes a non-empty store empty again.
7
+ //
8
+ // A wipe is irreversible, so every step is fail-closed and production must be
9
+ // unreachable at several at once (the separate-AWS-account guarantee is the one
10
+ // deferred layer — see docs/plans/done/seed-reset-and-fresh-store-guard.md):
11
+ //
12
+ // 1. name allowlist — the stack name must match ^(alpha|dev|pr-.+)$
13
+ // 2. wipeable flag — the target's own `Pulumi.<stack>.yaml` must declare
14
+ // `reventless:wipeable: true` (read via `pulumi config`)
15
+ // 3. tag-scoped discovery — targets are found ONLY through the framework's
16
+ // `reventless:platform=<project>` + `environment=<stack>`
17
+ // tags (Resource Groups Tagging API). Scoping on BOTH
18
+ // matters: `environment` is the stack NAME alone, so two
19
+ // projects sharing a stack name (e.g. `alpha`) in one
20
+ // account collide on it; `platform` (the Pulumi project)
21
+ // keeps a wipe inside the one project. No name globbing.
22
+ // 4. per-resource tag re-check — every discovered resource is re-verified to
23
+ // carry both tags before a single delete is issued
24
+ // 5. dry-run default + typed confirm — lists what it would empty and stops.
25
+ // Interactively, re-typing the exact stack name confirms
26
+ // a real wipe (no env var). Without a TTY (CI),
27
+ // REVENTLESS_WIPE_CONFIRM=<stack> is the equivalent.
28
+ //
29
+ // Gates 1 and 2 are AND-ed: a stray `wipeable: true` on an unlisted name is
30
+ // still refused, and a listed name without the flag is still refused. Production
31
+ // stacks satisfy neither.
32
+ //
33
+ // A deployment is usually several Pulumi projects sharing a stack name — the
34
+ // platform project plus one per domain plugin, each its own `reventless:platform`.
35
+ // The caller passes those projects as `targets`; the operator picks a scope
36
+ // (`domain` = all plugins, a single plugin, `platform`, or `everything`), and
37
+ // gate 2 + discovery run per selected project. Wiping domain data alone leaves
38
+ // the platform's plugin registry intact, so the store stays re-seedable.
39
+ //
40
+ // Stack resolution reuses `ReventlessSeedAws` (same `pulumi` subprocess, same
41
+ // backend pinning). AWS credentials come from the ambient chain (env / profile /
42
+ // SSO); only the region is resolved explicitly and pinned on the environment, so
43
+ // every SDK client targets the same account/region the tags were read from.
44
+
45
+ open ReventlessSeed
46
+
47
+ module Ddb = AwsSdk.DynamoDb
48
+ module Rgt = AwsSdk.ResourceGroupsTaggingApi
49
+ module S3 = AwsSdk.S3
50
+ module Lambda = AwsSdk.Lambda
51
+ module Quiesce = ReventlessSeedAws_Quiesce
52
+
53
+
54
+
55
+ // The Pulumi project name, which the framework stamps as `reventless:platform` on
56
+ // every resource (`Plugin.res`: `platformName = getProjectName()`). Discovery
57
+ // MUST scope on this as well as the stack: `reventless:environment` carries only
58
+ // the stack *name*, so two different Pulumi projects deployed with the same stack
59
+ // name (e.g. `alpha`) in one account/region share that tag. Filtering by platform
60
+ // too keeps a wipe inside the one project the operator is standing in. Read from
61
+ // the target project's Pulumi.yaml — the same dir the pulumi subprocess uses.
62
+ let projectName = (~projectDir: string): string => {
63
+ let path = `${projectDir}/Pulumi.yaml`
64
+ let raw = try NodeFs.readFileSync(path) catch {
65
+ | _ => throw(Seed.Failed(`could not read ${path} to scope the wipe to this Pulumi project.`))
66
+ }
67
+ switch raw
68
+ ->String.split("\n")
69
+ ->Array.find(line => line->String.trim->String.startsWith("name:")) {
70
+ | Some(line) =>
71
+ let trimmed = line->String.trim
72
+ trimmed
73
+ ->String.slice(~start=String.length("name:"), ~end=String.length(trimmed))
74
+ ->String.trim
75
+ ->String.replaceRegExp(%re("/^[\"']|[\"']$/g"), "")
76
+ | None => throw(Seed.Failed(`could not find a \`name:\` field in ${path}.`))
77
+ }
78
+ }
79
+
80
+ // A read of a JSON object field — items come back from the document client as
81
+ // already-unmarshalled JSON values, so a delete key is just the key attributes
82
+ // picked back out.
83
+ let field = (json: JSON.t, key: string): option<JSON.t> =>
84
+ switch json {
85
+ | Object(obj) => obj->Dict.get(key)
86
+ | _ => None
87
+ }
88
+
89
+ let asString = (json: JSON.t): option<string> =>
90
+ switch json {
91
+ | String(s) => Some(s)
92
+ | _ => None
93
+ }
94
+
95
+ let chunk = (arr: array<'a>, size: int): array<array<'a>> => {
96
+ let out = []
97
+ let i = ref(0)
98
+ while i.contents < arr->Array.length {
99
+ out->Array.push(arr->Array.slice(~start=i.contents, ~end=i.contents + size))
100
+ i := i.contents + size
101
+ }
102
+ out
103
+ }
104
+
105
+ // ── Gates ───────────────────────────────────────────────────────────────────
106
+
107
+ // Fail-closed name allowlist. A denylist ("everything except prod") fails open
108
+ // the day a new prod-like stack is added and forgotten; this fails closed.
109
+ let nameAllowlist = %re("/^(alpha|dev|pr-.+)$/")
110
+
111
+ // The stack's fully-resolved Pulumi config, read once. Reading it whole (rather
112
+ // than `pulumi config get <key>`, which exits non-zero for BOTH a missing key
113
+ // and a missing/unreachable stack) lets a refusal say *which* it was — an
114
+ // unreadable config is a pulumi/backend problem; an absent flag is a missing
115
+ // opt-in. `pulumi config --json` maps each key to `{value, secret}`.
116
+ let readStackConfig = (~projectDir, ~backend, ~stack): result<dict<JSON.t>, string> =>
117
+ switch (
118
+ try Some(ReventlessSeedAws.pulumi(~projectDir, ~backend, ["config", "--json", "--stack", stack])) catch {
119
+ | _ => None
120
+ }
121
+ ) {
122
+ | None =>
123
+ Error(
124
+ `could not read the Pulumi config for stack "${stack}" — is pulumi logged in to the right backend, and is the stack deployed?`,
125
+ )
126
+ | Some(raw) =>
127
+ switch (
128
+ try Some(JSON.parseOrThrow(raw)) catch {
129
+ | _ => None
130
+ }
131
+ ) {
132
+ | Some(Object(obj)) => Ok(obj)
133
+ | _ => Error(`could not parse \`pulumi config --json\` output for stack "${stack}".`)
134
+ }
135
+ }
136
+
137
+ let configValue = (cfg: dict<JSON.t>, key: string): option<string> =>
138
+ cfg->Dict.get(key)->Option.flatMap(v => v->field("value"))->Option.flatMap(asString)
139
+
140
+ // ── Discovery ─────────────────────────────────────────────────────────────────
141
+
142
+ type resource =
143
+ | Table(string)
144
+ | Bucket(string)
145
+ | Function(string)
146
+ | Other
147
+
148
+ // arn:aws:dynamodb:<region>:<acct>:table/<name> | arn:aws:s3:::<bucket>
149
+ // | arn:aws:lambda:<region>:<acct>:function:<name>
150
+ //
151
+ // A Lambda ARN can carry a trailing `:<version|alias>` qualifier. The tagging
152
+ // API returns the unqualified form, but taking the segment after `:function:`
153
+ // up to the next colon rather than to the end of the string means a qualified
154
+ // one still yields the function name instead of a name no API accepts.
155
+ let classify = (arn: string): resource =>
156
+ if arn->String.startsWith("arn:aws:dynamodb:") {
157
+ switch arn->String.split(":table/") {
158
+ | [_, name] => Table(name)
159
+ | _ => Other
160
+ }
161
+ } else if arn->String.startsWith("arn:aws:s3:::") {
162
+ Bucket(arn->String.slice(~start=String.length("arn:aws:s3:::"), ~end=String.length(arn)))
163
+ } else if arn->String.startsWith("arn:aws:lambda:") {
164
+ switch arn->String.split(":function:") {
165
+ | [_, rest] =>
166
+ switch rest->String.split(":") {
167
+ | [name] => Function(name)
168
+ | [name, _qualifier] => Function(name)
169
+ | _ => Other
170
+ }
171
+ | _ => Other
172
+ }
173
+ } else {
174
+ Other
175
+ }
176
+
177
+ let tagValue = (tags: array<Rgt.GetResourcesCommand.tag>, key: string): option<string> =>
178
+ tags->Array.findMap(t => t.key == key ? Some(t.value) : None)
179
+
180
+ /** What one project's tags resolve to: the stores to empty, and the runtimes
181
+ that have to be held still while that happens. */
182
+ type discovered = {
183
+ tables: array<string>,
184
+ buckets: array<string>,
185
+ functions: array<string>,
186
+ }
187
+
188
+ // Discovery is scoped by BOTH tags (platform AND environment) — the Tagging API
189
+ // ANDs multiple TagFilters — so it only ever sees the target project's own stack,
190
+ // never a same-named stack from another project. Each returned resource is then
191
+ // re-checked to carry both tags (a mismatch aborts the whole run rather than
192
+ // being skipped) as a second, per-resource guard.
193
+ //
194
+ // Lambda functions are discovered alongside the stores, under the same tags and
195
+ // the same per-resource re-check. They are never deleted from — they are what
196
+ // the wipe has to hold still, and the tag scope that decides what may be emptied
197
+ // is exactly the scope that decides what may be held.
198
+ let discover = async (~region, ~stack, ~platform): discovered => {
199
+ let client = Rgt.client(~region, ())
200
+ let tables = []
201
+ let buckets = []
202
+ let functions = []
203
+ let rec loop = async (token: option<string>): unit => {
204
+ let out = await Rgt.GetResourcesCommand.send(
205
+ client,
206
+ Rgt.GetResourcesCommand.make({
207
+ tagFilters: [
208
+ {key: "reventless:platform", values: [platform]},
209
+ {key: "reventless:environment", values: [stack]},
210
+ ],
211
+ resourceTypeFilters: ["dynamodb:table", "s3", "lambda:function"],
212
+ resourcesPerPage: 100,
213
+ paginationToken: ?token,
214
+ }),
215
+ )
216
+ out.resourceTagMappingList
217
+ ->Option.getOr([])
218
+ ->Array.forEach(m => {
219
+ let tags = m.tags->Option.getOr([])
220
+ let assertTag = (key, expected) =>
221
+ switch tagValue(tags, key) {
222
+ | Some(v) if v == expected => ()
223
+ | other =>
224
+ throw(
225
+ Seed.Failed(
226
+ `refusing: discovered resource ${m.resourceARN} carries ${key}=${other->Option.getOr(
227
+ "<none>",
228
+ )}, not "${expected}".`,
229
+ ),
230
+ )
231
+ }
232
+ assertTag("reventless:platform", platform)
233
+ assertTag("reventless:environment", stack)
234
+ switch classify(m.resourceARN) {
235
+ | Table(name) => tables->Array.push(name)
236
+ | Bucket(name) => buckets->Array.push(name)
237
+ | Function(name) => functions->Array.push(name)
238
+ | Other => ()
239
+ }
240
+ })
241
+ switch out.paginationToken {
242
+ | Some(t) if t != "" => await loop(Some(t))
243
+ | _ => ()
244
+ }
245
+ }
246
+ await loop(None)
247
+ {tables, buckets, functions}
248
+ }
249
+
250
+ // ── Declared object stores ────────────────────────────────────────────────────
251
+ //
252
+ // A store declared by a `@storageRef` field is provisioned by the PLATFORM
253
+ // deploy — the serving CDN and the presign services live there, and a
254
+ // shared-layout bucket holds several plugins' stores, so no plugin stack can own
255
+ // it. Its bucket therefore carries the platform project's `reventless:platform`
256
+ // tag, which makes it invisible to a domain-scoped tag discovery and, worse,
257
+ // wholesale-emptiable by a platform-scoped one.
258
+ //
259
+ // Tag discovery cannot fix that: the tag says which project *built* the bucket,
260
+ // and the answer needed here is which plugin's data is *in* it — at prefix
261
+ // granularity, since one bucket holds several plugins' stores. The platform
262
+ // already publishes exactly that mapping as its `objectStores` stack output, so
263
+ // the reset reads ownership from the declaration rather than inferring it.
264
+
265
+ /** One provisioned store: which plugin owns it, and where its objects live. */
266
+ type objectStore = {
267
+ qualified: string,
268
+ plugin: string,
269
+ store: string,
270
+ bucketName: string,
271
+ keyPrefix: string,
272
+ }
273
+
274
+ // A store's key is `{plugin}.{store}`, split at the FIRST dot: a registered
275
+ // plugin name cannot contain one, a store name could in principle.
276
+ let splitQualified = (key: string): option<(string, string)> =>
277
+ key
278
+ ->String.indexOfOpt(".")
279
+ ->Option.map(i => (
280
+ key->String.slice(~start=0, ~end=i),
281
+ key->String.slice(~start=i + 1, ~end=key->String.length),
282
+ ))
283
+
284
+ /** Parse the platform stack's `objectStores` output. Absent is normal — a
285
+ platform may declare no stores — so only a malformed entry is an error, and
286
+ it is an error rather than a skip because a store the reset cannot read is a
287
+ store it would silently leave behind. */
288
+ let parseObjectStores = (json: option<JSON.t>): result<array<objectStore>, string> =>
289
+ switch json {
290
+ | None => Ok([])
291
+ | Some(Object(entries)) =>
292
+ entries
293
+ ->Dict.toArray
294
+ ->Array.reduce(Ok([]), (acc, (qualified, entry)) =>
295
+ switch acc {
296
+ | Error(_) as failed => failed
297
+ | Ok(stores) =>
298
+ switch (
299
+ splitQualified(qualified),
300
+ entry->field("bucketName")->Option.flatMap(asString),
301
+ entry->field("keyPrefix")->Option.flatMap(asString),
302
+ ) {
303
+ | (Some((plugin, store)), Some(bucketName), Some(keyPrefix)) =>
304
+ Ok(Array.concat(stores, [{qualified, plugin, store, bucketName, keyPrefix}]))
305
+ | _ =>
306
+ Error(
307
+ `the platform stack's \`objectStores\` output has a malformed entry for "${qualified}" — ` ++
308
+ `expected a {plugin}.{store} key carrying bucketName and keyPrefix.`,
309
+ )
310
+ }
311
+ }
312
+ )
313
+ | Some(_) => Error("the platform stack's `objectStores` output is not an object.")
314
+ }
315
+
316
+ /** Refuse any store set a prefix-scoped wipe cannot separate.
317
+
318
+ Equality is the cross-plugin collision: two plugins declaring one store name
319
+ land on one prefix inside a shared bucket, and nothing distinguishes their
320
+ objects. Containment is the same problem one level up — the delete prefix is
321
+ `{keyPrefix}/`, so a store rooted at `a` encloses one rooted at `a/b`.
322
+ Comparing containment rather than equality is what keeps this correct once a
323
+ prefix carries path structure.
324
+
325
+ Fail-closed, and before anything is counted: this is the tool that destroys
326
+ data, so it refuses rather than skipping, and it does not assume an upstream
327
+ deploy-time check ran. */
328
+ let validateStores = (stores: array<objectStore>): result<unit, string> =>
329
+ switch stores->Array.find(s => s.keyPrefix == "" || s.store->String.includes("/")) {
330
+ | Some(s) =>
331
+ Error(
332
+ `store "${s.qualified}" has an unusable key prefix ("${s.keyPrefix}") — ` ++
333
+ `a store name may not be empty or contain "/".`,
334
+ )
335
+ | None =>
336
+ switch stores->Array.findMap(a =>
337
+ stores->Array.findMap(b =>
338
+ if a.qualified == b.qualified || a.bucketName != b.bucketName {
339
+ None
340
+ } else if a.keyPrefix == b.keyPrefix {
341
+ Some(
342
+ `stores "${a.qualified}" and "${b.qualified}" both live at ` ++
343
+ `${a.bucketName}/${a.keyPrefix}/ — a prefix-scoped wipe cannot tell their objects ` ++
344
+ `apart. Rename one store, or qualify the \`@storageRef\` annotation if they were ` ++
345
+ `meant to be one shared store.`,
346
+ )
347
+ } else if b.keyPrefix->String.startsWith(a.keyPrefix ++ "/") {
348
+ Some(
349
+ `store "${a.qualified}" (${a.bucketName}/${a.keyPrefix}/) encloses "${b.qualified}" ` ++
350
+ `(${b.keyPrefix}/) — wiping the first would delete the second's objects. Rename one.`,
351
+ )
352
+ } else {
353
+ None
354
+ }
355
+ )
356
+ ) {
357
+ | Some(message) => Error(message)
358
+ | None => Ok()
359
+ }
360
+ }
361
+
362
+ // ── Counting (dry-run) ─────────────────────────────────────────────────────────
363
+
364
+ let countTable = async (table: string): int => {
365
+ let rec loop = async (start: option<dict<JSON.t>>, acc: int): int => {
366
+ let out = await Ddb.DocumentClient.ScanCommand.send(
367
+ Ddb.DocumentClient.ScanCommand.make({
368
+ tableName: table,
369
+ select: #COUNT,
370
+ exclusiveStartKey: ?start,
371
+ }),
372
+ )
373
+ let acc = acc + out.count->Option.getOr(0)
374
+ switch out.lastEvaluatedKey {
375
+ | Some(k) => await loop(Some(k), acc)
376
+ | None => acc
377
+ }
378
+ }
379
+ await loop(None, 0)
380
+ }
381
+
382
+ // `~prefix` narrows the count to one declared store inside a shared bucket;
383
+ // omitted, it counts the whole bucket.
384
+ let countBucket = async (bucket: string, ~prefix: option<string>=?): int => {
385
+ let rec loop = async (keyMarker, versionMarker, acc): int => {
386
+ let out = await S3.ListObjectVersionsCommand.send(
387
+ S3.ListObjectVersionsCommand.make({
388
+ bucket,
389
+ prefix: ?prefix,
390
+ keyMarker: ?keyMarker,
391
+ versionIdMarker: ?versionMarker,
392
+ }),
393
+ )
394
+ let n =
395
+ out.versions->Option.getOr([])->Array.length +
396
+ out.deleteMarkers->Option.getOr([])->Array.length
397
+ if out.isTruncated->Option.getOr(false) {
398
+ await loop(out.nextKeyMarker, out.nextVersionIdMarker, acc + n)
399
+ } else {
400
+ acc + n
401
+ }
402
+ }
403
+ await loop(None, None, 0)
404
+ }
405
+
406
+ // ── Wiping ──────────────────────────────────────────────────────────────────
407
+
408
+ // BatchWrite takes ≤ 25 requests and may return some UnprocessedItems under
409
+ // throttling; resend those. Capped so a persistently-failing table surfaces as
410
+ // an error rather than looping forever.
411
+ let rec sendBatch = async (
412
+ table: string,
413
+ requests: array<Ddb.DocumentClient.BatchWriteCommand.writeRequest>,
414
+ ~attempt: int,
415
+ ): unit =>
416
+ if requests->Array.length > 0 {
417
+ if attempt > 8 {
418
+ throw(Seed.Failed(`table ${table}: ${(requests->Array.length)->Int.toString} item(s) still unprocessed after 8 retries.`))
419
+ }
420
+ let out = await Ddb.DocumentClient.BatchWriteCommand.send(
421
+ Ddb.DocumentClient.BatchWriteCommand.make({
422
+ requestItems: Dict.fromArray([(table, requests)]),
423
+ }),
424
+ )
425
+ let unprocessed =
426
+ out.unprocessedItems->Option.flatMap(d => d->Dict.get(table))->Option.getOr([])
427
+ if unprocessed->Array.length > 0 {
428
+ await sendBatch(table, unprocessed, ~attempt=attempt + 1)
429
+ }
430
+ }
431
+
432
+ let truncateTable = async (table: string): unit => {
433
+ let desc = await Ddb.DynamoDb.DescribeTableCommand.send(
434
+ Ddb.DynamoDb.DescribeTableCommand.make({tableName: table}),
435
+ )
436
+ let keyAttrs =
437
+ desc.table->Option.flatMap(t => t.keySchema)->Option.getOr([])->Array.map(k => k.attributeName)
438
+ if keyAttrs->Array.length == 0 {
439
+ throw(Seed.Failed(`could not read a key schema for table ${table}.`))
440
+ }
441
+ // Project only the key attributes (aliased to dodge reserved words) so the
442
+ // scan carries just what a delete needs.
443
+ let names = keyAttrs->Array.mapWithIndex((name, i) => (`#k${i->Int.toString}`, name))
444
+ let projection = names->Array.map(((alias, _)) => alias)->Array.join(", ")
445
+ let rec loop = async (start: option<dict<JSON.t>>): unit => {
446
+ let out = await Ddb.DocumentClient.ScanCommand.send(
447
+ Ddb.DocumentClient.ScanCommand.make({
448
+ tableName: table,
449
+ exclusiveStartKey: ?start,
450
+ projectionExpression: projection,
451
+ expressionAttributeNames: names->Dict.fromArray,
452
+ }),
453
+ )
454
+ let requests =
455
+ out.items
456
+ ->Option.getOr([])
457
+ ->Array.map(item => {
458
+ let key =
459
+ keyAttrs->Array.filterMap(attr => item->field(attr)->Option.map(v => (attr, v)))->Dict.fromArray
460
+ ({deleteRequest: {key: key}}: Ddb.DocumentClient.BatchWriteCommand.writeRequest)
461
+ })
462
+ let batches = chunk(requests, Ddb.DocumentClient.BatchWriteCommand.maxBatchSize)
463
+ for i in 0 to batches->Array.length - 1 {
464
+ switch batches->Array.get(i) {
465
+ | Some(b) => await sendBatch(table, b, ~attempt=1)
466
+ | None => ()
467
+ }
468
+ }
469
+ switch out.lastEvaluatedKey {
470
+ | Some(k) => await loop(Some(k))
471
+ | None => ()
472
+ }
473
+ }
474
+ await loop(None)
475
+ }
476
+
477
+ // One ListObjectVersions page returns ≤ 1000 entries (versions + delete
478
+ // markers), and DeleteObjects takes ≤ 1000, so one list page maps to one delete.
479
+ let emptyBucket = async (bucket: string, ~prefix: option<string>=?): unit => {
480
+ let rec loop = async (keyMarker, versionMarker): unit => {
481
+ let out = await S3.ListObjectVersionsCommand.send(
482
+ S3.ListObjectVersionsCommand.make({
483
+ bucket,
484
+ prefix: ?prefix,
485
+ keyMarker: ?keyMarker,
486
+ versionIdMarker: ?versionMarker,
487
+ }),
488
+ )
489
+ let ids =
490
+ Array.concat(out.versions->Option.getOr([]), out.deleteMarkers->Option.getOr([]))->Array.map(v => (
491
+ {key: v.key, versionId: v.versionId}: S3.DeleteObjectsCommand.objectIdentifier
492
+ ))
493
+ if ids->Array.length > 0 {
494
+ let res = await S3.DeleteObjectsCommand.send(
495
+ S3.DeleteObjectsCommand.make({
496
+ bucket,
497
+ delete: {objects: ids, quiet: true},
498
+ }),
499
+ )
500
+ switch res.errors {
501
+ | Some(errs) if errs->Array.length > 0 =>
502
+ throw(
503
+ Seed.Failed(
504
+ `failed to delete ${(errs->Array.length)->Int.toString} object(s) from ${bucket}: ${errs
505
+ ->Array.get(0)
506
+ ->Option.flatMap(e => e.message)
507
+ ->Option.getOr("unknown")}`,
508
+ ),
509
+ )
510
+ | _ => ()
511
+ }
512
+ }
513
+ if out.isTruncated->Option.getOr(false) {
514
+ await loop(out.nextKeyMarker, out.nextVersionIdMarker)
515
+ }
516
+ }
517
+ await loop(None, None)
518
+ }
519
+
520
+ // ── Targets & scope ───────────────────────────────────────────────────────────
521
+
522
+ // A deployment is several Pulumi projects sharing a stack name — the platform
523
+ // project plus one per domain plugin — each a separate `reventless:platform`. A
524
+ // target names one such project by the directory its `Pulumi.<stack>.yaml` lives
525
+ // in (relative to the seed cwd), plus a menu label and whether it holds domain
526
+ // data or platform bookkeeping. The caller declares them; the reset never guesses
527
+ // the topology.
528
+ type group =
529
+ | Domain
530
+ | Platform
531
+
532
+ type target = {
533
+ projectDir: string,
534
+ label: string,
535
+ group: group,
536
+ // The name this project's plugin REGISTERS, when it differs from the
537
+ // operator-facing `label` (`Catalog` against `catalog`). It is what the
538
+ // platform's `objectStores` keys are qualified by, so it is how a declared
539
+ // store is attributed to a target. Declared rather than case-folded from the
540
+ // label: the caller states the topology, the reset never guesses it.
541
+ plugin?: string,
542
+ }
543
+
544
+ let pluginOf = (t: target): string => t.plugin->Option.getOr(t.label)
545
+
546
+ // A target resolved to its discovered, counted stores, ready to report and wipe.
547
+ type resolved = {
548
+ target: target,
549
+ platform: string,
550
+ tables: array<string>,
551
+ tableCounts: array<int>,
552
+ bucketCounts: array<(string, int)>,
553
+ storeCounts: array<(objectStore, int)>,
554
+ /** The project's Lambda functions — not wiped, held still while it is. */
555
+ functions: array<string>,
556
+ }
557
+
558
+ // Picks which targets to wipe. `domain` (every domain plugin) leads and is the
559
+ // default; each single domain plugin follows so one plugin's data can be wiped
560
+ // alone; then `platform`; then `everything`. `SEED_RESET_SCOPE` (domain |
561
+ // platform | everything | a plugin label) selects non-interactively.
562
+ let chooseScope = async (~targets: array<target>): array<target> => {
563
+ let domain = targets->Array.filter(t => t.group == Domain)
564
+ let platform = targets->Array.filter(t => t.group == Platform)
565
+ let labelsOf = ts => ts->Array.map(t => t.label)->Array.join(", ")
566
+ switch Seed.Prompt.envValue("SEED_RESET_SCOPE")->Option.map(String.toLowerCase) {
567
+ | Some("domain") => domain
568
+ | Some("platform") => platform
569
+ | Some("all") | Some("everything") | Some("both") => targets
570
+ | Some(other) =>
571
+ switch targets->Array.find(t => t.label->String.toLowerCase == other) {
572
+ | Some(t) => [t]
573
+ | None =>
574
+ throw(
575
+ Seed.Failed(
576
+ `SEED_RESET_SCOPE="${other}" is not a scope — use domain, platform, everything, or a plugin label (${labelsOf(
577
+ domain,
578
+ )}).`,
579
+ ),
580
+ )
581
+ }
582
+ | None =>
583
+ let options = []
584
+ if domain->Array.length > 0 {
585
+ options->Array.push((`domain — ${labelsOf(domain)}`, domain))
586
+ // Single-plugin entries only when there is more than one, else they just
587
+ // duplicate the `domain` entry.
588
+ if domain->Array.length > 1 {
589
+ domain->Array.forEach(t => options->Array.push((t.label, [t])))
590
+ }
591
+ }
592
+ if platform->Array.length > 0 {
593
+ options->Array.push((`platform — ${labelsOf(platform)}`, platform))
594
+ }
595
+ if domain->Array.length > 0 && platform->Array.length > 0 {
596
+ options->Array.push((`everything — ${labelsOf(targets)}`, targets))
597
+ }
598
+ await Seed.Prompt.select(~title="Reset scope:", ~options)
599
+ }
600
+ }
601
+
602
+ // ── Orchestration ─────────────────────────────────────────────────────────────
603
+
604
+ // Gate 2 per target: its own `Pulumi.<stack>.yaml` must declare wipeable, and
605
+ // must resolve a region. Reasons are distinct (config unreadable vs opt-in
606
+ // missing vs region missing), each saying what to fix. Returns the target's
607
+ // region so the caller can insist every selected target shares one.
608
+ let gateTarget = (~target: target, ~backend, ~stack): string => {
609
+ let cfg = switch readStackConfig(~projectDir=target.projectDir, ~backend, ~stack) {
610
+ | Ok(c) => c
611
+ | Error(message) => throw(Seed.Failed(message))
612
+ }
613
+ switch configValue(cfg, "reventless:wipeable")->Option.map(v => v->String.trim->String.toLowerCase) {
614
+ | Some("true") => ()
615
+ | _ =>
616
+ throw(
617
+ Seed.Failed(
618
+ `${target.label}: stack "${stack}" does not declare \`reventless:wipeable: "true"\` in its Pulumi.${stack}.yaml — refusing. Add that line only on disposable dev stacks (see the alpha example configs).`,
619
+ ),
620
+ )
621
+ }
622
+ switch Seed.Prompt.envValue("AWS_REGION") {
623
+ | Some(r) if r != "" => r
624
+ | _ =>
625
+ switch configValue(cfg, "aws:region") {
626
+ | Some(r) if r != "" => r
627
+ | _ =>
628
+ throw(
629
+ Seed.Failed(
630
+ `${target.label}: could not resolve the AWS region — set AWS_REGION or \`aws:region\` in the stack config.`,
631
+ ),
632
+ )
633
+ }
634
+ }
635
+ }
636
+
637
+ /** Opt out of holding the platform still for the wipe. The hold needs Lambda
638
+ permissions the reset did not previously ask for, so credentials that lack
639
+ them have a way through — at the cost of the emptiness guarantee, which the
640
+ note printed alongside it says plainly. */
641
+ let noQuiesce = (): bool =>
642
+ switch Seed.Prompt.envValue("SEED_RESET_NO_QUIESCE")->Option.map(v =>
643
+ v->String.trim->String.toLowerCase
644
+ ) {
645
+ | Some("1") | Some("true") | Some("yes") => true
646
+ | _ => false
647
+ }
648
+
649
+ /** What to say when a store is not empty after the wipe.
650
+
651
+ The old message reported only a total and advised re-running. That advice was
652
+ wrong in exactly the case that occurs: a runtime holding its state in memory
653
+ rewrites the store on every invocation, so every re-run reproduces the same
654
+ failure and the message sends the operator round the loop again.
655
+
656
+ So name the stores, and separate the two situations that are actually
657
+ different. Under a hold, nothing could start during the wipe, so the only
658
+ possible writer is an invocation that was already in flight — and a re-run
659
+ does clear that. Without a hold there is no such bound, and re-running is the
660
+ wrong advice. */
661
+ let refillMessage = (~refilled: array<(string, int)>, ~heldCount: int): string => {
662
+ let total = refilled->Array.reduce(0, (acc, (_, n)) => acc + n)
663
+ let lines =
664
+ refilled
665
+ ->Array.map(((label, n)) => `\n ${n->Int.toString->String.padStart(8, " ")} ${label}`)
666
+ ->Array.join("")
667
+ let diagnosis = if heldCount > 0 {
668
+ `\n\n The wipe deleted these and something wrote them back. All ${heldCount->Int.toString} runtime(s) ` ++
669
+ `in scope were held at zero concurrency for the whole wipe, so the writer was an invocation already ` ++
670
+ `in flight when the hold took effect. Re-running clears it.`
671
+ } else {
672
+ `\n\n The wipe deleted these and a running runtime wrote them back. The stack was NOT held ` ++
673
+ `(SEED_RESET_NO_QUIESCE), so nothing stopped it, and re-running will not help: the writer keeps the ` ++
674
+ `state in memory and restores it on every invocation, identical each time. Re-run without ` ++
675
+ `SEED_RESET_NO_QUIESCE so the runtimes are held and recycled.`
676
+ }
677
+ `${total->Int.toString} item(s)/object(s) came back after the wipe:${lines}${diagnosis}`
678
+ }
679
+
680
+ let reportAll = (resolvedList: array<resolved>, ~stack, ~region): int => {
681
+ Seed.Runner.heading(`Reset target: stack "${stack}" in ${region}`)
682
+ let total = ref(0)
683
+ resolvedList->Array.forEach(r => {
684
+ Console.log("")
685
+ Console.log(` ${r.target.label} (${r.platform})`)
686
+ Console.log(" DynamoDB tables:")
687
+ r.tables->Array.forEachWithIndex((t, i) => {
688
+ let c = r.tableCounts->Array.get(i)->Option.getOr(0)
689
+ total := total.contents + c
690
+ Console.log(` ${c->Int.toString->String.padStart(8, " ")} ${t}`)
691
+ })
692
+ if r.tables->Array.length == 0 {
693
+ Console.log(" (none)")
694
+ }
695
+ Console.log(" S3 buckets:")
696
+ r.bucketCounts->Array.forEach(((b, c)) => {
697
+ total := total.contents + c
698
+ Console.log(` ${c->Int.toString->String.padStart(8, " ")} ${b}`)
699
+ })
700
+ if r.bucketCounts->Array.length == 0 {
701
+ Console.log(" (none)")
702
+ }
703
+ // Declared stores get their own section rather than being folded in with the
704
+ // plain buckets: the unit is a prefix inside a bucket that other plugins also
705
+ // write to, and the operator needs to see which is which before confirming.
706
+ if r.storeCounts->Array.length > 0 {
707
+ Console.log(" Object stores:")
708
+ r.storeCounts->Array.forEach(((s, c)) => {
709
+ total := total.contents + c
710
+ Console.log(
711
+ ` ${c->Int.toString->String.padStart(8, " ")} ${s.qualified} ` ++
712
+ `${s.bucketName}/${s.keyPrefix}/`,
713
+ )
714
+ })
715
+ }
716
+ })
717
+ total.contents
718
+ }
719
+
720
+ /**
721
+ * Reset a deployed stack across one or more of its Pulumi projects. Resolves the
722
+ * shared stack name, refuses unless it is on the name allowlist, lets the
723
+ * operator pick a scope (domain / a single plugin / platform / everything), then
724
+ * for each chosen project: refuses unless it declares itself wipeable, discovers
725
+ * its stores by `platform`+`environment` tag, and reports what it would empty.
726
+ * Only on a matching `REVENTLESS_WIPE_CONFIRM` plus a re-typed stack name does it
727
+ * truncate every table and empty every bucket, then verify empty.
728
+ *
729
+ * `targets` are the deployment's projects (the caller knows the topology);
730
+ * `stack` and `backend` mirror `ReventlessSeedAws.connect`.
731
+ */
732
+ let run = (~stack=?, ~backend=?, ~targets: array<target>, ()): unit => {
733
+ let go = async () => {
734
+ try {
735
+ if targets->Array.length == 0 {
736
+ throw(Seed.Failed("no targets were declared — nothing to reset."))
737
+ }
738
+ let backend = switch Seed.Prompt.envValue("SEED_PULUMI_BACKEND") {
739
+ | Some(url) => Some(url)
740
+ | None => backend
741
+ }
742
+ // Any target's dir lists the shared stack; prefer the platform project.
743
+ let baseTarget =
744
+ targets->Array.find(t => t.group == Platform)->Option.getOr(targets->Array.getUnsafe(0))
745
+ let stack = await ReventlessSeedAws.resolveStack(
746
+ ~projectDir=baseTarget.projectDir,
747
+ ~backend,
748
+ ~stack,
749
+ )
750
+
751
+ if !(nameAllowlist->RegExp.test(stack)) {
752
+ throw(
753
+ Seed.Failed(
754
+ `stack "${stack}" is not on the wipe name-allowlist (alpha, dev, pr-*) — refusing.`,
755
+ ),
756
+ )
757
+ }
758
+
759
+ let selected = await chooseScope(~targets)
760
+
761
+ // Declared object stores live in a bucket the PLATFORM project owns, so
762
+ // resolving them reads the platform's stack output whichever scope was
763
+ // picked. Reading is side-effect free; the gates below decide whether
764
+ // anything may be deleted from it.
765
+ let platformTarget = targets->Array.find(t => t.group == Platform)
766
+ let allStores = switch platformTarget {
767
+ | None =>
768
+ // Not silent: a topology with no platform target is exactly the case
769
+ // where declared stores would be missed, and missing them is the bug
770
+ // this resolution exists to fix.
771
+ Console.log("")
772
+ Console.log(
773
+ "Note: no `platform` target is declared, so declared object stores could not be " ++
774
+ "resolved — any uploaded objects will be left in place.",
775
+ )
776
+ []
777
+ | Some(pt) =>
778
+ let output = ReventlessSeedAws.stackOutputs(~projectDir=pt.projectDir, ~backend, stack)
779
+ switch parseObjectStores(output->field("objectStores")) {
780
+ | Ok(stores) => stores
781
+ | Error(message) => throw(Seed.Failed(message))
782
+ }
783
+ }
784
+ switch validateStores(allStores) {
785
+ | Ok() => ()
786
+ | Error(message) => throw(Seed.Failed(`refusing: ${message}`))
787
+ }
788
+
789
+ // Every bucket that holds a declared store, selected or not. These are
790
+ // excluded from the plain per-target bucket lists below so a store is
791
+ // reachable ONLY through the plugin that declared it — otherwise the
792
+ // platform scope would empty every plugin's objects wholesale.
793
+ let storeBucketNames = allStores->Array.map(s => s.bucketName)
794
+ let selectedStores =
795
+ allStores->Array.filter(s => selected->Array.some(t => pluginOf(t) == s.plugin))
796
+
797
+ // Gate every selected target and collect its region; all must agree, since
798
+ // the DynamoDB/S3 clients read one region from the environment. When a
799
+ // store is in scope, the platform's own stack must also declare itself
800
+ // wipeable — the objects belong to a plugin, but the bucket is the
801
+ // platform's, and both consents are needed to delete from it.
802
+ let gated = switch (selectedStores->Array.length > 0, platformTarget) {
803
+ | (true, Some(pt)) if !(selected->Array.some(t => t.projectDir == pt.projectDir)) =>
804
+ Array.concat(selected, [pt])
805
+ | _ => selected
806
+ }
807
+ let regions = gated->Array.map(t => gateTarget(~target=t, ~backend, ~stack))
808
+ let region = regions->Array.getUnsafe(0)
809
+ if regions->Array.some(r => r != region) {
810
+ throw(
811
+ Seed.Failed(
812
+ `selected targets span more than one region (${regions->Array.join(
813
+ ", ",
814
+ )}) — reset them one region at a time.`,
815
+ ),
816
+ )
817
+ }
818
+ NodeProcess.env->Dict.set("AWS_REGION", region)
819
+
820
+ // A store bucket arrives by stack output, not by tag discovery, so the
821
+ // per-resource tag re-check has to be applied to it explicitly: confirm it
822
+ // carries the platform project's own `platform`+`environment` tags before
823
+ // anything is deleted from it. One extra tagging-API call, and only when a
824
+ // store is actually in scope.
825
+ if selectedStores->Array.length > 0 {
826
+ switch platformTarget {
827
+ | Some(pt) =>
828
+ let platformProject = projectName(~projectDir=pt.projectDir)
829
+ let platformFound = await discover(~region, ~stack, ~platform=platformProject)
830
+ selectedStores->Array.forEach(s =>
831
+ if !(platformFound.buckets->Array.includes(s.bucketName)) {
832
+ throw(
833
+ Seed.Failed(
834
+ `refusing: store "${s.qualified}" names bucket ${s.bucketName}, which does not ` ++
835
+ `carry reventless:platform=${platformProject} + reventless:environment=${stack}.`,
836
+ ),
837
+ )
838
+ }
839
+ )
840
+ | None => ()
841
+ }
842
+ }
843
+
844
+ // Discover + count each target, scoped to its own project via the platform
845
+ // tag so a same-named stack from another project is never touched.
846
+ let resolvedList = []
847
+ for i in 0 to selected->Array.length - 1 {
848
+ switch selected->Array.get(i) {
849
+ | Some(target) =>
850
+ let platform = projectName(~projectDir=target.projectDir)
851
+ let found = await discover(~region, ~stack, ~platform)
852
+ let tables = found.tables->Array.toSorted(String.compare)
853
+ let buckets =
854
+ found.buckets
855
+ ->Array.filter(b => !(storeBucketNames->Array.includes(b)))
856
+ ->Array.toSorted(String.compare)
857
+ let tableCounts = []
858
+ for j in 0 to tables->Array.length - 1 {
859
+ switch tables->Array.get(j) {
860
+ | Some(t) => tableCounts->Array.push(await countTable(t))
861
+ | None => ()
862
+ }
863
+ }
864
+ let bucketCounts = []
865
+ for j in 0 to buckets->Array.length - 1 {
866
+ switch buckets->Array.get(j) {
867
+ | Some(b) => bucketCounts->Array.push((b, await countBucket(b)))
868
+ | None => ()
869
+ }
870
+ }
871
+ let stores = selectedStores->Array.filter(s => s.plugin == pluginOf(target))
872
+ let storeCounts = []
873
+ for j in 0 to stores->Array.length - 1 {
874
+ switch stores->Array.get(j) {
875
+ | Some(s) =>
876
+ storeCounts->Array.push((
877
+ s,
878
+ await countBucket(s.bucketName, ~prefix=`${s.keyPrefix}/`),
879
+ ))
880
+ | None => ()
881
+ }
882
+ }
883
+ resolvedList->Array.push({
884
+ target,
885
+ platform,
886
+ tables,
887
+ tableCounts,
888
+ bucketCounts,
889
+ storeCounts,
890
+ functions: found.functions->Array.toSorted(String.compare),
891
+ })
892
+ | None => ()
893
+ }
894
+ }
895
+
896
+ let total = reportAll(resolvedList, ~stack, ~region)
897
+ if total == 0 {
898
+ Seed.Prompt.close()
899
+ Console.log("")
900
+ Console.log(`Nothing to reset — the selected scope already reads empty in ${region}.`)
901
+ NodeProcess.exit(0)
902
+ }
903
+
904
+ // Confirmation. Interactively, re-typing the exact stack name IS the
905
+ // confirmation — the validation above (allowlist + wipeable + tag checks)
906
+ // plus a deliberate keystroke is enough, so no env var is needed. Without a
907
+ // TTY (CI/scripts) there is nothing to type into, so
908
+ // REVENTLESS_WIPE_CONFIRM=<stack> is the equivalent opt-in. Dry-run is the
909
+ // default either way.
910
+ let interactive = NodeProcess.stdin->NodeProcess.isTTY->Option.getOr(false)
911
+ let confirmed = if interactive {
912
+ let typed = await Seed.Prompt.ask(
913
+ `About to permanently empty ${total->Int.toString} item(s)/object(s) across the selected scope of "${stack}". ` ++
914
+ `Type the stack name to confirm, or press Enter to keep this a dry run: `,
915
+ )
916
+ typed->String.trim == stack
917
+ } else {
918
+ Seed.Prompt.envValue("REVENTLESS_WIPE_CONFIRM") == Some(stack)
919
+ }
920
+ Seed.Prompt.close()
921
+ if !confirmed {
922
+ Console.log("")
923
+ Console.log(
924
+ interactive
925
+ ? "Dry run — nothing was deleted."
926
+ : `Dry run — nothing was deleted. Set REVENTLESS_WIPE_CONFIRM=${stack} to empty this scope non-interactively.`,
927
+ )
928
+ NodeProcess.exit(0)
929
+ }
930
+
931
+ // Hold the platform still before the first delete. A truncate is not
932
+ // durable while the runtimes that own the data are running — see
933
+ // ReventlessSeedAws_Quiesce for the mechanism and for why emptying the
934
+ // upstream stores first does not substitute for this.
935
+ let functionNames = resolvedList->Array.reduce([], (acc, r) =>
936
+ Array.concat(acc, r.functions->Array.filter(f => !(acc->Array.includes(f))))
937
+ )
938
+ let quiesce = !noQuiesce() && functionNames->Array.length > 0
939
+ let lambdaClient = Lambda.client(~region, ())
940
+ let held = if quiesce {
941
+ Seed.Runner.heading(
942
+ `Holding ${functionNames->Array.length->Int.toString} runtime(s) at zero concurrency …`,
943
+ )
944
+ await Quiesce.hold(~client=lambdaClient, ~functionNames)
945
+ } else {
946
+ if functionNames->Array.length > 0 {
947
+ Console.log("")
948
+ Console.log(
949
+ "Note: SEED_RESET_NO_QUIESCE is set — the stack's runtimes keep running through the wipe. " ++
950
+ "A runtime that holds state across invocations can write it straight back over an emptied store.",
951
+ )
952
+ }
953
+ []
954
+ }
955
+
956
+ // From here the reset owns the platform's concurrency, so every exit has
957
+ // to run through the release below — including the abort path. ReScript
958
+ // has no `finally`, so the wipe's outcome is captured as a value and
959
+ // re-raised after the stack has been handed back.
960
+ let outcome = try {
961
+ for i in 0 to resolvedList->Array.length - 1 {
962
+ switch resolvedList->Array.get(i) {
963
+ | Some(r) =>
964
+ Seed.Runner.heading(`Emptying ${r.target.label} …`)
965
+ for j in 0 to r.tables->Array.length - 1 {
966
+ switch r.tables->Array.get(j) {
967
+ | Some(t) =>
968
+ await truncateTable(t)
969
+ Console.log(` truncated ${t}`)
970
+ | None => ()
971
+ }
972
+ }
973
+ for j in 0 to r.bucketCounts->Array.length - 1 {
974
+ switch r.bucketCounts->Array.get(j) {
975
+ | Some((b, _)) =>
976
+ await emptyBucket(b)
977
+ Console.log(` emptied ${b}`)
978
+ | None => ()
979
+ }
980
+ }
981
+ // Report the count with the store, not just in the run total: "how
982
+ // many images went" is the question an operator is actually asking.
983
+ for j in 0 to r.storeCounts->Array.length - 1 {
984
+ switch r.storeCounts->Array.get(j) {
985
+ | Some((s, count)) =>
986
+ await emptyBucket(s.bucketName, ~prefix=`${s.keyPrefix}/`)
987
+ Console.log(
988
+ ` emptied ${s.qualified} — ${count->Int.toString} object(s) removed from ` ++
989
+ `${s.bucketName}/${s.keyPrefix}/`,
990
+ )
991
+ | None => ()
992
+ }
993
+ }
994
+ | None => ()
995
+ }
996
+ }
997
+
998
+ // Prove empty — the inverse of the post-seed verify. Every store that
999
+ // still reads non-zero is named, because "12 items remain" without
1000
+ // saying where is the difference between a diagnosis and a mystery.
1001
+ let refilled = []
1002
+ for i in 0 to resolvedList->Array.length - 1 {
1003
+ switch resolvedList->Array.get(i) {
1004
+ | Some(r) =>
1005
+ for j in 0 to r.tables->Array.length - 1 {
1006
+ switch r.tables->Array.get(j) {
1007
+ | Some(t) =>
1008
+ let left = await countTable(t)
1009
+ if left != 0 {
1010
+ refilled->Array.push((t, left))
1011
+ }
1012
+ | None => ()
1013
+ }
1014
+ }
1015
+ for j in 0 to r.bucketCounts->Array.length - 1 {
1016
+ switch r.bucketCounts->Array.get(j) {
1017
+ | Some((b, _)) =>
1018
+ let left = await countBucket(b)
1019
+ if left != 0 {
1020
+ refilled->Array.push((b, left))
1021
+ }
1022
+ | None => ()
1023
+ }
1024
+ }
1025
+ // Per-store confirmation, so "every uploaded object is gone" is an
1026
+ // observed fact rather than an inference from a global total.
1027
+ for j in 0 to r.storeCounts->Array.length - 1 {
1028
+ switch r.storeCounts->Array.get(j) {
1029
+ | Some((s, _)) =>
1030
+ let left = await countBucket(s.bucketName, ~prefix=`${s.keyPrefix}/`)
1031
+ if left != 0 {
1032
+ refilled->Array.push((`${s.qualified} (${s.bucketName}/${s.keyPrefix}/)`, left))
1033
+ }
1034
+ Console.log(
1035
+ ` verified empty: ${s.qualified} — ${left->Int.toString} object(s) remain under ` ++
1036
+ `${s.bucketName}/${s.keyPrefix}/`,
1037
+ )
1038
+ | None => ()
1039
+ }
1040
+ }
1041
+ | None => ()
1042
+ }
1043
+ }
1044
+ Ok(refilled)
1045
+ } catch {
1046
+ | Seed.Failed(message) => Error(message)
1047
+ | exn =>
1048
+ Error(
1049
+ `the wipe failed: ${exn
1050
+ ->JsExn.fromException
1051
+ ->Option.flatMap(JsExn.message)
1052
+ ->Option.getOr("unknown error")}`,
1053
+ )
1054
+ }
1055
+
1056
+ // Recycle while still held, so the container that eventually serves
1057
+ // traffic is created after the stores were emptied — then hand the stack
1058
+ // back. Both are best-effort and report rather than raise: they run on the
1059
+ // abort path too, where throwing would bury the reason the reset failed.
1060
+ let warnings = if held->Array.length > 0 {
1061
+ Seed.Runner.heading(`Recycling ${held->Array.length->Int.toString} runtime(s) …`)
1062
+ let recycled = await Quiesce.recycle(~client=lambdaClient, ~held)
1063
+ let released = await Quiesce.release(~client=lambdaClient, ~held)
1064
+ Array.concat(recycled, released)
1065
+ } else {
1066
+ []
1067
+ }
1068
+ if warnings->Array.length > 0 {
1069
+ Console.error("")
1070
+ warnings->Array.forEach(w => Console.error(` warning: ${w}`))
1071
+ }
1072
+
1073
+ switch outcome {
1074
+ | Error(message) => throw(Seed.Failed(message))
1075
+ | Ok(refilled) if refilled->Array.length > 0 =>
1076
+ throw(Seed.Failed(refillMessage(~refilled, ~heldCount=held->Array.length)))
1077
+ | Ok(_) => ()
1078
+ }
1079
+
1080
+ Console.log("")
1081
+ Console.log(`Reset complete — the selected scope of "${stack}" reads empty and is re-seedable.`)
1082
+ NodeProcess.exit(0)
1083
+ } catch {
1084
+ | Seed.Failed(message) =>
1085
+ Seed.Prompt.close()
1086
+ Console.error("")
1087
+ Console.error(`Reset aborted — ${message}`)
1088
+ NodeProcess.exit(1)
1089
+ | exn =>
1090
+ Seed.Prompt.close()
1091
+ Console.error("")
1092
+ Console.error("Reset aborted with an unexpected error:")
1093
+ Console.error(exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("unknown"))
1094
+ NodeProcess.exit(1)
1095
+ }
1096
+ }
1097
+ go()->ignore
1098
+ }