@zabaca/zbc 0.14.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/package.json +1 -1
- package/src/commands/apply.ts +33 -9
- package/src/commands/destroy.ts +1 -1
- package/src/engine/apply.ts +63 -14
- package/src/engine/resolve.ts +63 -9
- package/templates/CLAUDE.md +1 -1
- package/templates/infra/modules/cloudflare/index.ts +4 -3
- package/templates/infra/modules/cloudflare-token/index.ts +0 -2
- package/templates/infra/modules/fly/index.ts +0 -8
- package/templates/infra/modules/fly/registry.json +1 -1
- package/templates/infra/modules/r2/index.ts +9 -23
- package/templates/infra/modules/turso/index.ts +0 -11
- package/templates/infra/src/define-module.ts +33 -0
- package/templates/infra/src/types.ts +13 -0
package/package.json
CHANGED
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/engine/apply.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { createApplyContext } from '../../templates/infra/src/context'
|
|
2
|
-
import
|
|
2
|
+
import { legacyConfigEphemeral } from '../../templates/infra/src/define-module'
|
|
3
|
+
import type { ApplyContext, ModuleInstance } from '../../templates/infra/src/types'
|
|
3
4
|
import { discoverInstances } from './discover'
|
|
4
|
-
import { resolveOrder } from './resolve'
|
|
5
|
+
import { assertEphemeralDestroyable, isEphemeral, resolveOrder } from './resolve'
|
|
5
6
|
import { loadSecrets } from './secrets'
|
|
6
7
|
|
|
7
8
|
export interface ApplyInstancesOptions {
|
|
8
9
|
secrets: Record<string, string>
|
|
9
10
|
projectRoot: string
|
|
10
|
-
/** Apply only
|
|
11
|
-
target?: string
|
|
11
|
+
/** Apply only these instances and their transitive imports. */
|
|
12
|
+
target?: string | string[]
|
|
12
13
|
/** Where the instances came from, for error messages. */
|
|
13
14
|
envLabel?: string
|
|
14
15
|
}
|
|
@@ -26,25 +27,63 @@ export async function applyInstance(
|
|
|
26
27
|
opts: { secrets: Record<string, string>; projectRoot: string },
|
|
27
28
|
outputs: Map<string, unknown>,
|
|
28
29
|
): Promise<unknown> {
|
|
30
|
+
const ctx = instanceContext(instance, opts, outputs)
|
|
31
|
+
|
|
32
|
+
const validatedConfig = instance._definition.configSchema.parse(instance.config)
|
|
33
|
+
|
|
34
|
+
const result = await instance._definition.apply(validatedConfig, ctx)
|
|
35
|
+
|
|
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 {
|
|
29
52
|
const importOutputs: Record<string, unknown> = {}
|
|
30
53
|
for (const dep of instance.imports) {
|
|
31
54
|
importOutputs[dep.name] = outputs.get(dep.name)
|
|
32
55
|
}
|
|
33
|
-
|
|
34
|
-
const ctx = createApplyContext({
|
|
56
|
+
return createApplyContext({
|
|
35
57
|
secrets: opts.secrets,
|
|
36
58
|
imports: importOutputs,
|
|
37
59
|
projectRoot: opts.projectRoot,
|
|
38
60
|
})
|
|
61
|
+
}
|
|
39
62
|
|
|
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!
|
|
40
85
|
const validatedConfig = instance._definition.configSchema.parse(instance.config)
|
|
41
|
-
|
|
42
|
-
const result = await instance._definition.apply(validatedConfig, ctx)
|
|
43
|
-
|
|
44
|
-
instance._definition.outputsSchema.parse(result)
|
|
45
|
-
|
|
46
|
-
outputs.set(instance.name, result)
|
|
47
|
-
return result
|
|
86
|
+
await destroy(validatedConfig, instanceContext(instance, opts, outputs))
|
|
48
87
|
}
|
|
49
88
|
|
|
50
89
|
/** The graph half of `zbc apply`: pure over in-memory instances, no I/O of its own. */
|
|
@@ -53,10 +92,20 @@ export async function applyInstances(
|
|
|
53
92
|
opts: ApplyInstancesOptions,
|
|
54
93
|
): Promise<Map<string, unknown>> {
|
|
55
94
|
const sorted = resolveOrder(instances, { target: opts.target, envLabel: opts.envLabel })
|
|
95
|
+
assertEphemeralDestroyable(sorted)
|
|
56
96
|
const outputs = new Map<string, unknown>()
|
|
57
97
|
|
|
58
98
|
for (const instance of sorted) {
|
|
59
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
|
+
}
|
|
60
109
|
await applyInstance(instance, opts, outputs)
|
|
61
110
|
console.log(`✓ ${instance.moduleName}:${instance.name} applied`)
|
|
62
111
|
}
|
|
@@ -68,7 +117,7 @@ export async function applyInstances(
|
|
|
68
117
|
export async function applyEnvironment(
|
|
69
118
|
projectRoot: string,
|
|
70
119
|
envDir: string,
|
|
71
|
-
target?: string,
|
|
120
|
+
target?: string | string[],
|
|
72
121
|
): Promise<Map<string, unknown>> {
|
|
73
122
|
const instances = await discoverInstances(envDir)
|
|
74
123
|
const secrets = await loadSecrets(envDir)
|
package/src/engine/resolve.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
|
+
import { legacyConfigEphemeral } from '../../templates/infra/src/define-module'
|
|
1
2
|
import type { ModuleInstance } from '../../templates/infra/src/types'
|
|
2
3
|
|
|
3
4
|
export interface ResolveOptions {
|
|
4
|
-
/**
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Apply/destroy only these instances (plus, for apply, their transitive
|
|
7
|
+
* imports). A bare string is one of them.
|
|
8
|
+
*
|
|
9
|
+
* Plural because CI scopes a production apply to what a push actually
|
|
10
|
+
* touched, and a push routinely touches two — running the CLI once per name
|
|
11
|
+
* would re-decrypt the environment and re-apply the shared dependencies of
|
|
12
|
+
* each, turning a saving into a slower, noisier deploy.
|
|
13
|
+
*/
|
|
14
|
+
target?: string | string[]
|
|
6
15
|
/** Where the instances came from, for error messages. */
|
|
7
16
|
envLabel?: string
|
|
8
17
|
/**
|
|
@@ -24,14 +33,22 @@ export function resolveOrder(
|
|
|
24
33
|
|
|
25
34
|
let toProcess = instances
|
|
26
35
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
)
|
|
36
|
+
const targets = typeof opts.target === 'string' ? [opts.target] : (opts.target ?? [])
|
|
37
|
+
|
|
38
|
+
if (targets.length > 0) {
|
|
39
|
+
const selected = new Map<string, ModuleInstance>()
|
|
40
|
+
for (const target of targets) {
|
|
41
|
+
const targetInstance = instances.find((i) => i.name === target)
|
|
42
|
+
if (!targetInstance) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`Instance "${target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
// Union, not concatenation: two targets that share a dependency would
|
|
48
|
+
// otherwise list it twice, and the sort counts an instance's edges once.
|
|
49
|
+
for (const dep of collectTransitiveDeps(targetInstance)) selected.set(dep.name, dep)
|
|
33
50
|
}
|
|
34
|
-
toProcess =
|
|
51
|
+
toProcess = Array.from(selected.values())
|
|
35
52
|
}
|
|
36
53
|
|
|
37
54
|
return topologicalSort(toProcess)
|
|
@@ -59,6 +76,43 @@ function assertImportsDiscovered(instances: ModuleInstance[], envLabel?: string)
|
|
|
59
76
|
}
|
|
60
77
|
}
|
|
61
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Whether this instance is ephemeral.
|
|
81
|
+
*
|
|
82
|
+
* `ephemeral` is WRITTEN by `defineModule` — which a subtree consumer vendors at
|
|
83
|
+
* `vendor/zbc/src/` and moves with `zbc update` — and READ here, in the engine
|
|
84
|
+
* the npm CLI ships. The two version independently, so an instance built by a
|
|
85
|
+
* `define-module.ts` older than this CLI has no `ephemeral` property at all. The
|
|
86
|
+
* engine repeats the legacy fallback rather than reading `undefined` as "no",
|
|
87
|
+
* which would silently make every preview resource permanent.
|
|
88
|
+
*
|
|
89
|
+
* The reverse skew — a newer vendored subtree under an older CLI, whose engine
|
|
90
|
+
* knows nothing of instance-level `ephemeral` — cannot be fixed from here; `zbc
|
|
91
|
+
* update` moving ahead of the CLI is what the version pin in `zbc init
|
|
92
|
+
* --subtree` exists to prevent.
|
|
93
|
+
*/
|
|
94
|
+
export function isEphemeral(instance: ModuleInstance): boolean {
|
|
95
|
+
const declared = (instance as { ephemeral?: boolean }).ephemeral
|
|
96
|
+
return declared ?? legacyConfigEphemeral(instance.moduleName, instance.config)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* An ephemeral instance of a module with no `destroy` is a contradiction, and
|
|
101
|
+
* the engine refuses it before it applies anything — including the instances
|
|
102
|
+
* that sort ahead of it. Silently applying an "ephemeral" resource that is
|
|
103
|
+
* never torn down is exactly what `cloudflare-token` did for as long as it
|
|
104
|
+
* declared the flag and never read it.
|
|
105
|
+
*/
|
|
106
|
+
export function assertEphemeralDestroyable(instances: ModuleInstance[]): void {
|
|
107
|
+
for (const inst of instances) {
|
|
108
|
+
if (isEphemeral(inst) && !inst._definition.destroy) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`Instance "${inst.name}" is ephemeral but module "${inst.moduleName}" has no destroy`,
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
62
116
|
function collectTransitiveDeps(instance: ModuleInstance): ModuleInstance[] {
|
|
63
117
|
const collected = new Set<string>()
|
|
64
118
|
const result: ModuleInstance[] = []
|
package/templates/CLAUDE.md
CHANGED
|
@@ -16,7 +16,7 @@ This project uses [zbc](https://github.com/Zabaca/zbc) for infrastructure scaffo
|
|
|
16
16
|
- `bun install` — install dependencies
|
|
17
17
|
- `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; `secret-relay` — the browser-based secret request relay; `warehouse` — a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies)
|
|
18
18
|
- `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
|
|
19
|
-
- `bunx @zabaca/zbc destroy <env>` — tear down an
|
|
19
|
+
- `bunx @zabaca/zbc destroy <env>` — tear down every instance in an environment that defines a destroy
|
|
20
20
|
|
|
21
21
|
## Conventions
|
|
22
22
|
|
|
@@ -336,9 +336,10 @@ export const cloudflareModule = defineModule({
|
|
|
336
336
|
* original behavior). Set `{ from, output }` to pull it from an imported
|
|
337
337
|
* instance's outputs instead — e.g. a `cloudflare-token` instance's
|
|
338
338
|
* `tokenValue` — so a minted, per-apply-rolled deploy token flows straight
|
|
339
|
-
* to wrangler and never sits at rest.
|
|
340
|
-
*
|
|
341
|
-
*
|
|
339
|
+
* to wrangler and never sits at rest. `destroy` resolves it the same way:
|
|
340
|
+
* the engine applies the imported instance on demand when a teardown asks
|
|
341
|
+
* for its output, so an environment that destroys workers — an ephemeral
|
|
342
|
+
* instance, or `zbc destroy preview` — needs no secrets.yaml fallback.
|
|
342
343
|
*/
|
|
343
344
|
apiToken: z.object({ from: z.string(), output: z.string() }).optional(),
|
|
344
345
|
/** Optional local build run before deploy (e.g. `vite build` for assets). */
|
|
@@ -138,8 +138,6 @@ export const cloudflareTokenModule = defineModule({
|
|
|
138
138
|
* to grant zone-scoped groups on all zones of the account.
|
|
139
139
|
*/
|
|
140
140
|
zones: z.array(z.string()).default([]),
|
|
141
|
-
/** Destroy+recreate on every apply (per-PR preview tokens). */
|
|
142
|
-
ephemeral: z.boolean().default(false),
|
|
143
141
|
}),
|
|
144
142
|
outputs: z.object({
|
|
145
143
|
tokenId: z.string(),
|
|
@@ -271,8 +271,6 @@ export const flyModule = defineModule({
|
|
|
271
271
|
* record, to order the two within one apply.
|
|
272
272
|
*/
|
|
273
273
|
certs: z.array(z.string()).default([]),
|
|
274
|
-
/** Destroy+recreate the whole app on every apply (preview environments). */
|
|
275
|
-
ephemeral: z.boolean().default(false),
|
|
276
274
|
}),
|
|
277
275
|
outputs: z.object({
|
|
278
276
|
appName: z.string(),
|
|
@@ -295,12 +293,6 @@ export const flyModule = defineModule({
|
|
|
295
293
|
)
|
|
296
294
|
}
|
|
297
295
|
|
|
298
|
-
// 0. Ephemeral: tear the whole app down first so every apply starts clean.
|
|
299
|
-
if (config.ephemeral) {
|
|
300
|
-
console.log(` Ephemeral: destroying ${appName} before recreate`)
|
|
301
|
-
fly(workdir, ['apps', 'destroy', appName, '--yes'], env, { allowFailure: true })
|
|
302
|
-
}
|
|
303
|
-
|
|
304
296
|
// 1. Ensure the app exists. `fly deploy` does not create one, and the
|
|
305
297
|
// failure it gives for a missing app is not obviously that.
|
|
306
298
|
const list = fly(workdir, ['apps', 'list'], env)
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
"secrets": ["FLY_API_TOKEN"],
|
|
9
9
|
"signupUrl": "https://fly.io/app/sign-up",
|
|
10
10
|
"tokenUrl": "https://fly.io/user/personal_access_tokens",
|
|
11
|
-
"instructions": "Requires flyctl on PATH (`brew install flyctl`). Add FLY_API_TOKEN to packages/infra/environments/<env>/secrets.yaml — mint a PERSONAL ACCESS TOKEN, not a deploy token: a deploy token is app-scoped and cannot create apps or allocate IPs. IMPORTANT: Fly tokens start `FlyV1 fm2_…` and contain a literal space; do not strip whitespace when handling the value or you get a bare 401. The app topology (processes, services, ports, handlers, VM size, autostop/autostart) lives in the package's own fly.toml, which is the source of truth; this module only orchestrates create + IPs + build + deploy. Set `ipv4: \"dedicated\"` for ANY service port that is not 80/443 — shared IPv4 covers 80/443 only, it bills $2/mo, and without it a raw-TCP service is silently unreachable. Dedicated IPv6 is free but may be unroutable from some networks, so it is not a substitute. For per-PR preview apps set `appName` (e.g. `myapp-pr-${process.env.PR_NUMBER}`) plus `ephemeral: true
|
|
11
|
+
"instructions": "Requires flyctl on PATH (`brew install flyctl`). Add FLY_API_TOKEN to packages/infra/environments/<env>/secrets.yaml — mint a PERSONAL ACCESS TOKEN, not a deploy token: a deploy token is app-scoped and cannot create apps or allocate IPs. IMPORTANT: Fly tokens start `FlyV1 fm2_…` and contain a literal space; do not strip whitespace when handling the value or you get a bare 401. The app topology (processes, services, ports, handlers, VM size, autostop/autostart) lives in the package's own fly.toml, which is the source of truth; this module only orchestrates create + IPs + build + deploy. Set `ipv4: \"dedicated\"` for ANY service port that is not 80/443 — shared IPv4 covers 80/443 only, it bills $2/mo, and without it a raw-TCP service is silently unreachable. Dedicated IPv6 is free but may be unroutable from some networks, so it is not a substitute. For per-PR preview apps set `appName` (e.g. `myapp-pr-${process.env.PR_NUMBER}`) in config, plus `ephemeral: true` on the INSTANCE (a sibling of `name`/`config`, not a config field) — the engine then destroys and recreates the app on every apply. `flySecrets` entries are a plain name (from secrets.yaml), `{ name, value }`, or `{ name, from, output }` to pull from an imported instance's outputs; they are staged with `fly secrets set --stage` so the deploy that follows picks them up as one deployment. Set `localBuild: true` to build with the local Docker daemon instead of Fly's remote builder."
|
|
12
12
|
}
|
|
@@ -40,13 +40,6 @@ export const r2Module = defineModule({
|
|
|
40
40
|
* applied at creation; Cloudflare doesn't support relocating a bucket.
|
|
41
41
|
*/
|
|
42
42
|
locationHint: z.string().optional(),
|
|
43
|
-
/**
|
|
44
|
-
* Destroy+recreate on every apply (preview environments). NOTE: deleting
|
|
45
|
-
* a non-empty bucket fails — the management API has no object purge, so
|
|
46
|
-
* ephemeral only works cleanly for buckets whose objects the app cleans
|
|
47
|
-
* up, or that stay small enough to purge by hand.
|
|
48
|
-
*/
|
|
49
|
-
ephemeral: z.boolean().default(false),
|
|
50
43
|
}),
|
|
51
44
|
outputs: z.object({
|
|
52
45
|
bucketName: z.string(),
|
|
@@ -55,22 +48,6 @@ export const r2Module = defineModule({
|
|
|
55
48
|
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
56
49
|
const base = `/accounts/${config.accountId}/r2/buckets`
|
|
57
50
|
|
|
58
|
-
if (config.ephemeral) {
|
|
59
|
-
try {
|
|
60
|
-
await cf(
|
|
61
|
-
apiToken,
|
|
62
|
-
'DELETE',
|
|
63
|
-
`${base}/${encodeURIComponent(config.bucketName)}`,
|
|
64
|
-
undefined,
|
|
65
|
-
OPTS,
|
|
66
|
-
)
|
|
67
|
-
console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
|
|
68
|
-
} catch {
|
|
69
|
-
// Didn't exist (or non-empty — creation below will then no-op via the
|
|
70
|
-
// existence check, which for ephemeral means stale objects persist).
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
51
|
const listing = await cf<{ buckets: Array<{ name: string }> }>(
|
|
75
52
|
apiToken,
|
|
76
53
|
'GET',
|
|
@@ -100,6 +77,15 @@ export const r2Module = defineModule({
|
|
|
100
77
|
|
|
101
78
|
return { bucketName: config.bucketName }
|
|
102
79
|
},
|
|
80
|
+
/**
|
|
81
|
+
* Delete the bucket. NOTE: the management API refuses to delete a NON-EMPTY
|
|
82
|
+
* bucket and has no object purge, so this — and therefore an `ephemeral: true`
|
|
83
|
+
* r2 instance, whose destroy+re-apply the engine drives — only comes out clean
|
|
84
|
+
* for buckets whose objects the app itself removes, or that stay small enough
|
|
85
|
+
* to purge by hand. A refusal is logged, not thrown: it is the ordinary
|
|
86
|
+
* outcome for a bucket still holding data, and a `zbc destroy` that aborted
|
|
87
|
+
* there would strand every instance behind it.
|
|
88
|
+
*/
|
|
103
89
|
async destroy(config, ctx) {
|
|
104
90
|
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
105
91
|
try {
|
|
@@ -96,7 +96,6 @@ export const tursoModule = defineModule({
|
|
|
96
96
|
dbName: z.string(),
|
|
97
97
|
group: z.string().default('default'),
|
|
98
98
|
primaryLocation: z.string().default('iad'),
|
|
99
|
-
ephemeral: z.boolean().default(false),
|
|
100
99
|
/**
|
|
101
100
|
* Path to a Drizzle migrations folder, relative to the monorepo root
|
|
102
101
|
* (resolved via ctx.projectRoot). When provided, apply() runs migrations
|
|
@@ -120,16 +119,6 @@ export const tursoModule = defineModule({
|
|
|
120
119
|
const { createClient } = await import('@tursodatabase/api')
|
|
121
120
|
const turso = createClient({ org: config.orgName, token: apiToken })
|
|
122
121
|
|
|
123
|
-
// For ephemeral databases, destroy first to get a clean state
|
|
124
|
-
if (config.ephemeral) {
|
|
125
|
-
try {
|
|
126
|
-
await turso.databases.delete(config.dbName)
|
|
127
|
-
console.log(` Deleted ephemeral database "${config.dbName}"`)
|
|
128
|
-
} catch {
|
|
129
|
-
// Database didn't exist — that's fine
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
122
|
// Check if database already exists
|
|
134
123
|
const databases = await turso.databases.list()
|
|
135
124
|
const existing = databases.find((db) => db.name === config.dbName)
|
|
@@ -10,6 +10,38 @@ interface DefineModuleOptions<TConfig extends z.ZodType, TOutputs extends z.ZodT
|
|
|
10
10
|
destroy?: DestroyFn<z.infer<TConfig>>
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The four modules that declared `ephemeral` in their own config schema before
|
|
15
|
+
* 0.14 — and therefore the only four for which `config: { ephemeral: true }` in
|
|
16
|
+
* a consumer's checked-in instance file ever meant anything.
|
|
17
|
+
*
|
|
18
|
+
* The list is deliberately closed. Every other module's `z.object` STRIPPED an
|
|
19
|
+
* `ephemeral` key, so a stray one — copy-pasted from the old README, which
|
|
20
|
+
* documented the flag as a config field — was silently inert. Honouring it
|
|
21
|
+
* everywhere would give that stray key teeth it never had: `wrangler delete
|
|
22
|
+
* --force` against a live Worker on the next `zbc apply production`, or a hard
|
|
23
|
+
* failure on a module that has no `destroy` at all.
|
|
24
|
+
*/
|
|
25
|
+
const LEGACY_EPHEMERAL_MODULES = new Set(['turso', 'r2', 'fly', 'cloudflare-token'])
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The pre-0.14 spelling: `ephemeral` as a field of a module's own config
|
|
29
|
+
* schema. Three of the four modules above acted on it inline, with three
|
|
30
|
+
* different failure policies; the fourth declared it and never read it. The
|
|
31
|
+
* engine owns the rule now, but a consumer's checked-in preview instance files
|
|
32
|
+
* still say `config: { ephemeral: true }` and `zbc update` must not break them —
|
|
33
|
+
* so that spelling keeps working for those four, with a deprecation line
|
|
34
|
+
* printed by `zbc apply`.
|
|
35
|
+
*/
|
|
36
|
+
export function legacyConfigEphemeral(moduleName: string, config: unknown): boolean {
|
|
37
|
+
return (
|
|
38
|
+
LEGACY_EPHEMERAL_MODULES.has(moduleName) &&
|
|
39
|
+
typeof config === 'object' &&
|
|
40
|
+
config !== null &&
|
|
41
|
+
(config as Record<string, unknown>).ephemeral === true
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
|
|
13
45
|
export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodType>(
|
|
14
46
|
opts: DefineModuleOptions<TConfig, TOutputs>,
|
|
15
47
|
): ModuleDefinition<TConfig, TOutputs> {
|
|
@@ -30,6 +62,7 @@ export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodTy
|
|
|
30
62
|
moduleName: opts.name,
|
|
31
63
|
config: instanceOpts.config,
|
|
32
64
|
imports: instanceOpts.imports ?? [],
|
|
65
|
+
ephemeral: instanceOpts.ephemeral ?? legacyConfigEphemeral(opts.name, instanceOpts.config),
|
|
33
66
|
_outputsSchema: opts.outputs,
|
|
34
67
|
_definition: definition as ModuleDefinition<any, TOutputs>,
|
|
35
68
|
}
|
|
@@ -92,6 +92,17 @@ export interface InstanceOptions<TConfig extends z.ZodType> {
|
|
|
92
92
|
name: string
|
|
93
93
|
config: z.input<TConfig>
|
|
94
94
|
imports?: ModuleInstance[]
|
|
95
|
+
/**
|
|
96
|
+
* Destroy, then apply, on every `zbc apply` — a clean resource each run.
|
|
97
|
+
* Requires the module to define `destroy`; an ephemeral instance of a module
|
|
98
|
+
* without one is refused before anything is applied.
|
|
99
|
+
*
|
|
100
|
+
* A property of the INSTANCE, not of the module's config: whether a preview
|
|
101
|
+
* resource is thrown away each run is the environment's decision, and four
|
|
102
|
+
* modules each restating it in their own schema is how three of them ended up
|
|
103
|
+
* with three different failure policies and the fourth with none at all.
|
|
104
|
+
*/
|
|
105
|
+
ephemeral?: boolean
|
|
95
106
|
}
|
|
96
107
|
|
|
97
108
|
export interface ModuleInstance<TOutputs extends z.ZodType = z.ZodType> {
|
|
@@ -99,6 +110,8 @@ export interface ModuleInstance<TOutputs extends z.ZodType = z.ZodType> {
|
|
|
99
110
|
moduleName: string
|
|
100
111
|
config: unknown
|
|
101
112
|
imports: ModuleInstance[]
|
|
113
|
+
/** See `InstanceOptions.ephemeral`. Always set — the engine reads it directly. */
|
|
114
|
+
ephemeral: boolean
|
|
102
115
|
_outputsSchema: TOutputs
|
|
103
116
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
104
117
|
_definition: ModuleDefinition<any, TOutputs>
|