@zabaca/zbc 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +117 -6
- package/package.json +5 -2
- package/src/commands/add.ts +13 -0
- package/src/commands/apply.ts +33 -9
- package/src/commands/destroy.ts +1 -1
- package/src/commands/init.ts +1 -0
- package/src/engine/apply.ts +110 -22
- package/src/engine/destroy.ts +183 -14
- package/src/engine/discover.ts +1 -1
- package/src/engine/resolve.ts +113 -14
- package/src/utils/copy-template.ts +10 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +3 -1
- package/templates/apps/inbox/tsconfig.json +3 -1
- package/templates/apps/inbox/worker/api.ts +197 -0
- package/templates/apps/inbox/worker/commands.ts +299 -0
- package/templates/apps/inbox/worker/inbox-do.ts +53 -10
- package/templates/apps/inbox/worker/index.ts +15 -202
- package/templates/apps/inbox/worker/mcp.ts +49 -100
- package/templates/infra/modules/cloudflare/index.ts +29 -73
- package/templates/infra/modules/cloudflare-access/index.ts +3 -3
- package/templates/infra/modules/cloudflare-api/index.ts +144 -32
- package/templates/infra/modules/cloudflare-api/registry.json +1 -1
- package/templates/infra/modules/cloudflare-email/index.ts +103 -144
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-token/index.ts +10 -32
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
- package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
- package/templates/infra/modules/fly/index.ts +17 -42
- package/templates/infra/modules/fly/registry.json +1 -1
- package/templates/infra/modules/host-file/index.ts +6 -7
- package/templates/infra/modules/provision-core/index.ts +21 -15
- package/templates/infra/modules/r2/index.ts +40 -71
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/modules/remote-provision/index.ts +1 -3
- package/templates/infra/modules/turso/index.ts +2 -15
- package/templates/infra/modules/vm-provision/index.ts +10 -3
- package/templates/infra/src/context.ts +115 -0
- package/templates/infra/src/define-module.ts +41 -2
- package/templates/infra/src/index.ts +11 -1
- package/templates/infra/src/types.ts +85 -3
- package/src/commands/add-registry.test.ts +0 -92
- package/src/commands/secret.test.ts +0 -717
- package/src/commands/vendor-mode.test.ts +0 -183
- package/src/infra-types.ts +0 -38
- package/src/utils/subtree.test.ts +0 -127
- package/templates/apps/inbox/worker/send-op.ts +0 -174
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,117 @@ only add or fix things are described by their `release(cli): @zabaca/zbc <x.y.z>
|
|
|
5
5
|
commit message and the PRs it names; this file exists for the ones a consumer
|
|
6
6
|
has to read before upgrading.
|
|
7
7
|
|
|
8
|
+
## 0.14.0
|
|
9
|
+
|
|
10
|
+
### An import naming an instance the environment does not contain is now a hard error
|
|
11
|
+
|
|
12
|
+
**If an instance file imports an instance whose own file is missing from the
|
|
13
|
+
environment directory — or does not `export default` it — `zbc apply` now fails
|
|
14
|
+
instead of running.** The message names both:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
Instance "web" imports "main-db", which is not in packages/infra/environments/production
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Before, this was two silent shrugs that compounded. The dependency sort dropped
|
|
21
|
+
the edge, so the importer could run first, and the apply loop then wrote
|
|
22
|
+
`undefined` into the context under that name. What the operator saw was a module
|
|
23
|
+
reporting a missing OUTPUT — "instance main-db doesn't emit databaseUrl" — for an
|
|
24
|
+
instance that was never there at all, which sends the reader to the wrong file.
|
|
25
|
+
No environment that applies today is affected: every import it resolves is one
|
|
26
|
+
the engine already found.
|
|
27
|
+
|
|
28
|
+
`zbc destroy` deliberately does **not** enforce this. An environment whose graph
|
|
29
|
+
has gone bad is exactly the one you need to be able to tear down, and refusing
|
|
30
|
+
there would strand every resource in it; destroy never needed the missing
|
|
31
|
+
instance's outputs, so the edge is skipped as before.
|
|
32
|
+
|
|
33
|
+
### `zbc destroy` may apply an imported instance, when a destroy asks for its output
|
|
34
|
+
|
|
35
|
+
A `destroy` used to receive `imports: {}` — the engine refused to look anything
|
|
36
|
+
up, on the theory that the imported instance might already be gone. Modules
|
|
37
|
+
worked around it: `cloudflare`'s destroy carried a swallowed catch around its
|
|
38
|
+
`apiToken` reference and fell back to a `CLOUDFLARE_API_TOKEN` in
|
|
39
|
+
`secrets.yaml`, which is a second copy of a credential `cloudflare-token` mints
|
|
40
|
+
fresh on every apply and never persists.
|
|
41
|
+
|
|
42
|
+
Now `ctx.output` answers during a destroy, and the engine applies the referenced
|
|
43
|
+
instance on demand to answer it — once per run, in dependency order, logged:
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
→ applying deploy-token (needed by web's destroy)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Opt-by-use:** a destroy that never reads an import applies nothing. **But if
|
|
50
|
+
your worker instance declares `apiToken: { from, output }`, its teardown now
|
|
51
|
+
resolves that reference rather than reading `secrets.yaml`** — so the imported
|
|
52
|
+
instance's apply has to succeed for the destroy to proceed. Removing a
|
|
53
|
+
now-unused `CLOUDFLARE_API_TOKEN` from an environment that only kept it for
|
|
54
|
+
teardown is safe; keeping it costs nothing.
|
|
55
|
+
|
|
56
|
+
Two limits worth knowing, both deliberate:
|
|
57
|
+
|
|
58
|
+
- **A targeted `zbc destroy <env> <instance>` refuses to do this** and says so.
|
|
59
|
+
A full-environment run tears down whatever it applied later in the same pass
|
|
60
|
+
(an import sorts before its importer, so it sorts after it in reverse); a
|
|
61
|
+
targeted run has no such pass, and the target filter exists precisely because
|
|
62
|
+
a thing's dependencies are shared infra you did not ask to touch. Provisioning
|
|
63
|
+
that infra and walking away is the same mistake with the sign flipped. Run the
|
|
64
|
+
full destroy, or apply the imported instance yourself first.
|
|
65
|
+
- **If a full destroy aborts partway, something it applied on demand can outlive
|
|
66
|
+
the run.** It was going to be torn down later in that same pass; the pass
|
|
67
|
+
stopped. Re-running `zbc destroy <env>` finishes the job.
|
|
68
|
+
|
|
69
|
+
A `destroy` that wraps `ctx.output` in a `try`/`catch` — the shape the old
|
|
70
|
+
`cloudflare` destroy had, so the shape a fork most likely copied — swallows the
|
|
71
|
+
engine's request to apply the import, gets nothing, and takes its fallback. The
|
|
72
|
+
engine cannot stop that (nothing in JavaScript survives a bare `catch`), so it
|
|
73
|
+
notices afterwards and prints a warning naming the instance.
|
|
74
|
+
|
|
75
|
+
### An imported output that is an empty string, or not a string, is now refused
|
|
76
|
+
|
|
77
|
+
`cloudflare-api`'s `resolveRef` — the reviewed one, used for every Cloudflare
|
|
78
|
+
credential — has always required a non-empty string. `cloudflare`'s
|
|
79
|
+
`workerVars`/`workerSecrets`/`r2Bindings` and `cloudflare-email`'s
|
|
80
|
+
`workerName` accepted an empty one, and `fly`'s `flySecrets` accepted anything
|
|
81
|
+
at all and ran it through `String()`.
|
|
82
|
+
They now all use the strict reading: an output that is `''`, a number, or a
|
|
83
|
+
boolean fails by name instead of reaching a provider as an empty credential or
|
|
84
|
+
the text `"true"`.
|
|
85
|
+
|
|
86
|
+
**If you reference an output whose empty value is meaningful** — the `fly`
|
|
87
|
+
module's `ipv4`/`ipv6` are `''` when no address is allocated — that reference
|
|
88
|
+
now fails. No instance in this repo does. A module that genuinely wants the
|
|
89
|
+
empty answer asks for it: `ctx.output(ref, field, { allowBlank: true })`, which
|
|
90
|
+
is what `provision-core`'s `volatileEnvFrom` does, since "nothing to mint" is a
|
|
91
|
+
real answer there.
|
|
92
|
+
|
|
93
|
+
### Copy-mode repos: `zbc add` now backfills missing `packages/infra/src/` files
|
|
94
|
+
|
|
95
|
+
Three modules — `fly`, `cloudflare-api` and `provision-core` — now import
|
|
96
|
+
`../../src/context`, a file that did not exist before this release. In a
|
|
97
|
+
copy-mode repo `packages/infra/src/` is written once, by `zbc init`, so a repo
|
|
98
|
+
scaffolded on an older CLI has whatever `src/` shipped *then*, and `zbc add fly`
|
|
99
|
+
would have installed a module importing a file that is not in the tree.
|
|
100
|
+
|
|
101
|
+
`zbc add` now copies any missing engine file into `packages/infra/src/` before
|
|
102
|
+
installing a module, skipping every file you already have. **If you already ran
|
|
103
|
+
`zbc add` on 0.14.0 and got an unresolvable `../../src/context` import, re-run
|
|
104
|
+
the same `zbc add` and it will be written.** Subtree consumers were never
|
|
105
|
+
affected — `zbc update` refreshes `vendor/zbc/src` wholesale.
|
|
106
|
+
|
|
107
|
+
### `ApplyContext` gained `secret()` and `output()`; the three fields are unchanged
|
|
108
|
+
|
|
109
|
+
`secrets`, `imports` and `projectRoot` are still there and still mean what they
|
|
110
|
+
meant. One reading changed with them: a secrets.yaml key written `KEY:` with
|
|
111
|
+
nothing after it parses to `null`, and `ctx.secret` now treats that as the blank
|
|
112
|
+
placeholder it looks like (accepted under `allowBlank`, refused as empty
|
|
113
|
+
otherwise) rather than as a `null` handed to a module expecting a string. A custom module reading them directly keeps working. The two methods are
|
|
114
|
+
where the rules now live — "what is this secret", "what did the instance I
|
|
115
|
+
imported emit" — and a module that adopts them gets the engine's messages
|
|
116
|
+
instead of its own. `defineModule` supplies them, so a module body may assume
|
|
117
|
+
they exist whoever called `apply`.
|
|
118
|
+
|
|
8
119
|
## 0.13.0
|
|
9
120
|
|
|
10
121
|
### `WALGIT_PUBLIC` opens the host for `true`, not only for `1` — this widens access
|
|
@@ -27,12 +138,12 @@ rather than silently.
|
|
|
27
138
|
|
|
28
139
|
What each value does now:
|
|
29
140
|
|
|
30
|
-
| `WALGIT_PUBLIC`
|
|
31
|
-
|
|
|
32
|
-
| `1`
|
|
33
|
-
| `true`
|
|
34
|
-
| unset
|
|
35
|
-
| anything else (`yes`, `on`, `TRUE`) | closed
|
|
141
|
+
| `WALGIT_PUBLIC` | before | after |
|
|
142
|
+
| ----------------------------------- | ------------------------------------------ | ------------------ |
|
|
143
|
+
| `1` | open | open (unchanged) |
|
|
144
|
+
| `true` | **closed**, while `/llms.txt` claimed open | **open** |
|
|
145
|
+
| unset | closed | closed (unchanged) |
|
|
146
|
+
| anything else (`yes`, `on`, `TRUE`) | closed | closed (unchanged) |
|
|
36
147
|
|
|
37
148
|
The widening covers `true` only. The accepted vocabulary is unchanged — it is
|
|
38
149
|
still exactly what `flagEnabled` has always taken — so an unrecognised value
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zabaca/zbc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Zabaca stack CLI — scaffold and deploy infrastructure",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
"bin",
|
|
13
13
|
"src",
|
|
14
14
|
"templates",
|
|
15
|
+
"!src/**/*.test.ts",
|
|
16
|
+
"!src/engine/fixtures.ts",
|
|
15
17
|
"!templates/**/*.test.ts",
|
|
16
18
|
"!templates/**/.wrangler",
|
|
17
19
|
"!templates/**/.DS_Store"
|
|
@@ -29,6 +31,7 @@
|
|
|
29
31
|
"yaml": "^2.8.3"
|
|
30
32
|
},
|
|
31
33
|
"devDependencies": {
|
|
32
|
-
"@types/bun": "^1.3.12"
|
|
34
|
+
"@types/bun": "^1.3.12",
|
|
35
|
+
"zod": "^3.24.0"
|
|
33
36
|
}
|
|
34
37
|
}
|
package/src/commands/add.ts
CHANGED
|
@@ -178,6 +178,19 @@ async function installModule(
|
|
|
178
178
|
|
|
179
179
|
console.log(`zbc add: ${moduleName}`)
|
|
180
180
|
|
|
181
|
+
// Fill in any engine file this repo does not have yet. `zbc init` lays down
|
|
182
|
+
// packages/infra/src/ once, at scaffold time, and every module imports
|
|
183
|
+
// '../../src/define-module' from it — so a repo initialized on an older CLI
|
|
184
|
+
// has whatever src/ shipped THEN, and a module added today can import a file
|
|
185
|
+
// that does not exist in its tree. `context.ts` is the first such addition:
|
|
186
|
+
// `fly`, `cloudflare-api` and `provision-core` import it. Skip-if-exists, so
|
|
187
|
+
// a consumer's own edits to the files they already have are untouched.
|
|
188
|
+
// `../../src` from the module directory is literally the path its own import
|
|
189
|
+
// statements resolve, in either layout.
|
|
190
|
+
await copyTemplateDir(path.resolve(source.dir, '../../src'), path.join(infraDir, 'src'), {
|
|
191
|
+
excludeTests: true,
|
|
192
|
+
})
|
|
193
|
+
|
|
181
194
|
await fs.mkdir(destDir, { recursive: true })
|
|
182
195
|
for (const f of registry.files ?? []) {
|
|
183
196
|
await copyTemplateFile(path.join(source.dir, f.path), path.join(destDir, f.path))
|
package/src/commands/apply.ts
CHANGED
|
@@ -20,6 +20,11 @@ export const applyCommand = defineCommand({
|
|
|
20
20
|
description: 'Specific instance to apply (+ its dependencies)',
|
|
21
21
|
required: false,
|
|
22
22
|
},
|
|
23
|
+
only: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Comma-separated instances to apply (+ their dependencies)',
|
|
26
|
+
required: false,
|
|
27
|
+
},
|
|
23
28
|
},
|
|
24
29
|
async run({ args }) {
|
|
25
30
|
const projectRoot = await findProjectRoot()
|
|
@@ -32,16 +37,35 @@ export const applyCommand = defineCommand({
|
|
|
32
37
|
process.exit(1)
|
|
33
38
|
}
|
|
34
39
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
// `--only a,b` is the positional's plural. Empty entries are dropped so a
|
|
41
|
+
// trailing comma — the shape a shell loop produces when its list is empty —
|
|
42
|
+
// does not become an instance named "", which would fail as "not found"
|
|
43
|
+
// and read as a bug in the environment rather than in the caller.
|
|
44
|
+
const only = (args.only ?? '')
|
|
45
|
+
.split(',')
|
|
46
|
+
.map((name) => name.trim())
|
|
47
|
+
.filter((name) => name.length > 0)
|
|
48
|
+
|
|
49
|
+
if (args.instance && only.length > 0) {
|
|
50
|
+
console.error('Pass either an instance positional or --only, not both.')
|
|
51
|
+
process.exit(1)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// An `--only` that was given but resolved to nothing is a caller that meant
|
|
55
|
+
// to scope and produced an empty list. Applying the whole environment there
|
|
56
|
+
// is the opposite of what it asked for, so refuse rather than widen.
|
|
57
|
+
if (args.only !== undefined && only.length === 0) {
|
|
58
|
+
console.error('--only was given but named no instances.')
|
|
59
|
+
process.exit(1)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const target = args.instance ?? (only.length > 0 ? only : undefined)
|
|
63
|
+
|
|
64
|
+
const envDir = path.join(projectRoot, 'packages', 'infra', 'environments', args.env)
|
|
42
65
|
|
|
43
|
-
|
|
44
|
-
|
|
66
|
+
const scope = target ? ` (instance: ${[target].flat().join(', ')})` : ''
|
|
67
|
+
console.log(`Applying ${args.env}${scope}...`)
|
|
68
|
+
await applyEnvironment(projectRoot, envDir, target)
|
|
45
69
|
console.log('\nDone.')
|
|
46
70
|
},
|
|
47
71
|
})
|
package/src/commands/destroy.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { destroyEnvironment } from '../engine/destroy'
|
|
|
7
7
|
export const destroyCommand = defineCommand({
|
|
8
8
|
meta: {
|
|
9
9
|
name: 'destroy',
|
|
10
|
-
description: 'Tear down
|
|
10
|
+
description: 'Tear down every instance that defines destroy (reverse dependency order)',
|
|
11
11
|
},
|
|
12
12
|
args: {
|
|
13
13
|
env: {
|
package/src/commands/init.ts
CHANGED
|
@@ -135,6 +135,7 @@ export const initCommand = defineCommand({
|
|
|
135
135
|
const infraDest = path.join(cwd, 'packages/infra')
|
|
136
136
|
await copyTemplateDir(path.join(tplRoot, 'infra'), infraDest, {
|
|
137
137
|
vars,
|
|
138
|
+
excludeTests: true,
|
|
138
139
|
exclude: ['modules', 'README.md', ...(args.subtree ? ['src'] : [])],
|
|
139
140
|
})
|
|
140
141
|
|
package/src/engine/apply.ts
CHANGED
|
@@ -1,37 +1,125 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createApplyContext } from '../../templates/infra/src/context'
|
|
2
|
+
import { legacyConfigEphemeral } from '../../templates/infra/src/define-module'
|
|
3
|
+
import type { ApplyContext, ModuleInstance } from '../../templates/infra/src/types'
|
|
2
4
|
import { discoverInstances } from './discover'
|
|
3
|
-
import { resolveOrder } from './resolve'
|
|
5
|
+
import { assertEphemeralDestroyable, isEphemeral, resolveOrder } from './resolve'
|
|
4
6
|
import { loadSecrets } from './secrets'
|
|
5
7
|
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const outputs = new Map<string, unknown>()
|
|
8
|
+
export interface ApplyInstancesOptions {
|
|
9
|
+
secrets: Record<string, string>
|
|
10
|
+
projectRoot: string
|
|
11
|
+
/** Apply only these instances and their transitive imports. */
|
|
12
|
+
target?: string | string[]
|
|
13
|
+
/** Where the instances came from, for error messages. */
|
|
14
|
+
envLabel?: string
|
|
15
|
+
}
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Apply one instance and record its outputs.
|
|
19
|
+
*
|
|
20
|
+
* Split out so the destroy path can reach it: a `destroy` that reads an
|
|
21
|
+
* imported instance's output needs that instance applied, and the alternative
|
|
22
|
+
* — every module carrying a fallback for the outputs it cannot see — is what
|
|
23
|
+
* this replaced.
|
|
24
|
+
*/
|
|
25
|
+
export async function applyInstance(
|
|
26
|
+
instance: ModuleInstance,
|
|
27
|
+
opts: { secrets: Record<string, string>; projectRoot: string },
|
|
28
|
+
outputs: Map<string, unknown>,
|
|
29
|
+
): Promise<unknown> {
|
|
30
|
+
const ctx = instanceContext(instance, opts, outputs)
|
|
21
31
|
|
|
22
|
-
|
|
32
|
+
const validatedConfig = instance._definition.configSchema.parse(instance.config)
|
|
23
33
|
|
|
24
|
-
|
|
34
|
+
const result = await instance._definition.apply(validatedConfig, ctx)
|
|
25
35
|
|
|
26
|
-
|
|
36
|
+
instance._definition.outputsSchema.parse(result)
|
|
37
|
+
|
|
38
|
+
outputs.set(instance.name, result)
|
|
39
|
+
return result
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The context for one instance on the apply path: its imports are whatever the
|
|
44
|
+
* instances ahead of it in the sort emitted, which is the whole of the ordering
|
|
45
|
+
* guarantee.
|
|
46
|
+
*/
|
|
47
|
+
function instanceContext(
|
|
48
|
+
instance: ModuleInstance,
|
|
49
|
+
opts: { secrets: Record<string, string>; projectRoot: string },
|
|
50
|
+
outputs: Map<string, unknown>,
|
|
51
|
+
): ApplyContext {
|
|
52
|
+
const importOutputs: Record<string, unknown> = {}
|
|
53
|
+
for (const dep of instance.imports) {
|
|
54
|
+
importOutputs[dep.name] = outputs.get(dep.name)
|
|
55
|
+
}
|
|
56
|
+
return createApplyContext({
|
|
57
|
+
secrets: opts.secrets,
|
|
58
|
+
imports: importOutputs,
|
|
59
|
+
projectRoot: opts.projectRoot,
|
|
60
|
+
})
|
|
61
|
+
}
|
|
27
62
|
|
|
28
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Destroy an ephemeral instance so the apply that follows starts from nothing.
|
|
65
|
+
*
|
|
66
|
+
* The engine adds NO catch of its own. The three modules that used to do this
|
|
67
|
+
* inline each swallowed the failure — `catch {}` twice, `allowFailure: true`
|
|
68
|
+
* once — which turned "the delete was refused" into "the resource is clean",
|
|
69
|
+
* and the resource then persisted across every preview run. Each of those
|
|
70
|
+
* modules' own `destroy` treats an absent resource as success, so nothing here
|
|
71
|
+
* needs a catch to survive the first-ever apply.
|
|
72
|
+
*
|
|
73
|
+
* What a module's OWN `destroy` swallows is still swallowed — `r2`'s logs a
|
|
74
|
+
* refused delete and returns, deliberately, so that `zbc destroy` does not abort
|
|
75
|
+
* the whole environment on one non-empty bucket. See its `destroy` doc: an
|
|
76
|
+
* ephemeral `r2` instance is only as clean as the bucket the app left behind.
|
|
77
|
+
*/
|
|
78
|
+
async function destroyEphemeral(
|
|
79
|
+
instance: ModuleInstance,
|
|
80
|
+
opts: { secrets: Record<string, string>; projectRoot: string },
|
|
81
|
+
outputs: Map<string, unknown>,
|
|
82
|
+
): Promise<void> {
|
|
83
|
+
// `assertEphemeralDestroyable` has already run over the whole graph.
|
|
84
|
+
const destroy = instance._definition.destroy!
|
|
85
|
+
const validatedConfig = instance._definition.configSchema.parse(instance.config)
|
|
86
|
+
await destroy(validatedConfig, instanceContext(instance, opts, outputs))
|
|
87
|
+
}
|
|
29
88
|
|
|
30
|
-
|
|
89
|
+
/** The graph half of `zbc apply`: pure over in-memory instances, no I/O of its own. */
|
|
90
|
+
export async function applyInstances(
|
|
91
|
+
instances: ModuleInstance[],
|
|
92
|
+
opts: ApplyInstancesOptions,
|
|
93
|
+
): Promise<Map<string, unknown>> {
|
|
94
|
+
const sorted = resolveOrder(instances, { target: opts.target, envLabel: opts.envLabel })
|
|
95
|
+
assertEphemeralDestroyable(sorted)
|
|
96
|
+
const outputs = new Map<string, unknown>()
|
|
31
97
|
|
|
32
|
-
|
|
98
|
+
for (const instance of sorted) {
|
|
99
|
+
console.log(`\n→ ${instance.moduleName}:${instance.name}`)
|
|
100
|
+
if (isEphemeral(instance)) {
|
|
101
|
+
if (legacyConfigEphemeral(instance.moduleName, instance.config)) {
|
|
102
|
+
console.log(
|
|
103
|
+
` ⚠ ${instance.name}: config.ephemeral is deprecated — set ephemeral: true on the instance`,
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
console.log(` ephemeral: destroying before re-apply`)
|
|
107
|
+
await destroyEphemeral(instance, opts, outputs)
|
|
108
|
+
}
|
|
109
|
+
await applyInstance(instance, opts, outputs)
|
|
33
110
|
console.log(`✓ ${instance.moduleName}:${instance.name} applied`)
|
|
34
111
|
}
|
|
35
112
|
|
|
36
113
|
return outputs
|
|
37
114
|
}
|
|
115
|
+
|
|
116
|
+
/** The I/O half: discover the environment's instances, decrypt its secrets, apply. */
|
|
117
|
+
export async function applyEnvironment(
|
|
118
|
+
projectRoot: string,
|
|
119
|
+
envDir: string,
|
|
120
|
+
target?: string | string[],
|
|
121
|
+
): Promise<Map<string, unknown>> {
|
|
122
|
+
const instances = await discoverInstances(envDir)
|
|
123
|
+
const secrets = await loadSecrets(envDir)
|
|
124
|
+
return applyInstances(instances, { secrets, projectRoot, target, envLabel: envDir })
|
|
125
|
+
}
|
package/src/engine/destroy.ts
CHANGED
|
@@ -1,15 +1,55 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createApplyContext } from '../../templates/infra/src/context'
|
|
2
|
+
import type {
|
|
3
|
+
ApplyContext,
|
|
4
|
+
ModuleInstance,
|
|
5
|
+
OutputOptions,
|
|
6
|
+
OutputRef,
|
|
7
|
+
} from '../../templates/infra/src/types'
|
|
8
|
+
import { applyInstance } from './apply'
|
|
2
9
|
import { discoverInstances } from './discover'
|
|
3
10
|
import { resolveOrder } from './resolve'
|
|
4
11
|
import { loadSecrets } from './secrets'
|
|
5
12
|
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
13
|
+
export interface DestroyInstancesOptions {
|
|
14
|
+
secrets: Record<string, string>
|
|
15
|
+
projectRoot: string
|
|
16
|
+
/** Destroy only this instance — see the comment on the filter below. */
|
|
17
|
+
target?: string
|
|
18
|
+
/** Where the instances came from, for error messages. */
|
|
19
|
+
envLabel?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Raised by a destroy context's `output` for an import that has not been
|
|
24
|
+
* applied yet in this run. `destroyInstances` catches it, applies that
|
|
25
|
+
* instance, and re-runs the destroy.
|
|
26
|
+
*
|
|
27
|
+
* Re-running is what buys a SYNCHRONOUS `ctx.output` — the same call, with the
|
|
28
|
+
* same three error messages, in `apply` and in `destroy` — and it is safe for
|
|
29
|
+
* exactly one reason, which every module in core already honours and which this
|
|
30
|
+
* note is here to keep true: **a destroy resolves everything it reads from
|
|
31
|
+
* imports before it performs its first side effect.** The credential is the
|
|
32
|
+
* first line of every `destroy` in core. A module that deleted something and
|
|
33
|
+
* then asked for an import would delete it twice.
|
|
34
|
+
*
|
|
35
|
+
* The other way to break it is to CATCH this — the shape the old `cloudflare`
|
|
36
|
+
* destroy had, and therefore the shape a consumer's fork most likely copied.
|
|
37
|
+
* Nothing in JavaScript survives a bare `catch`, so instead the engine notices
|
|
38
|
+
* afterwards and says so: see `warnIfSignalSwallowed`.
|
|
39
|
+
*/
|
|
40
|
+
class ImportNotYetApplied extends Error {
|
|
41
|
+
constructor(readonly instanceName: string) {
|
|
42
|
+
super(`import "${instanceName}" is not applied yet`)
|
|
43
|
+
this.name = 'ImportNotYetApplied'
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The graph half of `zbc destroy`: pure over in-memory instances. */
|
|
48
|
+
export async function destroyInstances(
|
|
49
|
+
instances: ModuleInstance[],
|
|
50
|
+
opts: DestroyInstancesOptions,
|
|
10
51
|
): Promise<void> {
|
|
11
|
-
const
|
|
12
|
-
const sorted = resolveOrder(instances)
|
|
52
|
+
const sorted = resolveOrder(instances, { envLabel: opts.envLabel, assertImports: false })
|
|
13
53
|
let reversed = [...sorted].reverse()
|
|
14
54
|
|
|
15
55
|
// Targeted destroy: tear down ONLY the named instance. Unlike apply, we do
|
|
@@ -17,17 +57,19 @@ export async function destroyEnvironment(
|
|
|
17
57
|
// usually shared infra you don't want destroyed alongside it. Without this filter,
|
|
18
58
|
// `zbc destroy <env> <instance>` silently ignored the instance arg and
|
|
19
59
|
// destroyed the entire environment.
|
|
20
|
-
if (target) {
|
|
21
|
-
const found = reversed.find((i) => i.name === target)
|
|
60
|
+
if (opts.target) {
|
|
61
|
+
const found = reversed.find((i) => i.name === opts.target)
|
|
22
62
|
if (!found) {
|
|
23
63
|
throw new Error(
|
|
24
|
-
`Instance "${target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
64
|
+
`Instance "${opts.target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
25
65
|
)
|
|
26
66
|
}
|
|
27
67
|
reversed = [found]
|
|
28
68
|
}
|
|
29
69
|
|
|
30
|
-
|
|
70
|
+
// Outputs of instances applied on demand, shared across the whole run: a
|
|
71
|
+
// credential minted for one teardown is the same credential for the next.
|
|
72
|
+
const outputs = new Map<string, unknown>()
|
|
31
73
|
|
|
32
74
|
for (const instance of reversed) {
|
|
33
75
|
const { destroy } = instance._definition
|
|
@@ -36,14 +78,141 @@ export async function destroyEnvironment(
|
|
|
36
78
|
continue
|
|
37
79
|
}
|
|
38
80
|
|
|
39
|
-
const ctx: ApplyContext = { secrets, imports: {}, projectRoot }
|
|
40
|
-
|
|
41
81
|
const validatedConfig = instance._definition.configSchema.parse(instance.config)
|
|
42
82
|
|
|
43
83
|
console.log(`\n→ ${instance.moduleName}:${instance.name}`)
|
|
44
84
|
|
|
45
|
-
|
|
85
|
+
// On-demand apply is a FULL-environment privilege. In that run whatever it
|
|
86
|
+
// applies is guaranteed to be torn down later in the same pass: an import
|
|
87
|
+
// sorts before its importer, so it sorts after it in reverse. A targeted
|
|
88
|
+
// destroy has no such pass — it would provision shared infra and walk away.
|
|
89
|
+
const ctx = destroyContext(instance, opts, outputs, { onDemand: !opts.target })
|
|
90
|
+
|
|
91
|
+
// One extra pass per import, at most: each retry applies an instance that
|
|
92
|
+
// was not applied before, and the set of imports is finite.
|
|
93
|
+
for (;;) {
|
|
94
|
+
try {
|
|
95
|
+
await destroy(validatedConfig, ctx.value)
|
|
96
|
+
break
|
|
97
|
+
} catch (err) {
|
|
98
|
+
if (!(err instanceof ImportNotYetApplied)) throw err
|
|
99
|
+
await ctx.provide(err.instanceName)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
ctx.warnIfSignalSwallowed()
|
|
46
104
|
|
|
47
105
|
console.log(`✓ ${instance.moduleName}:${instance.name} destroyed`)
|
|
48
106
|
}
|
|
49
107
|
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The context a `destroy` gets: the same two methods, with `output` reporting
|
|
111
|
+
* an import it can still fetch rather than failing on one the engine used to
|
|
112
|
+
* refuse to look up at all (it passed `imports: {}`, and `cloudflare` carried a
|
|
113
|
+
* swallowed catch and a secrets.yaml fallback to work around it).
|
|
114
|
+
*
|
|
115
|
+
* Opt-by-use: a destroy that never calls `output` applies nothing.
|
|
116
|
+
*/
|
|
117
|
+
function destroyContext(
|
|
118
|
+
instance: ModuleInstance,
|
|
119
|
+
opts: DestroyInstancesOptions,
|
|
120
|
+
outputs: Map<string, unknown>,
|
|
121
|
+
mode: { onDemand: boolean },
|
|
122
|
+
) {
|
|
123
|
+
const declared = new Map(instance.imports.map((dep) => [dep.name, dep]))
|
|
124
|
+
const importOutputs: Record<string, unknown> = {}
|
|
125
|
+
for (const dep of instance.imports) {
|
|
126
|
+
if (outputs.has(dep.name)) importOutputs[dep.name] = outputs.get(dep.name)
|
|
127
|
+
}
|
|
128
|
+
/** Imports this destroy asked for. Compared against what was provided, below. */
|
|
129
|
+
const signalled = new Set<string>()
|
|
130
|
+
|
|
131
|
+
const base = createApplyContext({
|
|
132
|
+
secrets: opts.secrets,
|
|
133
|
+
imports: importOutputs,
|
|
134
|
+
projectRoot: opts.projectRoot,
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
const value: ApplyContext = {
|
|
138
|
+
...base,
|
|
139
|
+
output(ref: OutputRef, field: string, outputOpts?: OutputOptions): string {
|
|
140
|
+
// `ref.output` is checked here too, so a half-written ref is reported as
|
|
141
|
+
// the typo it is instead of provisioning an instance and THEN failing.
|
|
142
|
+
if (ref.from && ref.output && declared.has(ref.from) && !(ref.from in importOutputs)) {
|
|
143
|
+
if (!mode.onDemand) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`${field} references instance "${ref.from}", whose outputs a targeted destroy will not create. ` +
|
|
146
|
+
`Run \`zbc destroy <env>\` for the whole environment, which applies "${ref.from}" only to tear ` +
|
|
147
|
+
`it down again, or apply "${ref.from}" yourself first.`,
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
signalled.add(ref.from)
|
|
151
|
+
throw new ImportNotYetApplied(ref.from)
|
|
152
|
+
}
|
|
153
|
+
return base.output(ref, field, outputOpts)
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Apply `name` (and whatever it imports) so the retry can resolve it. */
|
|
158
|
+
async function provide(name: string): Promise<void> {
|
|
159
|
+
const dep = declared.get(name)
|
|
160
|
+
// Both are unreachable through `value.output` above; a module that
|
|
161
|
+
// swallowed the signal and rethrew it could still get here, and a silent
|
|
162
|
+
// retry loop is worse than the original error.
|
|
163
|
+
if (!dep) throw new Error(`Cannot apply "${name}": it is not among ${instance.name}'s imports`)
|
|
164
|
+
if (name in importOutputs) throw new Error(`Import "${name}" was already applied`)
|
|
165
|
+
|
|
166
|
+
await ensureApplied(dep, `${instance.name}'s destroy`, opts, outputs)
|
|
167
|
+
importOutputs[name] = outputs.get(name)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A `destroy` that wraps `ctx.output` in a try/catch swallows the engine's
|
|
172
|
+
* signal, applies nothing, and takes its fallback branch — which is exactly
|
|
173
|
+
* the shape the old `cloudflare` destroy had, and therefore the shape a
|
|
174
|
+
* consumer's fork is most likely to be carrying. Silence there looks like
|
|
175
|
+
* success, so say it.
|
|
176
|
+
*/
|
|
177
|
+
function warnIfSignalSwallowed(): void {
|
|
178
|
+
for (const name of signalled) {
|
|
179
|
+
if (name in importOutputs) continue
|
|
180
|
+
console.log(
|
|
181
|
+
`⚠ ${instance.name}'s destroy asked for import "${name}" and then swallowed the error — ` +
|
|
182
|
+
`"${name}" was NOT applied, and whatever the destroy used instead is not its output.`,
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return { value, provide, warnIfSignalSwallowed }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Apply an instance and its transitive imports, once per run. */
|
|
191
|
+
async function ensureApplied(
|
|
192
|
+
instance: ModuleInstance,
|
|
193
|
+
neededBy: string,
|
|
194
|
+
opts: DestroyInstancesOptions,
|
|
195
|
+
outputs: Map<string, unknown>,
|
|
196
|
+
): Promise<void> {
|
|
197
|
+
if (outputs.has(instance.name)) return
|
|
198
|
+
// `neededBy` is the immediate asker, not the instance being destroyed: a
|
|
199
|
+
// transitive dependency is needed by the import that reads it, and saying
|
|
200
|
+
// otherwise points at a file that never mentions it.
|
|
201
|
+
for (const dep of instance.imports) {
|
|
202
|
+
await ensureApplied(dep, instance.name, opts, outputs)
|
|
203
|
+
}
|
|
204
|
+
console.log(`→ applying ${instance.name} (needed by ${neededBy})`)
|
|
205
|
+
await applyInstance(instance, opts, outputs)
|
|
206
|
+
console.log(`✓ ${instance.name} applied — this destroy created it; the run tears it down below`)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The I/O half: discover the environment's instances, decrypt its secrets, destroy. */
|
|
210
|
+
export async function destroyEnvironment(
|
|
211
|
+
projectRoot: string,
|
|
212
|
+
envDir: string,
|
|
213
|
+
target?: string,
|
|
214
|
+
): Promise<void> {
|
|
215
|
+
const instances = await discoverInstances(envDir)
|
|
216
|
+
const secrets = await loadSecrets(envDir)
|
|
217
|
+
await destroyInstances(instances, { secrets, projectRoot, target, envLabel: envDir })
|
|
218
|
+
}
|
package/src/engine/discover.ts
CHANGED