@zabaca/zbc 0.12.0 → 0.14.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 +174 -0
- package/package.json +6 -2
- package/src/commands/add.ts +13 -0
- package/src/commands/init.ts +1 -0
- package/src/engine/apply.ts +60 -21
- package/src/engine/destroy.ts +183 -14
- package/src/engine/discover.ts +1 -1
- package/src/engine/resolve.ts +56 -11
- package/src/utils/copy-template.ts +10 -0
- package/templates/apps/inbox/package.json +4 -2
- 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/apps/walgit/CONTEXT.md +135 -0
- package/templates/apps/walgit/Dockerfile +40 -18
- package/templates/apps/walgit/README.md +518 -55
- package/templates/apps/walgit/e2e/README.md +100 -6
- package/templates/apps/walgit/e2e/harness.ts +262 -1
- package/templates/apps/walgit/e2e/live.ts +588 -0
- package/templates/apps/walgit/e2e/scenarios.ts +367 -5
- package/templates/apps/walgit/e2e/suite.ts +5 -5
- package/templates/apps/walgit/examples/watch.ts +209 -0
- package/templates/apps/walgit/package.json +12 -3
- package/templates/apps/walgit/registry.json +6 -11
- package/templates/apps/walgit/shared/capabilities.ts +189 -0
- package/templates/apps/walgit/shared/container-env.ts +114 -0
- package/templates/apps/walgit/shared/credentials.ts +81 -0
- package/templates/apps/walgit/shared/events.ts +277 -0
- package/templates/apps/walgit/shared/landing.ts +1241 -0
- package/templates/apps/walgit/shared/llms.ts +463 -0
- package/templates/apps/walgit/shared/outbox.ts +266 -0
- package/templates/apps/walgit/shared/policy.ts +59 -0
- package/templates/apps/walgit/shared/protocol.ts +197 -0
- package/templates/apps/walgit/shared/provenance.ts +154 -0
- package/templates/apps/walgit/shared/ref-cache.ts +181 -0
- package/templates/apps/walgit/shared/telemetry.ts +219 -0
- package/templates/apps/walgit/src/announce-main.ts +37 -0
- package/templates/apps/walgit/src/announce.ts +98 -0
- package/templates/apps/walgit/src/append-only.ts +112 -0
- package/templates/apps/walgit/src/cache.ts +172 -0
- package/templates/apps/walgit/src/cli.ts +493 -0
- package/templates/apps/walgit/src/compact.ts +25 -23
- package/templates/apps/walgit/src/delete-repo.ts +237 -0
- package/templates/apps/walgit/src/expire.ts +248 -0
- package/templates/apps/walgit/src/gc.ts +8 -16
- package/templates/apps/walgit/src/git-backend.ts +29 -0
- package/templates/apps/walgit/src/git.ts +78 -0
- package/templates/apps/walgit/src/hook-main.ts +259 -17
- package/templates/apps/walgit/src/hooks.ts +4 -3
- package/templates/apps/walgit/src/http.ts +237 -45
- package/templates/apps/walgit/src/instructions.ts +240 -0
- package/templates/apps/walgit/src/keys.ts +126 -0
- package/templates/apps/walgit/src/limits.ts +158 -0
- package/templates/apps/walgit/src/materialize.bench.ts +10 -10
- package/templates/apps/walgit/src/materialize.ts +48 -40
- package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
- package/templates/apps/walgit/src/orphans.ts +2 -5
- package/templates/apps/walgit/src/pending.ts +201 -0
- package/templates/apps/walgit/src/push-cert.ts +254 -0
- package/templates/apps/walgit/src/push.ts +233 -46
- package/templates/apps/walgit/src/reconcile.ts +5 -8
- package/templates/apps/walgit/src/repo.ts +22 -77
- package/templates/apps/walgit/src/server.ts +148 -26
- package/templates/apps/walgit/src/signers.ts +577 -0
- package/templates/apps/walgit/src/store-env.ts +5 -4
- package/templates/apps/walgit/src/store.ts +47 -24
- package/templates/apps/walgit/src/usage.ts +404 -0
- package/templates/apps/walgit/src/verify.ts +171 -0
- package/templates/apps/walgit/src/wal-index.ts +189 -11
- package/templates/apps/walgit/tsconfig.json +8 -2
- package/templates/apps/walgit/tsconfig.worker.json +24 -0
- package/templates/apps/walgit/worker/events-do.ts +259 -0
- package/templates/apps/walgit/worker/index.ts +572 -0
- package/templates/apps/walgit/wrangler.jsonc +95 -0
- package/templates/apps/warehouse/package.json +1 -1
- package/templates/infra/modules/cloudflare/index.ts +93 -67
- 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 -30
- 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 +158 -35
- 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 +38 -55
- 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 +45 -7
- package/templates/infra/modules/vm-provision/index.ts +10 -3
- package/templates/infra/package.json +1 -1
- package/templates/infra/src/context.ts +115 -0
- package/templates/infra/src/define-module.ts +8 -2
- package/templates/infra/src/index.ts +11 -1
- package/templates/infra/src/types.ts +72 -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/templates/apps/walgit/entrypoint.sh +0 -59
- package/templates/apps/walgit/fly.toml +0 -52
- package/templates/apps/walgit/src/ssh-shell.ts +0 -36
- package/templates/apps/walgit/sshd_config +0 -38
|
@@ -3,12 +3,13 @@ import * as fs from 'node:fs'
|
|
|
3
3
|
import { execSync, spawnSync } from 'node:child_process'
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
import { defineModule } from '../../src/define-module'
|
|
6
|
+
import { resolveOutput, resolveSecret } from '../../src/context'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* fly — deploys a package to Fly.io via `fly deploy`.
|
|
9
10
|
*
|
|
10
11
|
* Same shape as the `cloudflare` module: a THIN orchestrator. `apply` runs on
|
|
11
|
-
* the operator machine, reads the Fly credential
|
|
12
|
+
* the operator machine, reads the Fly credential through `ctx.secret`, runs an
|
|
12
13
|
* optional local build, then shells `fly deploy` in the package's own
|
|
13
14
|
* directory. The app TOPOLOGY (processes, services, ports, handlers, VM size,
|
|
14
15
|
* regions, autostop/autostart) lives in that package's `fly.toml` — Fly is the
|
|
@@ -58,43 +59,53 @@ const flyValueSchema = z.union([
|
|
|
58
59
|
/** Which output of that instance to read. */
|
|
59
60
|
output: z.string(),
|
|
60
61
|
}),
|
|
62
|
+
z.object({
|
|
63
|
+
/** Env var name inside the app. */
|
|
64
|
+
name: z.string(),
|
|
65
|
+
/**
|
|
66
|
+
* A key in this environment's secrets.yaml, exposed under `name`.
|
|
67
|
+
*
|
|
68
|
+
* The plain-string form already reads a secret, but it forces the app's
|
|
69
|
+
* env var to be spelled exactly like the secret. An app whose interface
|
|
70
|
+
* says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
|
|
71
|
+
* `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
|
|
72
|
+
* the same credential under a second name, which is one more thing to
|
|
73
|
+
* forget when it rotates.
|
|
74
|
+
*/
|
|
75
|
+
secret: z.string(),
|
|
76
|
+
}),
|
|
61
77
|
])
|
|
62
78
|
|
|
63
79
|
type FlyValueEntry = z.infer<typeof flyValueSchema>
|
|
64
80
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Resolve a flySecrets entry to its `{ name, value }` pair.
|
|
83
|
+
*
|
|
84
|
+
* Takes the two raw fields rather than an `ApplyContext` — a full context is
|
|
85
|
+
* structurally one of these, and it keeps the helper callable with a literal.
|
|
86
|
+
* `resolveSecret`/`resolveOutput` are the same implementations `ctx.secret` and
|
|
87
|
+
* `ctx.output` are built from, so the failures read identically either way.
|
|
88
|
+
*/
|
|
89
|
+
export function resolveFlyValue(
|
|
67
90
|
entry: FlyValueEntry,
|
|
68
91
|
ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
|
|
69
92
|
fieldName: string,
|
|
70
93
|
): { name: string; value: string } {
|
|
71
94
|
if (typeof entry === 'string') {
|
|
72
|
-
|
|
73
|
-
if (!value) {
|
|
74
|
-
throw new Error(
|
|
75
|
-
`${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
|
|
76
|
-
)
|
|
77
|
-
}
|
|
78
|
-
return { name: entry, value }
|
|
95
|
+
return { name: entry, value: resolveSecret(ctx.secrets, entry, { field: fieldName }) }
|
|
79
96
|
}
|
|
80
97
|
|
|
81
98
|
if ('value' in entry) {
|
|
82
99
|
return { name: entry.name, value: entry.value }
|
|
83
100
|
}
|
|
84
101
|
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
)
|
|
90
|
-
}
|
|
91
|
-
const value = (instanceOutputs as Record<string, unknown>)[entry.output]
|
|
92
|
-
if (value === undefined) {
|
|
93
|
-
throw new Error(
|
|
94
|
-
`${fieldName} entry "${entry.name}" reads output "${entry.output}" from instance "${entry.from}", which does not emit it`,
|
|
95
|
-
)
|
|
102
|
+
const field = `${fieldName} entry "${entry.name}"`
|
|
103
|
+
|
|
104
|
+
if ('secret' in entry) {
|
|
105
|
+
return { name: entry.name, value: resolveSecret(ctx.secrets, entry.secret, { field }) }
|
|
96
106
|
}
|
|
97
|
-
|
|
107
|
+
|
|
108
|
+
return { name: entry.name, value: resolveOutput(entry, ctx.imports, field) }
|
|
98
109
|
}
|
|
99
110
|
|
|
100
111
|
/** Run flyctl, capturing BOTH streams — flyctl splits human output across them,
|
|
@@ -128,6 +139,76 @@ function fly(
|
|
|
128
139
|
/** Read `app = "name"` out of the package's fly.toml. The app name belongs to
|
|
129
140
|
* the package's own topology file; `appName` in config only overrides it (the
|
|
130
141
|
* per-PR preview case, mirroring the cloudflare module's `workerName`). */
|
|
142
|
+
/** Did `fly deploy` say, in its own words, that machines reached a good state?
|
|
143
|
+
*
|
|
144
|
+
* Exit 0 is not the signal — flyctl prints its build and then exits 0 on paths
|
|
145
|
+
* where nothing converged, which is what the caller's guard exists to catch.
|
|
146
|
+
* The vocabulary differs by path, and the guard originally knew only the
|
|
147
|
+
* first-launch half:
|
|
148
|
+
*
|
|
149
|
+
* launching a new machine -> "Finished launching new machines"
|
|
150
|
+
* a machine-less group -> "No machines in group"
|
|
151
|
+
* non-rolling update -> "update finished: success"
|
|
152
|
+
* ROLLING update -> "✔ Machine <id> is now in a good state"
|
|
153
|
+
*
|
|
154
|
+
* The last line is the one that was missing, and it is the line every deploy
|
|
155
|
+
* after the first prints. zbc-walgit was launched by hand, so CI's first run
|
|
156
|
+
* against it took the rolling path and the guard failed a deploy that had in
|
|
157
|
+
* fact converged (run 32881480843, 2026-08-25). A false red on a healthy
|
|
158
|
+
* deploy costs the guard its credibility as surely as a false green does.
|
|
159
|
+
*
|
|
160
|
+
* "reached stopped state" is NOT convergence and is deliberately not matched:
|
|
161
|
+
* flyctl prints it for an auto-stopped machine on its way to a good state, and
|
|
162
|
+
* also for one that stopped because it died. Only the good-state line settles it.
|
|
163
|
+
*/
|
|
164
|
+
export function machinesConverged(out: string): boolean {
|
|
165
|
+
return /(update finished: success|Finished launching new machines|No machines? in group|Machine \w+ is now in a good state)/.test(
|
|
166
|
+
out,
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Which of `wanted` has no certificate yet, given `fly certs list` output.
|
|
172
|
+
*
|
|
173
|
+
* Pure, and separated from apply because the cost of getting it wrong is
|
|
174
|
+
* asymmetric and invisible: `fly certs add` on a hostname that already has a
|
|
175
|
+
* certificate EXITS NON-ZERO, so a hostname wrongly judged absent fails the
|
|
176
|
+
* whole apply, while one wrongly judged present leaves the app serving a
|
|
177
|
+
* default certificate that every client rejects by name.
|
|
178
|
+
*
|
|
179
|
+
* Matching is on the first whitespace-delimited field of each line, never a
|
|
180
|
+
* substring: `git.zabaca.com` appears inside `www.git.zabaca.com`, and a
|
|
181
|
+
* substring test would skip a certificate that was never requested.
|
|
182
|
+
*/
|
|
183
|
+
export function certsToRequest(listOutput: string, wanted: string[]): string[] {
|
|
184
|
+
const present = new Set(
|
|
185
|
+
listOutput
|
|
186
|
+
.split('\n')
|
|
187
|
+
.map((line) => line.trim().split(/\s+/)[0])
|
|
188
|
+
.filter(Boolean),
|
|
189
|
+
)
|
|
190
|
+
return wanted.filter((hostname) => !present.has(hostname))
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Machines in the `app` process group, from `fly scale show` output.
|
|
195
|
+
*
|
|
196
|
+
* Returns undefined when the output cannot be read as a table — a flyctl
|
|
197
|
+
* version that reworded it, or a call that failed. Undefined means "do not
|
|
198
|
+
* scale", never "scale to zero": guessing a count from output this did not
|
|
199
|
+
* understand would destroy machines, and the safe direction when the evidence
|
|
200
|
+
* is unreadable is to leave the app alone and let the next apply try again.
|
|
201
|
+
*/
|
|
202
|
+
export function machineCount(scaleShowOutput: string): number | undefined {
|
|
203
|
+
for (const line of scaleShowOutput.split('\n')) {
|
|
204
|
+
const cells = line.split('│').map((cell) => cell.trim())
|
|
205
|
+
if (cells.length < 2 || cells[0] !== 'app') continue
|
|
206
|
+
const count = Number(cells[1])
|
|
207
|
+
if (Number.isInteger(count) && count >= 0) return count
|
|
208
|
+
}
|
|
209
|
+
return undefined
|
|
210
|
+
}
|
|
211
|
+
|
|
131
212
|
function appNameFromFlyToml(workdir: string): string | undefined {
|
|
132
213
|
const tomlPath = path.join(workdir, 'fly.toml')
|
|
133
214
|
if (!fs.existsSync(tomlPath)) return undefined
|
|
@@ -159,7 +240,9 @@ export const flyModule = defineModule({
|
|
|
159
240
|
/**
|
|
160
241
|
* App secrets, staged before deploy. Each entry is either a plain name (a
|
|
161
242
|
* key in this environment's secrets.yaml), `{ name, value }` for a literal,
|
|
162
|
-
*
|
|
243
|
+
* `{ name, secret }` to expose a secrets.yaml key under a different env var
|
|
244
|
+
* name, or `{ name, from, output }` to pull from an imported instance's
|
|
245
|
+
* outputs.
|
|
163
246
|
*/
|
|
164
247
|
flySecrets: z.array(flyValueSchema).default([]),
|
|
165
248
|
/**
|
|
@@ -178,6 +261,16 @@ export const flyModule = defineModule({
|
|
|
178
261
|
* for a builder machine to spin up.
|
|
179
262
|
*/
|
|
180
263
|
localBuild: z.boolean().default(false),
|
|
264
|
+
/**
|
|
265
|
+
* Custom hostnames Fly should hold a TLS certificate for, e.g.
|
|
266
|
+
* `git.zabaca.com`. Each is requested once and left alone thereafter.
|
|
267
|
+
*
|
|
268
|
+
* The DNS record for the hostname must already point at this app, or Fly
|
|
269
|
+
* has nothing to validate against and the certificate sits pending — so
|
|
270
|
+
* the instance declaring a cert should `imports` whatever manages that
|
|
271
|
+
* record, to order the two within one apply.
|
|
272
|
+
*/
|
|
273
|
+
certs: z.array(z.string()).default([]),
|
|
181
274
|
/** Destroy+recreate the whole app on every apply (preview environments). */
|
|
182
275
|
ephemeral: z.boolean().default(false),
|
|
183
276
|
}),
|
|
@@ -191,8 +284,7 @@ export const flyModule = defineModule({
|
|
|
191
284
|
ipv6: z.string(),
|
|
192
285
|
}),
|
|
193
286
|
async apply(config, ctx) {
|
|
194
|
-
const token = ctx.
|
|
195
|
-
if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
287
|
+
const token = ctx.secret('FLY_API_TOKEN')
|
|
196
288
|
|
|
197
289
|
const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
|
|
198
290
|
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
@@ -235,7 +327,23 @@ export const flyModule = defineModule({
|
|
|
235
327
|
fly(workdir, ['ips', 'allocate-v6', '-a', appName], env)
|
|
236
328
|
}
|
|
237
329
|
|
|
238
|
-
// 3.
|
|
330
|
+
// 3. Custom hostname certificates. Requested before the deploy rather than
|
|
331
|
+
// after, because issuance is asynchronous on Fly's side and a deploy can
|
|
332
|
+
// take minutes — asking first lets validation run during it.
|
|
333
|
+
//
|
|
334
|
+
// `fly certs add` on a hostname that already has a certificate is an
|
|
335
|
+
// error, not a no-op, so this lists first and matches whole lines: a
|
|
336
|
+
// substring test would see `git.zabaca.com` inside `www.git.zabaca.com`
|
|
337
|
+
// and skip a certificate that was never requested.
|
|
338
|
+
if (config.certs.length > 0) {
|
|
339
|
+
const listed = fly(workdir, ['certs', 'list', '-a', appName], env).out
|
|
340
|
+
for (const hostname of certsToRequest(listed, config.certs)) {
|
|
341
|
+
console.log(` Requesting certificate for ${hostname}`)
|
|
342
|
+
fly(workdir, ['certs', 'add', hostname, '-a', appName], env)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// 4. Optional local build. Inherit stdio so build output streams.
|
|
239
347
|
if (config.build) {
|
|
240
348
|
const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
|
|
241
349
|
console.log(
|
|
@@ -244,11 +352,11 @@ export const flyModule = defineModule({
|
|
|
244
352
|
execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
|
|
245
353
|
}
|
|
246
354
|
|
|
247
|
-
//
|
|
355
|
+
// 5. Resolve every secret BEFORE staging so a bad reference fails fast,
|
|
248
356
|
// without leaving a half-configured app. `resolveFlyValue` is pure.
|
|
249
357
|
const resolved = config.flySecrets.map((entry) => resolveFlyValue(entry, ctx, 'flySecrets'))
|
|
250
358
|
|
|
251
|
-
//
|
|
359
|
+
// 6. Stage secrets. `--stage` withholds the deployment that `fly secrets
|
|
252
360
|
// set` would otherwise trigger; step 6 picks them up. Values go on the
|
|
253
361
|
// command line as NAME=VALUE — flyctl offers no stdin form — so they are
|
|
254
362
|
// visible to a local process listing, though never logged here.
|
|
@@ -268,7 +376,7 @@ export const flyModule = defineModule({
|
|
|
268
376
|
console.log(` Staged secrets: ${resolved.map((s) => s.name).join(', ')}`)
|
|
269
377
|
}
|
|
270
378
|
|
|
271
|
-
//
|
|
379
|
+
// 7. Deploy.
|
|
272
380
|
const deployArgs = ['deploy', '-a', appName, '--yes']
|
|
273
381
|
if (!config.highAvailability) deployArgs.push('--ha=false')
|
|
274
382
|
if (config.localBuild) deployArgs.push('--local-only')
|
|
@@ -279,15 +387,13 @@ export const flyModule = defineModule({
|
|
|
279
387
|
|
|
280
388
|
// Success-theater guard, same lesson as the cloudflare module: require a
|
|
281
389
|
// confirmation that machines actually converged rather than trusting exit 0.
|
|
282
|
-
if (
|
|
283
|
-
!/(update finished: success|Finished launching new machines|No machines? in group)/.test(out)
|
|
284
|
-
) {
|
|
390
|
+
if (!machinesConverged(out)) {
|
|
285
391
|
throw new Error(
|
|
286
392
|
`fly deploy exited 0 but printed no machine-convergence confirmation:\n${out}`,
|
|
287
393
|
)
|
|
288
394
|
}
|
|
289
395
|
|
|
290
|
-
//
|
|
396
|
+
// 8. Read the IPs back for outputs — dependents need the address, and after
|
|
291
397
|
// step 2 it is whatever Fly actually holds, not what we asked for.
|
|
292
398
|
const finalIps = fly(workdir, ['ips', 'list', '-a', appName], env)
|
|
293
399
|
const v4 = finalIps.out.match(/\bv4\s*│\s*([0-9.]+)/)?.[1] ?? ''
|
|
@@ -295,11 +401,28 @@ export const flyModule = defineModule({
|
|
|
295
401
|
const hostname = `${appName}.fly.dev`
|
|
296
402
|
console.log(` Deployed: ${hostname}${v4 ? ` (${v4})` : ''}`)
|
|
297
403
|
|
|
404
|
+
// 9. Machine count. This is NOT what `--ha` on the deploy above does:
|
|
405
|
+
// flyctl's `--ha` provisions a spare only when it is FIRST launching an
|
|
406
|
+
// app, and a deploy to an app that already exists keeps whatever count
|
|
407
|
+
// it has. So `highAvailability: true` on a live app changed nothing and
|
|
408
|
+
// said nothing — the deploy reported success either way, which is the
|
|
409
|
+
// failure this module already learned to distrust once.
|
|
410
|
+
//
|
|
411
|
+
// `fly scale count` is the converging form, and it runs AFTER the deploy
|
|
412
|
+
// so a machine created here starts from the image just released rather
|
|
413
|
+
// than the previous one.
|
|
414
|
+
const wanted = config.highAvailability ? 2 : 1
|
|
415
|
+
const shown = fly(workdir, ['scale', 'show', '-a', appName], env, { allowFailure: true })
|
|
416
|
+
const current = machineCount(shown.out)
|
|
417
|
+
if (current !== undefined && current !== wanted) {
|
|
418
|
+
console.log(` Scaling machines: ${current} → ${wanted}`)
|
|
419
|
+
fly(workdir, ['scale', 'count', String(wanted), '-a', appName, '--yes'], env)
|
|
420
|
+
}
|
|
421
|
+
|
|
298
422
|
return { appName, hostname, ipv4: v4, ipv6: v6 }
|
|
299
423
|
},
|
|
300
424
|
async destroy(config, ctx) {
|
|
301
|
-
const token = ctx.
|
|
302
|
-
if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
425
|
+
const token = ctx.secret('FLY_API_TOKEN')
|
|
303
426
|
const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
|
|
304
427
|
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
305
428
|
const appName = config.appName ?? appNameFromFlyToml(workdir)
|
|
@@ -22,14 +22,13 @@ export const hostFileModule = defineModule({
|
|
|
22
22
|
}),
|
|
23
23
|
outputs: z.object({ path: z.string(), changed: z.boolean() }),
|
|
24
24
|
apply: async (config, ctx) => {
|
|
25
|
+
// `allowBlank`: presence is the contract. An empty secret is a legitimate
|
|
26
|
+
// file body, and refusing it would make "no value yet" unrepresentable.
|
|
25
27
|
const desired =
|
|
26
|
-
config.content !== undefined
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const existing = fs.existsSync(config.path)
|
|
31
|
-
? fs.readFileSync(config.path, 'utf8')
|
|
32
|
-
: null
|
|
28
|
+
config.content !== undefined
|
|
29
|
+
? config.content
|
|
30
|
+
: ctx.secret(config.secretKey!, { allowBlank: true })
|
|
31
|
+
const existing = fs.existsSync(config.path) ? fs.readFileSync(config.path, 'utf8') : null
|
|
33
32
|
const changed = existing !== desired
|
|
34
33
|
const mode = parseInt(config.mode, 8)
|
|
35
34
|
if (changed) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
+
import { resolveOutput } from '../../src/context'
|
|
2
3
|
|
|
3
4
|
// The parts of "converge the inside of a machine" that do not care how the
|
|
4
5
|
// work is delivered: what to run, whether to run it, and how to decide that
|
|
@@ -93,6 +94,20 @@ export function renderProvisionScript(input: {
|
|
|
93
94
|
* Reads `ENVVAR: "instance.field"` references out of another instance's
|
|
94
95
|
* outputs. Outputs only exist during an apply, so this is the only way a
|
|
95
96
|
* just-minted credential can reach a script without being written down.
|
|
97
|
+
*
|
|
98
|
+
* Only the dotted spelling is this function's own — `instance.field` is a
|
|
99
|
+
* flatter form than the `{ from, output }` every other module takes, and it is
|
|
100
|
+
* kept because it is what instance files already say. Once split, the lookup
|
|
101
|
+
* is the engine's `resolveOutput`, the same one behind `ctx.output`.
|
|
102
|
+
*
|
|
103
|
+
* `allowBlank`: an empty value is a real answer here. The authkey module mints
|
|
104
|
+
* only when there is a join to perform, and reports `''` otherwise —
|
|
105
|
+
* `shouldProvision` reads exactly that to decide whether an unchanged digest
|
|
106
|
+
* still has work.
|
|
107
|
+
*
|
|
108
|
+
* A non-string output is now an error rather than a `String(value)`. Exporting
|
|
109
|
+
* `TS_AUTHKEY=true` because a ref pointed at a boolean output is not a value
|
|
110
|
+
* any script wanted, and it reaches the guest looking exactly like one that was.
|
|
96
111
|
*/
|
|
97
112
|
export function resolveVolatileEnv(
|
|
98
113
|
spec: Record<string, string>,
|
|
@@ -104,21 +119,12 @@ export function resolveVolatileEnv(
|
|
|
104
119
|
if (dot <= 0 || dot === ref.length - 1) {
|
|
105
120
|
throw new Error(`volatileEnvFrom.${envVar}: "${ref}" is not of the form instance.field`)
|
|
106
121
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
)
|
|
114
|
-
}
|
|
115
|
-
const value = (source as Record<string, unknown>)[field]
|
|
116
|
-
if (value === undefined) {
|
|
117
|
-
throw new Error(
|
|
118
|
-
`volatileEnvFrom.${envVar}: instance "${instance}" has no output field "${field}"`,
|
|
119
|
-
)
|
|
120
|
-
}
|
|
121
|
-
out[envVar] = String(value)
|
|
122
|
+
out[envVar] = resolveOutput(
|
|
123
|
+
{ from: ref.slice(0, dot), output: ref.slice(dot + 1) },
|
|
124
|
+
imports,
|
|
125
|
+
`volatileEnvFrom.${envVar}`,
|
|
126
|
+
{ allowBlank: true },
|
|
127
|
+
)
|
|
122
128
|
}
|
|
123
129
|
return out
|
|
124
130
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
+
import { cf, type CfOptions } from '../cloudflare-api'
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
|
|
6
|
-
* token
|
|
7
|
+
* token through ctx.secret, idempotent list→create, console.log progress).
|
|
7
8
|
*
|
|
8
9
|
* Exists so bucket lifecycle is owned by infra instead of being a side effect
|
|
9
10
|
* of `wrangler deploy` prompting to create a missing bucket. A worker wires
|
|
@@ -13,46 +14,18 @@ import { defineModule } from '../../src/define-module'
|
|
|
13
14
|
* Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
|
|
14
15
|
*/
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
): Promise<T> {
|
|
29
|
-
const res = await fetch(`${API}${path}`, {
|
|
30
|
-
method: init?.method ?? 'GET',
|
|
31
|
-
headers: {
|
|
32
|
-
Authorization: `Bearer ${token}`,
|
|
33
|
-
'Content-Type': 'application/json',
|
|
34
|
-
},
|
|
35
|
-
body: init?.body === undefined ? undefined : JSON.stringify(init.body),
|
|
36
|
-
})
|
|
37
|
-
let envelope: CfEnvelope<T>
|
|
38
|
-
try {
|
|
39
|
-
envelope = (await res.json()) as CfEnvelope<T>
|
|
40
|
-
} catch {
|
|
41
|
-
throw new Error(`Cloudflare API ${path}: HTTP ${res.status} (non-JSON body)`)
|
|
42
|
-
}
|
|
43
|
-
if (!res.ok || !envelope.success) {
|
|
44
|
-
const codes = (envelope.errors ?? []).map((e) => e.code)
|
|
45
|
-
const detail = (envelope.errors ?? []).map((e) => `${e.code}: ${e.message}`).join('; ')
|
|
46
|
-
if (codes.includes(10000)) {
|
|
47
|
-
throw new Error(
|
|
48
|
-
`Cloudflare API ${path} rejected the token (10000 Authentication error). ` +
|
|
49
|
-
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
50
|
-
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
51
|
-
)
|
|
52
|
-
}
|
|
53
|
-
throw new Error(`Cloudflare API ${path} failed (HTTP ${res.status}): ${detail}`)
|
|
54
|
-
}
|
|
55
|
-
return envelope.result
|
|
17
|
+
/**
|
|
18
|
+
* Named per-code guidance for this module's calls — the one genuinely
|
|
19
|
+
* per-module part of a Cloudflare failure. Everything else about the envelope
|
|
20
|
+
* (the base URL, the error shapes, the typed throw) is `../cloudflare-api`'s.
|
|
21
|
+
*/
|
|
22
|
+
const OPTS: CfOptions = {
|
|
23
|
+
hints: {
|
|
24
|
+
10000:
|
|
25
|
+
`rejected the token (10000 Authentication error). ` +
|
|
26
|
+
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
27
|
+
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
28
|
+
},
|
|
56
29
|
}
|
|
57
30
|
|
|
58
31
|
export const r2Module = defineModule({
|
|
@@ -79,15 +52,18 @@ export const r2Module = defineModule({
|
|
|
79
52
|
bucketName: z.string(),
|
|
80
53
|
}),
|
|
81
54
|
async apply(config, ctx) {
|
|
82
|
-
const apiToken = ctx.
|
|
83
|
-
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
55
|
+
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
84
56
|
const base = `/accounts/${config.accountId}/r2/buckets`
|
|
85
57
|
|
|
86
58
|
if (config.ephemeral) {
|
|
87
59
|
try {
|
|
88
|
-
await
|
|
89
|
-
|
|
90
|
-
|
|
60
|
+
await cf(
|
|
61
|
+
apiToken,
|
|
62
|
+
'DELETE',
|
|
63
|
+
`${base}/${encodeURIComponent(config.bucketName)}`,
|
|
64
|
+
undefined,
|
|
65
|
+
OPTS,
|
|
66
|
+
)
|
|
91
67
|
console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
|
|
92
68
|
} catch {
|
|
93
69
|
// Didn't exist (or non-empty — creation below will then no-op via the
|
|
@@ -95,22 +71,28 @@ export const r2Module = defineModule({
|
|
|
95
71
|
}
|
|
96
72
|
}
|
|
97
73
|
|
|
98
|
-
const listing = await
|
|
74
|
+
const listing = await cf<{ buckets: Array<{ name: string }> }>(
|
|
99
75
|
apiToken,
|
|
76
|
+
'GET',
|
|
100
77
|
`${base}?per_page=1000`,
|
|
78
|
+
undefined,
|
|
79
|
+
OPTS,
|
|
101
80
|
)
|
|
102
81
|
const exists = listing.buckets.some((b) => b.name === config.bucketName)
|
|
103
82
|
|
|
104
83
|
if (exists) {
|
|
105
84
|
console.log(` Bucket "${config.bucketName}" already exists`)
|
|
106
85
|
} else {
|
|
107
|
-
await
|
|
108
|
-
|
|
109
|
-
|
|
86
|
+
await cf(
|
|
87
|
+
apiToken,
|
|
88
|
+
'POST',
|
|
89
|
+
base,
|
|
90
|
+
{
|
|
110
91
|
name: config.bucketName,
|
|
111
92
|
...(config.locationHint ? { locationHint: config.locationHint } : {}),
|
|
112
93
|
},
|
|
113
|
-
|
|
94
|
+
OPTS,
|
|
95
|
+
)
|
|
114
96
|
console.log(
|
|
115
97
|
` Created bucket "${config.bucketName}"${config.locationHint ? ` (${config.locationHint})` : ''}`,
|
|
116
98
|
)
|
|
@@ -119,13 +101,14 @@ export const r2Module = defineModule({
|
|
|
119
101
|
return { bucketName: config.bucketName }
|
|
120
102
|
},
|
|
121
103
|
async destroy(config, ctx) {
|
|
122
|
-
const apiToken = ctx.
|
|
123
|
-
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
104
|
+
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
124
105
|
try {
|
|
125
|
-
await
|
|
106
|
+
await cf(
|
|
126
107
|
apiToken,
|
|
108
|
+
'DELETE',
|
|
127
109
|
`/accounts/${config.accountId}/r2/buckets/${encodeURIComponent(config.bucketName)}`,
|
|
128
|
-
|
|
110
|
+
undefined,
|
|
111
|
+
OPTS,
|
|
129
112
|
)
|
|
130
113
|
console.log(` Deleted bucket "${config.bucketName}"`)
|
|
131
114
|
} catch (err) {
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
"files": [{ "path": "index.ts" }],
|
|
5
5
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
6
6
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
7
|
-
"instructions": "CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }"
|
|
7
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope. In COPY mode run `zbc add cloudflare-api` too.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }"
|
|
8
8
|
}
|
|
@@ -85,9 +85,7 @@ export const remoteProvisionModule = defineModule({
|
|
|
85
85
|
apply: async (config, ctx) => {
|
|
86
86
|
const env: Record<string, string> = { ...config.env }
|
|
87
87
|
for (const [key, secretKey] of Object.entries(config.envSecrets)) {
|
|
88
|
-
|
|
89
|
-
if (value === undefined) throw new Error(`secret "${secretKey}" not found in secrets.yaml`)
|
|
90
|
-
env[key] = value
|
|
88
|
+
env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
|
|
91
89
|
}
|
|
92
90
|
|
|
93
91
|
const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
|
|
@@ -50,6 +50,45 @@ export async function waitUntilReachable(
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* `@libsql/client` and `drizzle-orm` are turso's OPTIONAL dependencies, and this
|
|
55
|
+
* is the seam that keeps them optional.
|
|
56
|
+
*
|
|
57
|
+
* Only the `migrationsDir` branch of `apply` touches them, so `registry.json`
|
|
58
|
+
* lists them under `optionalDependencies` and `zbc add turso` does not pull
|
|
59
|
+
* drizzle into a repository that has no migrations to run. A plain
|
|
60
|
+
* `await import('@libsql/client')` contradicts that: it is a module TypeScript
|
|
61
|
+
* must resolve at compile time, so every consumer that took the module at its
|
|
62
|
+
* word and skipped them compiles three unresolvable imports — `modules/` is the
|
|
63
|
+
* tree they vendor, so the errors are theirs, not just ours.
|
|
64
|
+
*
|
|
65
|
+
* Going through a specifier the compiler cannot fold to a literal moves that
|
|
66
|
+
* resolution to runtime, where the branch has already established the package is
|
|
67
|
+
* installed. The types below are the price: the surface used is written out here
|
|
68
|
+
* rather than read off the real package, so it has to be kept honest by hand.
|
|
69
|
+
* Both are small and neither is on a version we pin.
|
|
70
|
+
*/
|
|
71
|
+
const importOptional = <T>(specifier: string): Promise<T> => import(specifier) as Promise<T>
|
|
72
|
+
|
|
73
|
+
/** The one function this module calls in `@libsql/client`, and the two it calls on the result. */
|
|
74
|
+
interface LibsqlClientModule {
|
|
75
|
+
createClient(config: { url: string; authToken?: string }): LibsqlClient
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface LibsqlClient {
|
|
79
|
+
execute(sql: string): Promise<unknown>
|
|
80
|
+
close(): void
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The handle is opaque here — it is created and then handed straight to `migrate`. */
|
|
84
|
+
interface DrizzleLibsqlModule {
|
|
85
|
+
drizzle(client: LibsqlClient): unknown
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface DrizzleMigratorModule {
|
|
89
|
+
migrate(db: unknown, config: { migrationsFolder: string }): Promise<void>
|
|
90
|
+
}
|
|
91
|
+
|
|
53
92
|
export const tursoModule = defineModule({
|
|
54
93
|
name: 'turso',
|
|
55
94
|
configSchema: z.object({
|
|
@@ -70,8 +109,7 @@ export const tursoModule = defineModule({
|
|
|
70
109
|
authToken: z.string(),
|
|
71
110
|
}),
|
|
72
111
|
async apply(config, ctx) {
|
|
73
|
-
const apiToken = ctx.
|
|
74
|
-
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
112
|
+
const apiToken = ctx.secret('TURSO_API_TOKEN')
|
|
75
113
|
|
|
76
114
|
// Imported here rather than at the top of the file, the way the migration
|
|
77
115
|
// dependencies below already are: a consumer that vendors zbc-core but
|
|
@@ -144,9 +182,10 @@ export const tursoModule = defineModule({
|
|
|
144
182
|
|
|
145
183
|
if (config.migrationsDir) {
|
|
146
184
|
const { resolve } = await import('node:path')
|
|
147
|
-
const { createClient: createLibsqlClient } =
|
|
148
|
-
|
|
149
|
-
const {
|
|
185
|
+
const { createClient: createLibsqlClient } =
|
|
186
|
+
await importOptional<LibsqlClientModule>('@libsql/client')
|
|
187
|
+
const { drizzle } = await importOptional<DrizzleLibsqlModule>('drizzle-orm/libsql')
|
|
188
|
+
const { migrate } = await importOptional<DrizzleMigratorModule>('drizzle-orm/libsql/migrator')
|
|
150
189
|
|
|
151
190
|
const folder = resolve(ctx.projectRoot, config.migrationsDir)
|
|
152
191
|
const migrationClient = createLibsqlClient({
|
|
@@ -170,8 +209,7 @@ export const tursoModule = defineModule({
|
|
|
170
209
|
}
|
|
171
210
|
},
|
|
172
211
|
async destroy(config, ctx) {
|
|
173
|
-
const apiToken = ctx.
|
|
174
|
-
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
212
|
+
const apiToken = ctx.secret('TURSO_API_TOKEN')
|
|
175
213
|
|
|
176
214
|
const { createClient } = await import('@tursodatabase/api')
|
|
177
215
|
const turso = createClient({ org: config.orgName, token: apiToken })
|
|
@@ -44,6 +44,15 @@ export interface VmOutputs {
|
|
|
44
44
|
target?: IncusTarget
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* The one legitimate raw reader of `ctx.imports`.
|
|
49
|
+
*
|
|
50
|
+
* Every other lookup in core names what it wants — `ctx.output({ from, output
|
|
51
|
+
* }, field)` — because the instance file said so. This one has nothing to name:
|
|
52
|
+
* it SEARCHES the imports for outputs shaped like a vm, so that an instance
|
|
53
|
+
* importing exactly one vm need not repeat that vm's name. A ref-based
|
|
54
|
+
* resolver cannot express "whichever one it is", which is why this stays.
|
|
55
|
+
*/
|
|
47
56
|
export function findVmOutputs(imports: Record<string, unknown>): VmOutputs[] {
|
|
48
57
|
return Object.values(imports).filter((o): o is VmOutputs => {
|
|
49
58
|
if (typeof o !== 'object' || o === null) return false
|
|
@@ -104,12 +113,10 @@ export const vmProvisionModule = defineModule({
|
|
|
104
113
|
|
|
105
114
|
const env: Record<string, string> = { ...config.env }
|
|
106
115
|
for (const [key, secretKey] of Object.entries(config.envSecrets)) {
|
|
107
|
-
const value = ctx.secrets[secretKey]
|
|
108
116
|
// Presence is the contract, not non-emptiness — an intentionally blank
|
|
109
117
|
// placeholder lets a script no-op the step it gates until the real value
|
|
110
118
|
// is filled in, at which point the digest changes and it re-provisions.
|
|
111
|
-
|
|
112
|
-
env[key] = value
|
|
119
|
+
env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
|
|
113
120
|
}
|
|
114
121
|
|
|
115
122
|
const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
|