@zabaca/zbc 0.22.0 → 0.23.1

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 (44) hide show
  1. package/package.json +1 -1
  2. package/templates/CLAUDE.md +5 -0
  3. package/templates/apps/walgit/CONTEXT.md +5 -1
  4. package/templates/apps/walgit/README.md +164 -27
  5. package/templates/apps/walgit/package.json +2 -2
  6. package/templates/apps/walgit/registry.json +1 -1
  7. package/templates/apps/walgit/shared/browse.ts +18 -4
  8. package/templates/apps/walgit/shared/capabilities.ts +28 -3
  9. package/templates/apps/walgit/shared/container-env.ts +41 -2
  10. package/templates/apps/walgit/shared/container-lifecycle.ts +239 -0
  11. package/templates/apps/walgit/shared/container-snapshot.ts +219 -0
  12. package/templates/apps/walgit/shared/edge-refs.ts +612 -0
  13. package/templates/apps/walgit/{src → shared}/instructions.ts +8 -4
  14. package/templates/apps/walgit/shared/keys.ts +17 -0
  15. package/templates/apps/walgit/shared/landing.ts +10 -3
  16. package/templates/apps/walgit/shared/llms.ts +24 -7
  17. package/templates/apps/walgit/shared/policy.ts +1 -1
  18. package/templates/apps/walgit/shared/protocol.ts +35 -0
  19. package/templates/apps/walgit/shared/sleep-after.ts +44 -0
  20. package/templates/apps/walgit/shared/wal-index.ts +22 -1
  21. package/templates/apps/walgit/src/boot-residue.ts +58 -0
  22. package/templates/apps/walgit/src/cache.ts +9 -0
  23. package/templates/apps/walgit/src/cli.ts +39 -4
  24. package/templates/apps/walgit/src/delete-repo.ts +58 -9
  25. package/templates/apps/walgit/src/edge-refs.ts +148 -0
  26. package/templates/apps/walgit/src/expire.ts +75 -7
  27. package/templates/apps/walgit/src/hook-main.ts +2 -0
  28. package/templates/apps/walgit/src/http.ts +17 -4
  29. package/templates/apps/walgit/src/materialize.ts +34 -15
  30. package/templates/apps/walgit/src/private.ts +6 -2
  31. package/templates/apps/walgit/src/push.ts +34 -8
  32. package/templates/apps/walgit/src/reconcile.ts +6 -1
  33. package/templates/apps/walgit/src/server.ts +69 -8
  34. package/templates/apps/walgit/src/sync.ts +10 -2
  35. package/templates/apps/walgit/worker/container-binding.ts +104 -0
  36. package/templates/apps/walgit/worker/durable-container.ts +786 -0
  37. package/templates/apps/walgit/worker/events-do.ts +16 -12
  38. package/templates/apps/walgit/worker/index.ts +235 -17
  39. package/templates/apps/walgit/worker/mcp.ts +9 -4
  40. package/templates/apps/walgit/wrangler.jsonc +44 -33
  41. package/templates/claude/settings.json +8 -0
  42. package/templates/infra/modules/cloudflare/index.ts +9 -0
  43. package/templates/infra/modules/d1/index.ts +30 -4
  44. package/templates/infra/modules/d1/registry.json +1 -1
@@ -11,12 +11,17 @@
11
11
  * straight to this port.
12
12
  */
13
13
 
14
+ import * as fs from 'node:fs'
15
+
14
16
  import { capabilitiesFrom } from '../shared/capabilities'
17
+ import { BOOT_MARKER } from '../shared/container-snapshot'
15
18
  import { parseTokens } from '../shared/credentials'
16
19
  import { listCommits, listTree, readBlob, statBlob } from './browse'
20
+ import { clearBootResidue } from './boot-residue'
17
21
  import { ensureBareRepo } from './cache'
18
- import { configuredExpiryMs, expireRepos } from './expire'
19
- import { createHttpHandler } from './http'
22
+ import { publishUploadPackAtBoot } from './edge-refs'
23
+ import { configuredClaimedExpiryMs, configuredExpiryMs, expireRepos } from './expire'
24
+ import { createHttpHandler, type SweepOptions } from './http'
20
25
  import { privateReposConfigError, privateReposEnabled, privateReposSeed } from './private'
21
26
  import { gitAncestry, isProposalRef, listProposals } from './proposals'
22
27
  import { resolveRepo } from './repo'
@@ -127,6 +132,7 @@ if (privateSeed && !store) {
127
132
  * retention promise from — so the page and the sweeper can never disagree.
128
133
  */
129
134
  const expiryMs = configuredExpiryMs()
135
+ const claimedExpiryMs = configuredClaimedExpiryMs()
130
136
 
131
137
  /**
132
138
  * What this process actually booted with, printed once.
@@ -149,6 +155,7 @@ const expiryMs = configuredExpiryMs()
149
155
  console.log(
150
156
  `walgit boot: public=${isPublic} appendOnly=${caps.appendOnly} ` +
151
157
  `retentionHours=${caps.retentionHours ?? 'off'} ` +
158
+ `claimedRetentionHours=${caps.claimedRetentionHours ?? 'off'} ` +
152
159
  `maxPush=${caps.maxPushBytes ?? 'unset'} maxRepo=${caps.maxRepoBytes ?? 'unset'} ` +
153
160
  `private=${caps.namesCanBePrivate} ` +
154
161
  `perSource=${
@@ -168,15 +175,24 @@ console.log(
168
175
  * too, but this line is the one that survives in the container's own log when
169
176
  * the question is what the sweeper actually did.
170
177
  */
171
- async function runSweep(logStore: ObjectStore, windowMs: number) {
172
- const result = await expireRepos(logStore, { windowMs, dryRun: false, reposDir })
178
+ async function runSweep(logStore: ObjectStore, windowMs: number, opts: SweepOptions) {
179
+ const result = await expireRepos(logStore, {
180
+ windowMs,
181
+ claimedWindowMs: claimedExpiryMs,
182
+ collectOnly: opts.collectOnly,
183
+ dryRun: false,
184
+ reposDir,
185
+ })
173
186
  console.log(
174
- `walgit expire: collected ${result.collected.length}, retained ${result.retained.length}`,
187
+ `walgit expire${opts.collectOnly ? ' (collect only)' : ''}: ` +
188
+ `collected ${result.collected.length}, retained ${result.retained.length}`,
175
189
  )
176
190
  return {
177
191
  collected: result.collected.map((o) => ({ repoId: o.repoId, reason: o.decision.reason })),
178
192
  retained: result.retained.length,
179
193
  windowMs: result.windowMs,
194
+ claimedWindowMs: result.claimedWindowMs,
195
+ collectOnly: result.collectOnly,
180
196
  }
181
197
  }
182
198
 
@@ -195,7 +211,7 @@ try {
195
211
  // endpoint should not exist for it — `expireRepos` would return an empty
196
212
  // report either way, but a deployment that cannot collect anything should
197
213
  // not answer as though it might.
198
- sweep: store && expiryMs !== null ? () => runSweep(store, expiryMs) : undefined,
214
+ sweep: store && expiryMs !== null ? (opts) => runSweep(store, expiryMs, opts) : undefined,
199
215
  // Answered from the Index, so a ref-event handshake states what is
200
216
  // published rather than what this node's disk happens to hold. Absent
201
217
  // without a store, in which case there is nothing authoritative to read
@@ -260,7 +276,13 @@ try {
260
276
  ? {
261
277
  readIndex: async (repoId) => {
262
278
  const { index, etag } = await loadIndex(store, repoId)
263
- return etag === null ? null : { refs: index.refs, lastPush: lastPushOf(index) }
279
+ return etag === null
280
+ ? null
281
+ : {
282
+ refs: index.refs,
283
+ lastPush: lastPushOf(index),
284
+ claimed: index.claim !== undefined,
285
+ }
264
286
  },
265
287
  listTree: (repo, rev, path) => listTree(repo.dir, rev, path),
266
288
  statBlob: (repo, rev, path) => statBlob(repo.dir, rev, path),
@@ -296,5 +318,44 @@ try {
296
318
  process.exit(1)
297
319
  }
298
320
 
299
- Bun.serve({ port, idleTimeout: 0, fetch: handler })
321
+ // Before the port opens, because the port opening is what the Durable Object
322
+ // takes to mean "ready": a disk restored from a snapshot can carry a dead
323
+ // push's hand-off record and a materialize lock, and no request may see either
324
+ // (src/boot-residue.ts). Logged only when it found something, which on a disk
325
+ // that was not restored is never.
326
+ const residue = clearBootResidue(reposDir)
327
+ // After the residue goes, so clearing it does not read as a change: the stop
328
+ // compares the cache against this marker to decide whether a new snapshot is
329
+ // worth taking (`needsNewSnapshot`, shared/container-snapshot.ts).
330
+ try {
331
+ fs.writeFileSync(BOOT_MARKER, reposDir)
332
+ } catch (err) {
333
+ console.warn(`walgit: could not write ${BOOT_MARKER}: ${(err as Error).message}`)
334
+ }
335
+ if (residue.cleared.length > 0) {
336
+ console.log(
337
+ `walgit: cleared ${residue.cleared.length} stale lock/hand-off path(s) across ${residue.repos} cached repo(s)`,
338
+ )
339
+ }
340
+
341
+ const server = Bun.serve({ port, idleTimeout: 0, fetch: handler })
342
+
343
+ // What this image's git advertises, published for the edge to answer ref
344
+ // checks with while this container sleeps (`src/edge-refs.ts`). After the
345
+ // listener is up and never awaited: the request that woke this container is
346
+ // served the ordinary way either way, and so is every one until this lands.
347
+ if (store) void publishUploadPackAtBoot(store)
348
+
349
+ // The container's idle stop is a SIGTERM (`stopContainer` in
350
+ // worker/durable-container.ts), and this process is PID 1, which the kernel
351
+ // exempts from every signal it has no handler for. Without this the stop was
352
+ // ignored, the container ran around the clock, and the Durable Object in front
353
+ // of it stayed awake polling it. Stop accepting, let the requests in flight
354
+ // finish, then exit — nothing durable is lost by going, since a push is
355
+ // acknowledged only once the log holds it. The Durable Object kills the
356
+ // container outright if this has not happened within its grace period.
357
+ process.on('SIGTERM', () => {
358
+ console.log('walgit: SIGTERM, draining and exiting')
359
+ void server.stop().finally(() => process.exit(0))
360
+ })
300
361
  console.log(`walgit smart-HTTP listening on :${port} (repos: ${reposDir})`)
@@ -23,7 +23,7 @@
23
23
 
24
24
  import type { ObjectStore } from '../shared/store'
25
25
  import type { ResolvedRepo } from './repo'
26
- import { isPartial, materialize, type MaterializeStats } from './materialize'
26
+ import { ensureHead, isPartial, materialize, type MaterializeStats } from './materialize'
27
27
  import { reconcile, type ReconcileResult } from './reconcile'
28
28
  import { loadIndex } from '../shared/wal-index'
29
29
 
@@ -47,7 +47,15 @@ export async function syncRepo(
47
47
  // `isPartial` covers the case reconcile cannot see: an interrupted restore
48
48
  // that happened to finish placing the packs its refs need, but died before
49
49
  // the rest. The marker is the only evidence, so it is trusted over the refs.
50
- if (reconciled.missing.length === 0 && !isPartial(repo.dir)) return reconciled
50
+ if (reconciled.missing.length === 0 && !isPartial(repo.dir)) {
51
+ // HEAD as well as the refs, on every access and not only on a restore: a
52
+ // push moves refs without touching HEAD, so a first push of `feature`
53
+ // leaves it on the unborn `main` `git init` chose until something points
54
+ // it at the Default Branch — and the edge, answering `ls-refs` from the
55
+ // Index, already reports that branch (`shared/edge-refs.ts`).
56
+ ensureHead(repo.dir, index.refs)
57
+ return reconciled
58
+ }
51
59
 
52
60
  const result = await materialize(store, repo, index)
53
61
  return { ...result.reconciled, materialize: result.stats }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Which container a request goes to — the one seam every caller of the
3
+ * container uses (the proxy, the browse and raw routes, the sweep, the MCP
4
+ * reads, the ref-event object).
5
+ *
6
+ * Two container applications exist while a deployment moves from the
7
+ * `default` scheduling policy to `durable_object`, each behind its own Durable
8
+ * Object binding, and `WALGIT_CONTAINER_POLICY` picks one
9
+ * (`containerPolicyFrom`, shared/container-lifecycle.ts). Unset is the old one.
10
+ * That default is the point: `wrangler deploy` puts a Worker live before it
11
+ * creates the container application the Worker's new binding needs, so the
12
+ * deploy that introduces `WalgitDurableContainer` must not also route to it.
13
+ * README.md, "Deployment", has the phases.
14
+ *
15
+ * Both are reached the same way — one named object, `fetch` — so a caller holds
16
+ * a `ContainerFetcher` and never learns which application answered.
17
+ */
18
+
19
+ import { type Container, getContainer } from '@cloudflare/containers'
20
+
21
+ import { containerPolicyFrom } from '../shared/container-lifecycle'
22
+ import { SERVED_HEADER } from '../shared/protocol'
23
+ import { containerHost, type WalgitDurableContainer } from './durable-container'
24
+
25
+ /** The bindings and the switch, as every caller's environment carries them. */
26
+ export interface ContainerBindings {
27
+ /**
28
+ * The `default`-policy application's object (`WalgitContainer`). The BASE
29
+ * class rather than the subclass, which is defined in index.ts — and index.ts
30
+ * imports this file. All any caller does with it is `fetch`.
31
+ */
32
+ WALGIT_CONTAINER?: DurableObjectNamespace<Container>
33
+ /**
34
+ * The `durable_object`-policy application's object. Optional so a Worker
35
+ * deployed from a config that predates it still typechecks against reality:
36
+ * without the binding, the switch below has nothing to switch to.
37
+ */
38
+ WALGIT_DURABLE_CONTAINER?: DurableObjectNamespace<WalgitDurableContainer>
39
+ /** `durable_object` to route to the new application. Edge-only. */
40
+ WALGIT_CONTAINER_POLICY?: string
41
+ }
42
+
43
+ export interface ContainerFetcher {
44
+ fetch(request: Request): Promise<Response>
45
+ }
46
+
47
+ /**
48
+ * The container this deployment routes to.
49
+ *
50
+ * A switch set to `durable_object` on a Worker with no such binding is a
51
+ * configuration that cannot be honoured, and the answer is the old container
52
+ * with an error in the log rather than a refusal of every git request: the
53
+ * old application is still the one that exists.
54
+ */
55
+ export function containerFor(env: ContainerBindings): ContainerFetcher {
56
+ return retryingReads(pickContainer(env))
57
+ }
58
+
59
+ /**
60
+ * Send a bodiless read once more when the container never answered it.
61
+ *
62
+ * A deploy resets the Durable Object in front of the container, and a request
63
+ * caught mid-start in that moment is answered `500 Failed to start container:
64
+ * Durable Object reset because its code was updated` — by the object, with no
65
+ * `SERVED_HEADER`, because the container never saw it. The object's own retry
66
+ * dies with it, so the one that works is out here, against the NEW object. Only
67
+ * GET/HEAD, which carry no body to have been consumed, and only once.
68
+ */
69
+ /** The runtime's words when a deploy resets a Durable Object mid-request. */
70
+ const RESET_BY_DEPLOY = 'reset because its code was updated'
71
+
72
+ function retryingReads(target: ContainerFetcher): ContainerFetcher {
73
+ return {
74
+ async fetch(request) {
75
+ const response = await target.fetch(request)
76
+ const read = request.method === 'GET' || request.method === 'HEAD'
77
+ if (!read || response.status !== 500 || response.headers.has(SERVED_HEADER)) return response
78
+ // Only the reset. A start that genuinely failed already took its budget,
79
+ // and a second attempt would double the wait it was capped to avoid.
80
+ const text = await response.text()
81
+ if (!text.includes(RESET_BY_DEPLOY)) {
82
+ return new Response(text, { status: response.status, headers: response.headers })
83
+ }
84
+ return target.fetch(request)
85
+ },
86
+ }
87
+ }
88
+
89
+ function pickContainer(env: ContainerBindings): ContainerFetcher {
90
+ if (containerPolicyFrom(env) === 'durable_object') {
91
+ if (env.WALGIT_DURABLE_CONTAINER) return containerHost(env.WALGIT_DURABLE_CONTAINER)
92
+ console.error(
93
+ 'walgit: WALGIT_CONTAINER_POLICY=durable_object but no WALGIT_DURABLE_CONTAINER binding; ' +
94
+ 'routing to the default-policy container',
95
+ )
96
+ }
97
+ // A config that binds only the new class has nothing else to route to, so
98
+ // the switch is moot: this is every deployment after phase 3.
99
+ if (!env.WALGIT_CONTAINER) {
100
+ if (env.WALGIT_DURABLE_CONTAINER) return containerHost(env.WALGIT_DURABLE_CONTAINER)
101
+ throw new Error('walgit: no container binding (WALGIT_DURABLE_CONTAINER) configured')
102
+ }
103
+ return getContainer(env.WALGIT_CONTAINER)
104
+ }