@zabaca/zbc 0.12.0 → 0.13.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/package.json +2 -1
  3. package/templates/apps/inbox/package.json +1 -1
  4. package/templates/apps/walgit/CONTEXT.md +135 -0
  5. package/templates/apps/walgit/Dockerfile +40 -18
  6. package/templates/apps/walgit/README.md +518 -55
  7. package/templates/apps/walgit/e2e/README.md +100 -6
  8. package/templates/apps/walgit/e2e/harness.ts +262 -1
  9. package/templates/apps/walgit/e2e/live.ts +588 -0
  10. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  11. package/templates/apps/walgit/e2e/suite.ts +5 -5
  12. package/templates/apps/walgit/examples/watch.ts +209 -0
  13. package/templates/apps/walgit/package.json +12 -3
  14. package/templates/apps/walgit/registry.json +6 -11
  15. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  16. package/templates/apps/walgit/shared/container-env.ts +114 -0
  17. package/templates/apps/walgit/shared/credentials.ts +81 -0
  18. package/templates/apps/walgit/shared/events.ts +277 -0
  19. package/templates/apps/walgit/shared/landing.ts +1241 -0
  20. package/templates/apps/walgit/shared/llms.ts +463 -0
  21. package/templates/apps/walgit/shared/outbox.ts +266 -0
  22. package/templates/apps/walgit/shared/policy.ts +59 -0
  23. package/templates/apps/walgit/shared/protocol.ts +197 -0
  24. package/templates/apps/walgit/shared/provenance.ts +154 -0
  25. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  26. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  27. package/templates/apps/walgit/src/announce-main.ts +37 -0
  28. package/templates/apps/walgit/src/announce.ts +98 -0
  29. package/templates/apps/walgit/src/append-only.ts +112 -0
  30. package/templates/apps/walgit/src/cache.ts +172 -0
  31. package/templates/apps/walgit/src/cli.ts +493 -0
  32. package/templates/apps/walgit/src/compact.ts +25 -23
  33. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  34. package/templates/apps/walgit/src/expire.ts +248 -0
  35. package/templates/apps/walgit/src/gc.ts +8 -16
  36. package/templates/apps/walgit/src/git-backend.ts +29 -0
  37. package/templates/apps/walgit/src/git.ts +78 -0
  38. package/templates/apps/walgit/src/hook-main.ts +259 -17
  39. package/templates/apps/walgit/src/hooks.ts +4 -3
  40. package/templates/apps/walgit/src/http.ts +237 -45
  41. package/templates/apps/walgit/src/instructions.ts +240 -0
  42. package/templates/apps/walgit/src/keys.ts +126 -0
  43. package/templates/apps/walgit/src/limits.ts +158 -0
  44. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  45. package/templates/apps/walgit/src/materialize.ts +48 -40
  46. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  47. package/templates/apps/walgit/src/orphans.ts +2 -5
  48. package/templates/apps/walgit/src/pending.ts +201 -0
  49. package/templates/apps/walgit/src/push-cert.ts +254 -0
  50. package/templates/apps/walgit/src/push.ts +233 -46
  51. package/templates/apps/walgit/src/reconcile.ts +5 -8
  52. package/templates/apps/walgit/src/repo.ts +22 -77
  53. package/templates/apps/walgit/src/server.ts +148 -26
  54. package/templates/apps/walgit/src/signers.ts +577 -0
  55. package/templates/apps/walgit/src/store-env.ts +5 -4
  56. package/templates/apps/walgit/src/store.ts +47 -24
  57. package/templates/apps/walgit/src/usage.ts +404 -0
  58. package/templates/apps/walgit/src/verify.ts +171 -0
  59. package/templates/apps/walgit/src/wal-index.ts +189 -11
  60. package/templates/apps/walgit/tsconfig.json +8 -2
  61. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  62. package/templates/apps/walgit/worker/events-do.ts +259 -0
  63. package/templates/apps/walgit/worker/index.ts +572 -0
  64. package/templates/apps/walgit/wrangler.jsonc +95 -0
  65. package/templates/apps/warehouse/package.json +1 -1
  66. package/templates/infra/modules/cloudflare/index.ts +77 -6
  67. package/templates/infra/modules/fly/index.ts +150 -10
  68. package/templates/infra/modules/turso/index.ts +43 -3
  69. package/templates/infra/package.json +1 -1
  70. package/templates/apps/walgit/entrypoint.sh +0 -59
  71. package/templates/apps/walgit/fly.toml +0 -52
  72. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  73. package/templates/apps/walgit/sshd_config +0 -38
@@ -86,12 +86,30 @@ const buildSchema = z.object({
86
86
  cwd: z.string().optional(),
87
87
  })
88
88
 
89
+ /**
90
+ * The origin a route pattern answers on, for `deployUrl` when there is no
91
+ * workers.dev URL to report.
92
+ *
93
+ * Only a pattern whose host is a concrete hostname qualifies. A wildcard host
94
+ * (`*.example.com/*`) names a set rather than an address, and emitting
95
+ * `https://*.example.com` would hand a dependent a string that looks like a URL
96
+ * and resolves to nothing.
97
+ */
98
+ export function routeUrl(routes: string[]): string {
99
+ for (const route of routes) {
100
+ const host = route.split('/')[0]
101
+ if (host && !host.includes('*') && host.includes('.')) return `https://${host}`
102
+ }
103
+ return ''
104
+ }
105
+
89
106
  /**
90
107
  * A worker secret/var entry: a plain name (resolved from this environment's
91
108
  * secrets.yaml), a `{ name, value }` literal (vars that are per-instance
92
109
  * config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
93
- * needs no editing), or a `{ name, from, output }` reference into an imported
94
- * instance's outputs (`ctx.imports[from][output]`).
110
+ * needs no editing), a `{ name, from, output }` reference into an imported
111
+ * instance's outputs (`ctx.imports[from][output]`), or a `{ name, secret }`
112
+ * pair that exposes a secrets.yaml key under a different env var name.
95
113
  */
96
114
  const workerValueSchema = z.union([
97
115
  z.string(),
@@ -109,6 +127,21 @@ const workerValueSchema = z.union([
109
127
  /** Which output of that instance to read. */
110
128
  output: z.string(),
111
129
  }),
130
+ z.object({
131
+ /** Env var name inside the Worker. */
132
+ name: z.string(),
133
+ /**
134
+ * A key in this environment's secrets.yaml, exposed under `name`.
135
+ *
136
+ * The plain-string form already reads a secret, but it forces the Worker's
137
+ * env var to be spelled exactly like the secret. An app whose interface
138
+ * says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
139
+ * `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
140
+ * the same credential under a second name, which is one more thing to
141
+ * forget when it rotates. Same form, same reason, as the `fly` module's.
142
+ */
143
+ secret: z.string(),
144
+ }),
112
145
  ])
113
146
 
114
147
  type WorkerValueEntry = z.infer<typeof workerValueSchema>
@@ -133,6 +166,16 @@ function resolveWorkerValue(
133
166
  return { name: entry.name, value: entry.value }
134
167
  }
135
168
 
169
+ if ('secret' in entry) {
170
+ const value = ctx.secrets[entry.secret]
171
+ if (!value) {
172
+ throw new Error(
173
+ `${fieldName} entry "${entry.name}" references secret "${entry.secret}", which is missing from this environment's secrets.yaml`,
174
+ )
175
+ }
176
+ return { name: entry.name, value }
177
+ }
178
+
136
179
  const instanceOutputs = ctx.imports[entry.from]
137
180
  if (instanceOutputs === undefined) {
138
181
  throw new Error(
@@ -333,8 +376,10 @@ export const cloudflareModule = defineModule({
333
376
  /**
334
377
  * Worker secrets to push after deploy. Each entry is either a plain name
335
378
  * — a key in this environment's secrets.yaml, becoming a Worker secret
336
- * binding of the same name (read at runtime as `env.<NAME>`) — or a
337
- * `{ name, from, output }` reference into an imported instance's outputs.
379
+ * binding of the same name (read at runtime as `env.<NAME>`) — a
380
+ * `{ name, secret }` pair exposing a secrets.yaml key under a different
381
+ * name, or a `{ name, from, output }` reference into an imported
382
+ * instance's outputs.
338
383
  * Pushed via `wrangler secret put` with the value piped through stdin.
339
384
  */
340
385
  workerSecrets: z.array(workerValueSchema).default([]),
@@ -380,6 +425,26 @@ export const cloudflareModule = defineModule({
380
425
  * `name` declared in wrangler.jsonc.
381
426
  */
382
427
  workerName: z.string().optional(),
428
+ /**
429
+ * Hostname patterns this worker answers, e.g. `zbc.zabaca.com/*`, emitted
430
+ * as `--route`. The DNS record for the hostname is NOT created here: it
431
+ * belongs to a `cloudflare-zone` instance, and this instance should import
432
+ * that one so the record exists before the route is claimed.
433
+ *
434
+ * It lives in instance config rather than wrangler.jsonc, and that is the
435
+ * whole point. Preview PRs deploy the SAME wrangler.jsonc under a
436
+ * per-PR `workerName`, so a route declared in the file would be claimed by
437
+ * every preview deploy too — and a Cloudflare route is unique per zone, so
438
+ * the most recently deployed PR would take production's traffic, silently
439
+ * and with no error anywhere. A preview instance omits `routes` and keeps
440
+ * its `*.workers.dev` URL.
441
+ *
442
+ * Deliberately a route, not a wrangler "custom domain": a custom domain
443
+ * has wrangler create its own managed DNS record, which the zone module
444
+ * would then read as undeclared drift, and the two would argue on every
445
+ * apply.
446
+ */
447
+ routes: z.array(z.string()).default([]),
383
448
  }),
384
449
  outputs: z.object({
385
450
  deployUrl: z.string(),
@@ -465,9 +530,10 @@ export const cloudflareModule = defineModule({
465
530
  if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
466
531
  if (config.workerName) deployArgs.push('--name', config.workerName)
467
532
  if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
533
+ for (const route of config.routes) deployArgs.push('--route', route)
468
534
  for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
469
535
  console.log(
470
- ` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
536
+ ` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${config.routes.length ? ` [routes: ${config.routes.join(', ')}]` : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
471
537
  )
472
538
  let out: string
473
539
  try {
@@ -485,8 +551,13 @@ export const cloudflareModule = defineModule({
485
551
  )
486
552
  }
487
553
  const workerName = deployedMatch[1]!
554
+ // A routed worker has no workers.dev URL to print: wrangler DISABLES the
555
+ // subdomain when routes are configured and `workers_dev` is not explicitly
556
+ // true, and prints the routes instead. Falling back to the first route
557
+ // keeps `deployUrl` meaning "where this worker answers" rather than going
558
+ // empty the moment an app gets a real hostname.
488
559
  const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
489
- const deployUrl = urlMatch?.[0] ?? ''
560
+ const deployUrl = urlMatch?.[0] ?? routeUrl(config.routes)
490
561
  console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
491
562
 
492
563
  // 4. Push Worker secrets (after deploy: the script must exist first).
@@ -58,12 +58,27 @@ const flyValueSchema = z.union([
58
58
  /** Which output of that instance to read. */
59
59
  output: z.string(),
60
60
  }),
61
+ z.object({
62
+ /** Env var name inside the app. */
63
+ name: z.string(),
64
+ /**
65
+ * A key in this environment's secrets.yaml, exposed under `name`.
66
+ *
67
+ * The plain-string form already reads a secret, but it forces the app's
68
+ * env var to be spelled exactly like the secret. An app whose interface
69
+ * says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
70
+ * `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
71
+ * the same credential under a second name, which is one more thing to
72
+ * forget when it rotates.
73
+ */
74
+ secret: z.string(),
75
+ }),
61
76
  ])
62
77
 
63
78
  type FlyValueEntry = z.infer<typeof flyValueSchema>
64
79
 
65
80
  /** Resolve a flySecrets entry to its `{ name, value }` pair. */
66
- function resolveFlyValue(
81
+ export function resolveFlyValue(
67
82
  entry: FlyValueEntry,
68
83
  ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
69
84
  fieldName: string,
@@ -82,6 +97,17 @@ function resolveFlyValue(
82
97
  return { name: entry.name, value: entry.value }
83
98
  }
84
99
 
100
+ if ('secret' in entry) {
101
+ const value = ctx.secrets[entry.secret]
102
+ if (!value) {
103
+ throw new Error(
104
+ `${fieldName} entry "${entry.name}" reads secret "${entry.secret}", ` +
105
+ "which is missing from this environment's secrets.yaml",
106
+ )
107
+ }
108
+ return { name: entry.name, value }
109
+ }
110
+
85
111
  const instanceOutputs = ctx.imports[entry.from]
86
112
  if (!instanceOutputs) {
87
113
  throw new Error(
@@ -128,6 +154,76 @@ function fly(
128
154
  /** Read `app = "name"` out of the package's fly.toml. The app name belongs to
129
155
  * the package's own topology file; `appName` in config only overrides it (the
130
156
  * per-PR preview case, mirroring the cloudflare module's `workerName`). */
157
+ /** Did `fly deploy` say, in its own words, that machines reached a good state?
158
+ *
159
+ * Exit 0 is not the signal — flyctl prints its build and then exits 0 on paths
160
+ * where nothing converged, which is what the caller's guard exists to catch.
161
+ * The vocabulary differs by path, and the guard originally knew only the
162
+ * first-launch half:
163
+ *
164
+ * launching a new machine -> "Finished launching new machines"
165
+ * a machine-less group -> "No machines in group"
166
+ * non-rolling update -> "update finished: success"
167
+ * ROLLING update -> "✔ Machine <id> is now in a good state"
168
+ *
169
+ * The last line is the one that was missing, and it is the line every deploy
170
+ * after the first prints. zbc-walgit was launched by hand, so CI's first run
171
+ * against it took the rolling path and the guard failed a deploy that had in
172
+ * fact converged (run 32881480843, 2026-08-25). A false red on a healthy
173
+ * deploy costs the guard its credibility as surely as a false green does.
174
+ *
175
+ * "reached stopped state" is NOT convergence and is deliberately not matched:
176
+ * flyctl prints it for an auto-stopped machine on its way to a good state, and
177
+ * also for one that stopped because it died. Only the good-state line settles it.
178
+ */
179
+ export function machinesConverged(out: string): boolean {
180
+ return /(update finished: success|Finished launching new machines|No machines? in group|Machine \w+ is now in a good state)/.test(
181
+ out,
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Which of `wanted` has no certificate yet, given `fly certs list` output.
187
+ *
188
+ * Pure, and separated from apply because the cost of getting it wrong is
189
+ * asymmetric and invisible: `fly certs add` on a hostname that already has a
190
+ * certificate EXITS NON-ZERO, so a hostname wrongly judged absent fails the
191
+ * whole apply, while one wrongly judged present leaves the app serving a
192
+ * default certificate that every client rejects by name.
193
+ *
194
+ * Matching is on the first whitespace-delimited field of each line, never a
195
+ * substring: `git.zabaca.com` appears inside `www.git.zabaca.com`, and a
196
+ * substring test would skip a certificate that was never requested.
197
+ */
198
+ export function certsToRequest(listOutput: string, wanted: string[]): string[] {
199
+ const present = new Set(
200
+ listOutput
201
+ .split('\n')
202
+ .map((line) => line.trim().split(/\s+/)[0])
203
+ .filter(Boolean),
204
+ )
205
+ return wanted.filter((hostname) => !present.has(hostname))
206
+ }
207
+
208
+ /**
209
+ * Machines in the `app` process group, from `fly scale show` output.
210
+ *
211
+ * Returns undefined when the output cannot be read as a table — a flyctl
212
+ * version that reworded it, or a call that failed. Undefined means "do not
213
+ * scale", never "scale to zero": guessing a count from output this did not
214
+ * understand would destroy machines, and the safe direction when the evidence
215
+ * is unreadable is to leave the app alone and let the next apply try again.
216
+ */
217
+ export function machineCount(scaleShowOutput: string): number | undefined {
218
+ for (const line of scaleShowOutput.split('\n')) {
219
+ const cells = line.split('│').map((cell) => cell.trim())
220
+ if (cells.length < 2 || cells[0] !== 'app') continue
221
+ const count = Number(cells[1])
222
+ if (Number.isInteger(count) && count >= 0) return count
223
+ }
224
+ return undefined
225
+ }
226
+
131
227
  function appNameFromFlyToml(workdir: string): string | undefined {
132
228
  const tomlPath = path.join(workdir, 'fly.toml')
133
229
  if (!fs.existsSync(tomlPath)) return undefined
@@ -159,7 +255,9 @@ export const flyModule = defineModule({
159
255
  /**
160
256
  * App secrets, staged before deploy. Each entry is either a plain name (a
161
257
  * key in this environment's secrets.yaml), `{ name, value }` for a literal,
162
- * or `{ name, from, output }` to pull from an imported instance's outputs.
258
+ * `{ name, secret }` to expose a secrets.yaml key under a different env var
259
+ * name, or `{ name, from, output }` to pull from an imported instance's
260
+ * outputs.
163
261
  */
164
262
  flySecrets: z.array(flyValueSchema).default([]),
165
263
  /**
@@ -178,6 +276,16 @@ export const flyModule = defineModule({
178
276
  * for a builder machine to spin up.
179
277
  */
180
278
  localBuild: z.boolean().default(false),
279
+ /**
280
+ * Custom hostnames Fly should hold a TLS certificate for, e.g.
281
+ * `git.zabaca.com`. Each is requested once and left alone thereafter.
282
+ *
283
+ * The DNS record for the hostname must already point at this app, or Fly
284
+ * has nothing to validate against and the certificate sits pending — so
285
+ * the instance declaring a cert should `imports` whatever manages that
286
+ * record, to order the two within one apply.
287
+ */
288
+ certs: z.array(z.string()).default([]),
181
289
  /** Destroy+recreate the whole app on every apply (preview environments). */
182
290
  ephemeral: z.boolean().default(false),
183
291
  }),
@@ -235,7 +343,23 @@ export const flyModule = defineModule({
235
343
  fly(workdir, ['ips', 'allocate-v6', '-a', appName], env)
236
344
  }
237
345
 
238
- // 3. Optional local build. Inherit stdio so build output streams.
346
+ // 3. Custom hostname certificates. Requested before the deploy rather than
347
+ // after, because issuance is asynchronous on Fly's side and a deploy can
348
+ // take minutes — asking first lets validation run during it.
349
+ //
350
+ // `fly certs add` on a hostname that already has a certificate is an
351
+ // error, not a no-op, so this lists first and matches whole lines: a
352
+ // substring test would see `git.zabaca.com` inside `www.git.zabaca.com`
353
+ // and skip a certificate that was never requested.
354
+ if (config.certs.length > 0) {
355
+ const listed = fly(workdir, ['certs', 'list', '-a', appName], env).out
356
+ for (const hostname of certsToRequest(listed, config.certs)) {
357
+ console.log(` Requesting certificate for ${hostname}`)
358
+ fly(workdir, ['certs', 'add', hostname, '-a', appName], env)
359
+ }
360
+ }
361
+
362
+ // 4. Optional local build. Inherit stdio so build output streams.
239
363
  if (config.build) {
240
364
  const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
241
365
  console.log(
@@ -244,11 +368,11 @@ export const flyModule = defineModule({
244
368
  execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
245
369
  }
246
370
 
247
- // 4. Resolve every secret BEFORE staging so a bad reference fails fast,
371
+ // 5. Resolve every secret BEFORE staging so a bad reference fails fast,
248
372
  // without leaving a half-configured app. `resolveFlyValue` is pure.
249
373
  const resolved = config.flySecrets.map((entry) => resolveFlyValue(entry, ctx, 'flySecrets'))
250
374
 
251
- // 5. Stage secrets. `--stage` withholds the deployment that `fly secrets
375
+ // 6. Stage secrets. `--stage` withholds the deployment that `fly secrets
252
376
  // set` would otherwise trigger; step 6 picks them up. Values go on the
253
377
  // command line as NAME=VALUE — flyctl offers no stdin form — so they are
254
378
  // visible to a local process listing, though never logged here.
@@ -268,7 +392,7 @@ export const flyModule = defineModule({
268
392
  console.log(` Staged secrets: ${resolved.map((s) => s.name).join(', ')}`)
269
393
  }
270
394
 
271
- // 6. Deploy.
395
+ // 7. Deploy.
272
396
  const deployArgs = ['deploy', '-a', appName, '--yes']
273
397
  if (!config.highAvailability) deployArgs.push('--ha=false')
274
398
  if (config.localBuild) deployArgs.push('--local-only')
@@ -279,15 +403,13 @@ export const flyModule = defineModule({
279
403
 
280
404
  // Success-theater guard, same lesson as the cloudflare module: require a
281
405
  // 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
- ) {
406
+ if (!machinesConverged(out)) {
285
407
  throw new Error(
286
408
  `fly deploy exited 0 but printed no machine-convergence confirmation:\n${out}`,
287
409
  )
288
410
  }
289
411
 
290
- // 7. Read the IPs back for outputs — dependents need the address, and after
412
+ // 8. Read the IPs back for outputs — dependents need the address, and after
291
413
  // step 2 it is whatever Fly actually holds, not what we asked for.
292
414
  const finalIps = fly(workdir, ['ips', 'list', '-a', appName], env)
293
415
  const v4 = finalIps.out.match(/\bv4\s*│\s*([0-9.]+)/)?.[1] ?? ''
@@ -295,6 +417,24 @@ export const flyModule = defineModule({
295
417
  const hostname = `${appName}.fly.dev`
296
418
  console.log(` Deployed: ${hostname}${v4 ? ` (${v4})` : ''}`)
297
419
 
420
+ // 9. Machine count. This is NOT what `--ha` on the deploy above does:
421
+ // flyctl's `--ha` provisions a spare only when it is FIRST launching an
422
+ // app, and a deploy to an app that already exists keeps whatever count
423
+ // it has. So `highAvailability: true` on a live app changed nothing and
424
+ // said nothing — the deploy reported success either way, which is the
425
+ // failure this module already learned to distrust once.
426
+ //
427
+ // `fly scale count` is the converging form, and it runs AFTER the deploy
428
+ // so a machine created here starts from the image just released rather
429
+ // than the previous one.
430
+ const wanted = config.highAvailability ? 2 : 1
431
+ const shown = fly(workdir, ['scale', 'show', '-a', appName], env, { allowFailure: true })
432
+ const current = machineCount(shown.out)
433
+ if (current !== undefined && current !== wanted) {
434
+ console.log(` Scaling machines: ${current} → ${wanted}`)
435
+ fly(workdir, ['scale', 'count', String(wanted), '-a', appName, '--yes'], env)
436
+ }
437
+
298
438
  return { appName, hostname, ipv4: v4, ipv6: v6 }
299
439
  },
300
440
  async destroy(config, ctx) {
@@ -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({
@@ -144,9 +183,10 @@ export const tursoModule = defineModule({
144
183
 
145
184
  if (config.migrationsDir) {
146
185
  const { resolve } = await import('node:path')
147
- const { createClient: createLibsqlClient } = await import('@libsql/client')
148
- const { drizzle } = await import('drizzle-orm/libsql')
149
- const { migrate } = await import('drizzle-orm/libsql/migrator')
186
+ const { createClient: createLibsqlClient } =
187
+ await importOptional<LibsqlClientModule>('@libsql/client')
188
+ const { drizzle } = await importOptional<DrizzleLibsqlModule>('drizzle-orm/libsql')
189
+ const { migrate } = await importOptional<DrizzleMigratorModule>('drizzle-orm/libsql/migrator')
150
190
 
151
191
  const folder = resolve(ctx.projectRoot, config.migrationsDir)
152
192
  const migrationClient = createLibsqlClient({
@@ -12,7 +12,7 @@
12
12
  "devDependencies": {
13
13
  "@types/bun": "^1.3.14",
14
14
  "@types/node": "^25.6.0",
15
- "typescript": "^5.7.0"
15
+ "typescript": "^7.0.2"
16
16
  },
17
17
  "scripts": {
18
18
  "test": "bun test",
@@ -1,59 +0,0 @@
1
- #!/bin/sh
2
- # walgit boot: materialize SSH identity from secrets, then supervise sshd and
3
- # the smart-HTTP server as one unit.
4
- set -eu
5
-
6
- REPOS_DIR="${WALGIT_REPOS_DIR:-/srv/walgit/repos}"
7
- mkdir -p "$REPOS_DIR"
8
- chown git:git "$REPOS_DIR"
9
-
10
- # The host key comes from a secret because the container filesystem does not
11
- # survive a machine stop. A generated-on-boot key would change on every
12
- # autostart and every client would see the SSH man-in-the-middle warning — on a
13
- # host designed to stop whenever it is idle, that is every day.
14
- if [ -n "${WALGIT_SSH_HOST_KEY:-}" ]; then
15
- printf '%s\n' "$WALGIT_SSH_HOST_KEY" > /etc/ssh/ssh_host_ed25519_key
16
- chmod 600 /etc/ssh/ssh_host_ed25519_key
17
- ssh-keygen -y -f /etc/ssh/ssh_host_ed25519_key > /etc/ssh/ssh_host_ed25519_key.pub
18
- else
19
- echo "walgit: WALGIT_SSH_HOST_KEY is unset — generating an EPHEMERAL host key." >&2
20
- echo "walgit: clients will see a changed host key after every machine stop." >&2
21
- ssh-keygen -q -t ed25519 -N '' -f /etc/ssh/ssh_host_ed25519_key
22
- fi
23
-
24
- # Every authorized key is pinned to the forced command. The client's own command
25
- # line is then never executed — it arrives as SSH_ORIGINAL_COMMAND and is parsed
26
- # by src/repo.ts, which allows exactly two git verbs and one repository name.
27
- AUTH_KEYS=/srv/walgit/.ssh/authorized_keys
28
- : > "$AUTH_KEYS"
29
- if [ -n "${WALGIT_SSH_AUTHORIZED_KEYS:-}" ]; then
30
- printf '%s\n' "$WALGIT_SSH_AUTHORIZED_KEYS" | while IFS= read -r key; do
31
- case "$key" in
32
- ''|\#*) continue ;;
33
- esac
34
- printf 'command="bun /app/src/ssh-shell.ts",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty %s\n' "$key" >> "$AUTH_KEYS"
35
- done
36
- fi
37
- chown git:git "$AUTH_KEYS"
38
- chmod 600 "$AUTH_KEYS"
39
- if [ ! -s "$AUTH_KEYS" ]; then
40
- echo "walgit: no authorized keys — SSH will refuse every client (set WALGIT_SSH_AUTHORIZED_KEYS)." >&2
41
- fi
42
-
43
- # Two processes, one machine lifetime: if either half dies the machine should
44
- # stop rather than keep serving half a git host, so each kills the other.
45
- /usr/sbin/sshd -D -e &
46
- SSHD=$!
47
- bun /app/src/server.ts &
48
- HTTP=$!
49
-
50
- term() { kill "$SSHD" "$HTTP" 2>/dev/null || true; }
51
- trap term TERM INT
52
-
53
- # Polled rather than `wait -n`, which busybox ash does not reliably provide.
54
- while kill -0 "$SSHD" 2>/dev/null && kill -0 "$HTTP" 2>/dev/null; do
55
- sleep 5
56
- done
57
- echo "walgit: a server process exited — stopping the machine." >&2
58
- term
59
- exit 1
@@ -1,52 +0,0 @@
1
- # walgit on Fly. The topology lives here, not in the zbc `fly` module — the
2
- # module only runs `fly deploy` against this file.
3
- #
4
- # The app name is a per-project identity, so an instance in a consumer's
5
- # environment overrides it with `appName`. This default is what `fly deploy`
6
- # uses if nothing does.
7
- app = "walgit"
8
- primary_region = "sjc"
9
-
10
- [build]
11
-
12
- # SSH: RAW TCP PASS-THROUGH. The absence of `handlers` is what makes it raw —
13
- # adding one would make Fly Proxy try to speak HTTP or TLS to a git client and
14
- # every connection would fail. Verified against real Fly in the walgit M0 spike
15
- # (docs/research/walgit-m0-spike/ in the zbc repository).
16
- #
17
- # A dedicated IPv4 is REQUIRED for this to be reachable at all: shared IPv4
18
- # covers ports 80/443 only, and nothing reports the difference. The instance
19
- # sets `ipv4: "dedicated"`.
20
- [[services]]
21
- protocol = "tcp"
22
- internal_port = 22
23
- auto_stop_machines = "stop"
24
- auto_start_machines = true
25
- min_machines_running = 0
26
-
27
- [[services.ports]]
28
- port = 22
29
-
30
- # smart-HTTP. Same autostop policy, so both front doors wake the same machine;
31
- # the M0 spike measured a raw-TCP cold start at ~1.35 s, which a git client
32
- # spends waiting and never notices.
33
- [[services]]
34
- protocol = "tcp"
35
- internal_port = 8080
36
- auto_stop_machines = "stop"
37
- auto_start_machines = true
38
- min_machines_running = 0
39
-
40
- [[services.ports]]
41
- port = 80
42
- handlers = ["http"]
43
- force_https = true
44
-
45
- [[services.ports]]
46
- port = 443
47
- handlers = ["tls", "http"]
48
-
49
- # No [[mounts]]. Deliberate: see the Dockerfile — the repo on disk is a cache.
50
- [[vm]]
51
- size = "shared-cpu-1x"
52
- memory = "512mb"
@@ -1,36 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * The SSH forced command.
4
- *
5
- * Every authorized key is pinned to this script (`command="..."` in
6
- * authorized_keys), so an SSH session can do exactly one thing: run one git
7
- * transport verb against one repository. The client's own command line arrives
8
- * in SSH_ORIGINAL_COMMAND and is parsed, never executed.
9
- *
10
- * git's transport is stdio: upload-pack/receive-pack speak the pack protocol
11
- * over the same stdin/stdout the SSH channel provides, which is why this
12
- * process replaces itself with git rather than proxying bytes.
13
- */
14
-
15
- import { spawnSync } from 'node:child_process'
16
- import { ensureBareRepo, parseSshCommand, resolveRepo } from './repo'
17
- import { storeFromEnv } from './store-env'
18
- import { syncRepo } from './sync'
19
-
20
- const reposDir = process.env.WALGIT_REPOS_DIR ?? '/srv/walgit/repos'
21
-
22
- try {
23
- const { service, requested } = parseSshCommand(process.env.SSH_ORIGINAL_COMMAND)
24
- const repo = ensureBareRepo(resolveRepo(reposDir, requested))
25
- // Before a byte of the pack protocol is exchanged: an upload-pack that
26
- // advertises stale refs sends the client a repository that no longer exists,
27
- // and a receive-pack negotiating against them computes its ref updates from
28
- // a state the log has already moved past.
29
- await syncRepo(storeFromEnv(), repo)
30
- const res = spawnSync(service, [repo.dir], { stdio: 'inherit' })
31
- process.exit(res.status ?? 1)
32
- } catch (err) {
33
- // Goes back over the SSH channel to the client, which prints it verbatim.
34
- process.stderr.write(`walgit: ${(err as Error).message}\n`)
35
- process.exit(1)
36
- }
@@ -1,38 +0,0 @@
1
- # walgit sshd. Everything here narrows what a session can be: the forced command
2
- # on each authorized key is the real gate, and this file removes every other way
3
- # in.
4
-
5
- Port 22
6
- AddressFamily any
7
- HostKey /etc/ssh/ssh_host_ed25519_key
8
-
9
- # Only the `git` account, only by public key.
10
- AllowUsers git
11
- PermitRootLogin no
12
- PasswordAuthentication no
13
- KbdInteractiveAuthentication no
14
- ChallengeResponseAuthentication no
15
- PubkeyAuthentication yes
16
- AuthorizedKeysFile /srv/walgit/.ssh/authorized_keys
17
-
18
- # git speaks over the session channel and needs nothing else. A forwarded port
19
- # would turn a repo credential into network access to the machine.
20
- AllowTcpForwarding no
21
- AllowAgentForwarding no
22
- X11Forwarding no
23
- PermitTunnel no
24
- PermitTTY no
25
-
26
- # Fly Proxy holds the client connection; sshd sees only the proxy, so keepalives
27
- # here are what notice a client that vanished mid-fetch.
28
- ClientAliveInterval 60
29
- ClientAliveCountMax 3
30
-
31
- # Machines stop when idle and start on a raw TCP connection, so an unauthenticated
32
- # connection is a real cost, not just a socket. Keep the window short.
33
- LoginGraceTime 20
34
- MaxStartups 20:30:60
35
-
36
- # stderr, so Fly captures it in the machine log rather than a file on a disk
37
- # that disappears.
38
- LogLevel INFO