@zabaca/zbc 0.21.1 → 0.23.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 (44) hide show
  1. package/package.json +6 -1
  2. package/templates/CLAUDE.md +5 -0
  3. package/templates/apps/walgit/CONTEXT.md +5 -1
  4. package/templates/apps/walgit/README.md +159 -24
  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 +14 -5
  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/push.ts +34 -8
  31. package/templates/apps/walgit/src/reconcile.ts +6 -1
  32. package/templates/apps/walgit/src/server.ts +69 -8
  33. package/templates/apps/walgit/src/sync.ts +10 -2
  34. package/templates/apps/walgit/worker/container-binding.ts +104 -0
  35. package/templates/apps/walgit/worker/durable-container.ts +786 -0
  36. package/templates/apps/walgit/worker/events-do.ts +16 -12
  37. package/templates/apps/walgit/worker/index.ts +235 -17
  38. package/templates/apps/walgit/worker/mcp.ts +9 -4
  39. package/templates/apps/walgit/wrangler.jsonc +44 -33
  40. package/templates/claude/settings.json +8 -0
  41. package/templates/infra/modules/cloudflare/index.ts +9 -0
  42. package/templates/infra/modules/cloudflare-zone/index.ts +83 -9
  43. package/templates/infra/modules/d1/index.ts +30 -4
  44. package/templates/infra/modules/d1/registry.json +1 -1
@@ -20,7 +20,6 @@
20
20
  * be connected and permanently deaf.
21
21
  */
22
22
 
23
- import { Container, getContainer } from '@cloudflare/containers'
24
23
  import { DurableObject } from 'cloudflare:workers'
25
24
 
26
25
  import { capabilitiesFrom } from '../shared/capabilities'
@@ -38,9 +37,10 @@ import {
38
37
  import { Outbox } from '../shared/outbox'
39
38
  import { INTERNAL_HEADER, READ_VERDICT_PATH, REFS_PATH } from '../shared/protocol'
40
39
  import { RefCache } from '../shared/ref-cache'
40
+ import { type ContainerBindings, containerFor } from './container-binding'
41
41
 
42
42
  /** Only the bindings this object touches — the Worker's Env is a superset. */
43
- export interface EventsEnv {
43
+ export interface EventsEnv extends ContainerBindings {
44
44
  /**
45
45
  * The announce secret, presented to the container when this object asks
46
46
  * whether a subscriber may read what it watches (docs/adr/0013).
@@ -55,12 +55,6 @@ export interface EventsEnv {
55
55
  WALGIT_PRIVATE_REPOS?: string
56
56
  WALGIT_SIGNER_LISTS?: string
57
57
  WALGIT_PUSH_CERT_SEED?: string
58
- // The BASE class, not `WalgitContainer`: that one is defined in index.ts,
59
- // which imports this file, so naming it here would be a cycle. `any` was the
60
- // first way around that and cost a typecheck — `DurableObjectStub<any>` sends
61
- // the RPC type machinery infinitely deep (TS2589). The base is enough: all
62
- // this object ever does with the binding is `fetch`.
63
- WALGIT_CONTAINER: DurableObjectNamespace<Container>
64
58
  }
65
59
 
66
60
  /** The Worker's internal call to fan an announcement out. Never client-reachable. */
@@ -307,8 +301,14 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
307
301
  },
308
302
  body: JSON.stringify({ credential, repos }),
309
303
  })
310
- const response = await getContainer(this.env.WALGIT_CONTAINER).fetch(request)
311
- if (!response.ok) throw new Error(`read verdict: ${response.status}`)
304
+ const response = await containerFor(this.env).fetch(request)
305
+ if (!response.ok) {
306
+ // Cancelled, not dropped: the container's object counts a request in
307
+ // flight until its body is over, and an unread body may never be — which
308
+ // would hold the idle stop off (worker/durable-container.ts).
309
+ await response.body?.cancel()
310
+ throw new Error(`read verdict: ${response.status}`)
311
+ }
312
312
  const body = (await response.json()) as { verdicts?: Record<string, boolean> }
313
313
  if (!body.verdicts) throw new Error('read verdict: no verdicts in the answer')
314
314
  return body.verdicts
@@ -382,8 +382,12 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
382
382
  `https://walgit.internal${REFS_PATH}?repo=${encodeURIComponent(repo)}`,
383
383
  { headers: { [INTERNAL_HEADER]: '1' } },
384
384
  )
385
- const response = await getContainer(this.env.WALGIT_CONTAINER).fetch(request)
386
- if (!response.ok) throw new Error(`refs lookup for ${repo}: ${response.status}`)
385
+ const response = await containerFor(this.env).fetch(request)
386
+ if (!response.ok) {
387
+ // Cancelled for the reason `readVerdicts` cancels its own.
388
+ await response.body?.cancel()
389
+ throw new Error(`refs lookup for ${repo}: ${response.status}`)
390
+ }
387
391
  const body = (await response.json()) as { refs?: Record<string, string> }
388
392
  return body.refs ?? {}
389
393
  }
@@ -20,13 +20,16 @@
20
20
  * here instead — off the serving path, and only for what the log cannot answer
21
21
  * (shared/telemetry.ts).
22
22
  *
23
- * Reads are proxied like everything else. Serving a fetch straight from R2 at
24
- * the edge, without waking the container, is a real optimisation and
25
- * deliberately not in this milestone.
23
+ * Reads are proxied like everything else, with one exception: a protocol-v2
24
+ * ref check — `info/refs` and the `ls-refs` after it — is answered here off the
25
+ * Index (shared/edge-refs.ts), because polling agents send little else and each
26
+ * poll kept the container awake. Serving a fetch straight from R2 at the edge,
27
+ * without waking the container, is a real optimisation and deliberately not in
28
+ * this milestone.
26
29
  */
27
30
 
28
31
  import { AwsClient } from 'aws4fetch'
29
- import { Container, getContainer } from '@cloudflare/containers'
32
+ import { Container } from '@cloudflare/containers'
30
33
 
31
34
  import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
32
35
  import { containerEnv, fingerprintEnv, reconcileContainerEnv } from '../shared/container-env'
@@ -34,6 +37,9 @@ import { parseTokens } from '../shared/credentials'
34
37
  import { authorizeAnnounce, authorizeSubscribe } from '../shared/events'
35
38
  import { renderLanding, wantsLanding } from '../shared/landing'
36
39
  import { renderLlms, wantsLlms } from '../shared/llms'
40
+ import { renderInstructions } from '../shared/instructions'
41
+ import { sleepAfterFrom } from '../shared/sleep-after'
42
+ import { indexKey } from '../shared/keys'
37
43
  import {
38
44
  FAVICON_BODY,
39
45
  FAVICON_CONTENT_TYPE,
@@ -54,6 +60,8 @@ import {
54
60
  COLD_HEADER,
55
61
  EVENTS_PATH,
56
62
  BROWSE_PATH,
63
+ COLLECT_CRON,
64
+ containerRoutes,
57
65
  EXPIRE_PATH,
58
66
  INTERNAL_HEADER,
59
67
  INTERNAL_HEADERS,
@@ -70,6 +78,9 @@ import {
70
78
  type RequestMetric,
71
79
  } from '../shared/telemetry'
72
80
  import { browseResponse } from '../shared/browse'
81
+ import { type ContainerBindings, containerFor } from './container-binding'
82
+ import { WalgitDurableContainer } from './durable-container'
83
+ import { refsAtEdge, uploadPackKeyFor } from '../shared/edge-refs'
73
84
  import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
74
85
  import { handleMcp } from './mcp'
75
86
  // The card's picture, as bytes in the bundle (wrangler.jsonc's `Data` rule).
@@ -77,8 +88,15 @@ import { handleMcp } from './mcp'
77
88
  // committed — never drawn per request.
78
89
  import OG_IMAGE_BYTES from '../assets/agentgit-og.png'
79
90
 
80
- export interface Env {
81
- WALGIT_CONTAINER: DurableObjectNamespace<WalgitContainer>
91
+ /**
92
+ * The container is reached through `containerFor` (worker/container-binding.ts)
93
+ * and never through a binding directly: two bindings exist while the deployment
94
+ * moves to the `durable_object` scheduling policy — `WALGIT_CONTAINER` for
95
+ * `WalgitContainer` below, `WALGIT_DURABLE_CONTAINER` for
96
+ * `WalgitDurableContainer` — and `WALGIT_CONTAINER_POLICY` says which one this
97
+ * deployment routes to.
98
+ */
99
+ export interface Env extends ContainerBindings {
82
100
  /**
83
101
  * The commit this Worker was deployed from, set by the cloudflare module's
84
102
  * `deployIdVar`. Nothing reads it: it exists so that a deploy which changes
@@ -114,6 +132,7 @@ export interface Env {
114
132
  */
115
133
  WALGIT_WEB?: string
116
134
  WALGIT_RETENTION_HOURS?: string
135
+ WALGIT_CLAIMED_RETENTION_HOURS?: string
117
136
  WALGIT_MAX_PUSH_BYTES?: string
118
137
  WALGIT_MAX_REPO_BYTES?: string
119
138
  /**
@@ -188,14 +207,34 @@ export interface Env {
188
207
  WALGIT_POSTHOG_KEY?: string
189
208
  WALGIT_POSTHOG_HOST?: string
190
209
  WALGIT_POSTHOG_UI_HOST?: string
210
+ /** How long the container idles before it stops (`shared/sleep-after.ts`). */
211
+ WALGIT_SLEEP_AFTER?: string
212
+ /**
213
+ * `1` to snapshot the container's disk on the idle stop and start the next
214
+ * one from it, so a wake re-syncs the Cache instead of rebuilding it
215
+ * (`shared/container-snapshot.ts`). Off unless set — the platform feature is
216
+ * in public beta — and edge-only: the Durable Object reads it and the
217
+ * container never does, so turning it either way restarts nothing.
218
+ */
219
+ WALGIT_SNAPSHOTS?: string
191
220
  WALGIT_EVENTS: DurableObjectNamespace<WalgitEvents>
192
221
  }
193
222
 
194
- export { WalgitEvents }
223
+ export { WalgitEvents, WalgitDurableContainer }
195
224
 
196
225
  /** Where `reconcileEnv` remembers the environment the container booted with. */
197
226
  const ENV_FINGERPRINT_KEY = 'container-env-fingerprint'
198
227
 
228
+ /**
229
+ * RETIRING. The `default`-policy container class. It serves until a deployment
230
+ * sets `WALGIT_CONTAINER_POLICY=durable_object` — the default routes here, so
231
+ * the deploy that introduces the new application changes nothing a client sees
232
+ * — and after that it is the rollback path: unsetting the variable routes back
233
+ * to it in one forward deploy. Kept exported until its application is deleted
234
+ * and its class retired (README.md, "Deployment", phase 3).
235
+ *
236
+ * Left exactly as it was: it is the known-good half of the move.
237
+ */
199
238
  export class WalgitContainer extends Container<Env> {
200
239
  /**
201
240
  * Was this instance's container only just started?
@@ -204,16 +243,22 @@ export class WalgitContainer extends Container<Env> {
204
243
  * test cannot show them in production, and only this side knows it: from the
205
244
  * Worker every request is a `fetch` that took as long as it took. So the
206
245
  * first response after a start is stamped, once, and the Worker reads it off.
246
+ *
247
+ * `false` until `onStart` says otherwise: a Durable Object reconstructed in
248
+ * front of a container that was already running has started nothing, and
249
+ * stamping its first response cold counted ~10 phantom cold starts a day.
207
250
  */
208
- private freshStart = true
251
+ private freshStart = false
209
252
 
210
253
  // src/server.ts's PORT default, and the Dockerfile's.
211
254
  defaultPort = 8080
212
255
 
213
256
  // A clone of a cold repository has to materialize it from the log first, and
214
257
  // a large push writes a pack before it is acknowledged. Neither is fast, and
215
- // both are the normal path here rather than an edge case.
216
- sleepAfter = '20m'
258
+ // both are the normal path here rather than an edge case. So the default is
259
+ // generous, and an instance whose traffic makes idle time the larger cost
260
+ // sets its own (`shared/sleep-after.ts`).
261
+ sleepAfter = sleepAfterFrom(this.env)
217
262
 
218
263
  // The container is a separate process on a separate machine: `wrangler secret
219
264
  // put` reaches this Worker and stops there. Forwarding is what gives the push
@@ -297,9 +342,24 @@ export class WalgitContainer extends Container<Env> {
297
342
  }
298
343
  await this.reconciled
299
344
 
345
+ let response = await super.fetch(request)
346
+ // A read that lands between the container's SIGTERM exit and the library
347
+ // noticing it is refused by the library itself (a 500 the container never
348
+ // stamped). Once more, after a beat, starts a fresh container instead. Only
349
+ // a bodiless read: a push's body has already been consumed.
350
+ if (
351
+ (request.method === 'GET' || request.method === 'HEAD') &&
352
+ response.status === 500 &&
353
+ !response.headers.has(SERVED_HEADER)
354
+ ) {
355
+ await scheduler.wait(500)
356
+ response = await super.fetch(request)
357
+ }
358
+ // Read AFTER the fetch: `onStart` runs inside `super.fetch`, so a flag read
359
+ // before it was still `false` for the request that woke the container and
360
+ // stamped the next one cold instead.
300
361
  const cold = this.freshStart
301
362
  this.freshStart = false
302
- const response = await super.fetch(request)
303
363
  if (!cold) return response
304
364
  // Rebuilt rather than mutated (Response headers are immutable), passing the
305
365
  // body by reference so a clone is not buffered to add one header.
@@ -407,6 +467,32 @@ export default {
407
467
  })
408
468
  }
409
469
 
470
+ // The plain-text `/` — the API surface an agent's default fetch reads
471
+ // (`shared/instructions.ts`). The browser's `/` is the landing branch
472
+ // above; this is everything else that asks for `/`. It used to be proxied,
473
+ // and agents fetch it often enough that it alone kept the container from
474
+ // sleeping. Rendered from the same capabilities the container would use,
475
+ // and above the credential gate there too, so the answer is the same one.
476
+ if (url.pathname === '/' && (request.method === 'GET' || request.method === 'HEAD')) {
477
+ const bytes = new TextEncoder().encode(renderInstructions(url.origin, caps))
478
+ record(env, ctx, {
479
+ kind: 'instructions',
480
+ repo: '',
481
+ outcome: 'ok',
482
+ reject: '',
483
+ status: 200,
484
+ served: false,
485
+ cold: false,
486
+ ttfbMs: Date.now() - startedAt,
487
+ totalMs: Date.now() - startedAt,
488
+ bytesServed: request.method === 'HEAD' ? 0 : bytes.byteLength,
489
+ bytesReceived: 0,
490
+ })
491
+ return new Response(request.method === 'HEAD' ? null : bytes, {
492
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
493
+ })
494
+ }
495
+
410
496
  // `/robots.txt`, beside the manual it points at and for the same reasons.
411
497
  // Until this branch existed the path was answered by Cloudflare's managed
412
498
  // Content Signals file, which says nothing either way — and a crawler that
@@ -619,7 +705,24 @@ export default {
619
705
  // container has already chosen the `content-type` from the CONTENT — plain
620
706
  // text with `nosniff`, or an octet-stream attachment — because it is the
621
707
  // half holding the bytes, and nothing here second-guesses that.
708
+ // A repository page for a name nobody has pushed to is a 404 the edge can
709
+ // read off the log, and most of these are not people: `/contact`,
710
+ // `/about` and `/impressum` are scanners trying a site that is not here.
711
+ // See `absentAtEdge` for when the edge is allowed to say so.
712
+ const absent = browseRoute ? await absentAtEdge(env, caps, browseRoute.repo) : false
713
+
622
714
  if (browseRoute && browseRoute.kind === 'raw') {
715
+ if (absent) {
716
+ record(env, ctx, {
717
+ kind: 'browse',
718
+ repo: browseRoute.repo,
719
+ ...EDGE_NOT_FOUND_METRIC,
720
+ bytesReceived: 0,
721
+ ttfbMs: Date.now() - startedAt,
722
+ totalMs: Date.now() - startedAt,
723
+ })
724
+ return edgeNotFound(request.method)
725
+ }
623
726
  const query =
624
727
  `?repo=${encodeURIComponent(browseRoute.repo)}&op=raw` +
625
728
  (browseRoute.rest === '' ? '' : `&ref=${encodeURIComponent(browseRoute.rest)}`)
@@ -628,7 +731,7 @@ export default {
628
731
  // route below: the edge must not open a door the client could not.
629
732
  headers: authorizationOf(request),
630
733
  })
631
- const res = await getContainer(env.WALGIT_CONTAINER).fetch(asked)
734
+ const res = await containerFor(env).fetch(asked)
632
735
  const outcome = outcomeOf({
633
736
  status: res.status,
634
737
  declared: res.headers.get(REJECT_HEADER) ?? '',
@@ -653,6 +756,10 @@ export default {
653
756
  // bookkeeping rather than protocol.
654
757
  const headers = new Headers(res.headers)
655
758
  for (const name of INTERNAL_HEADERS) headers.delete(name)
759
+ // A HEAD sends no body, but the container was asked a GET and is sending
760
+ // one: cancelled, so the request it belongs to ends here rather than
761
+ // staying in flight in the container's object (worker/durable-container.ts).
762
+ if (request.method === 'HEAD') await res.body?.cancel()
656
763
  return new Response(request.method === 'HEAD' ? null : res.body, {
657
764
  status: res.status,
658
765
  statusText: res.statusText,
@@ -667,6 +774,18 @@ export default {
667
774
  {
668
775
  caps,
669
776
  ask: async (query) => {
777
+ // The container's own 404, word for word, so `browseResponse`
778
+ // renders the page it always rendered for a missing name.
779
+ if (absent) {
780
+ return {
781
+ status: 404,
782
+ text: NOT_FOUND_BODY,
783
+ contentType: 'text/plain;charset=UTF-8',
784
+ served: false,
785
+ reject: 'not-found',
786
+ challenges: [],
787
+ }
788
+ }
670
789
  const asked = new Request(`https://walgit.internal${BROWSE_PATH}${query}`, {
671
790
  // The client's own credential, and nothing else: the container
672
791
  // answers this behind the deployment token and then the Read
@@ -674,7 +793,7 @@ export default {
674
793
  // client could not.
675
794
  headers: authorizationOf(request),
676
795
  })
677
- const res = await getContainer(env.WALGIT_CONTAINER).fetch(asked)
796
+ const res = await containerFor(env).fetch(asked)
678
797
  return {
679
798
  status: res.status,
680
799
  text: await res.text(),
@@ -789,13 +908,64 @@ export default {
789
908
 
790
909
  const facts = classifyRequest(request.method, url.pathname, url.search)
791
910
 
911
+ // A path the container does not route is a 404 there, so on a public
912
+ // deployment it is a 404 here, without the wake (`containerRoutes`). Not
913
+ // on a token-gated one: its container answers an unauthenticated stranger
914
+ // 401 before it looks at the path, and a 404 from here would tell that
915
+ // stranger which paths are not repositories.
916
+ if (caps.publicAccess && facts.kind === 'other' && !containerRoutes(url.pathname)) {
917
+ record(env, ctx, {
918
+ ...base(facts, request),
919
+ ...EDGE_NOT_FOUND_METRIC,
920
+ ttfbMs: Date.now() - startedAt,
921
+ totalMs: Date.now() - startedAt,
922
+ })
923
+ return edgeNotFound(request.method)
924
+ }
925
+
926
+ // A protocol-v2 ref check — the advertisement, or the `ls-refs` after it —
927
+ // answered off the Index without waking the container (`shared/edge-refs.ts`).
928
+ // It is nearly all of a public deployment's git traffic: agents polling one
929
+ // ref, each poll keeping the container awake for another `sleepAfter`.
930
+ //
931
+ // Only on a public deployment, for the reason the 404 above is: a
932
+ // token-gated container answers a stranger 401 before it reads the path,
933
+ // and nothing here may get ahead of that. Everything `refsAtEdge` is not
934
+ // sure of comes back as a request to forward — the original, or, when the
935
+ // body had to be read to be sure, a rebuilt one carrying the same bytes.
936
+ let forwardable = request
937
+ if (caps.publicAccess && (facts.kind === 'clone-advertise' || facts.kind === 'clone')) {
938
+ const edge = await refsAtEdge(request, {
939
+ publicAccess: caps.publicAccess,
940
+ store: edgeStore(env),
941
+ recordKey: uploadPackKeyFor(env),
942
+ })
943
+ if (edge.response) {
944
+ record(env, ctx, {
945
+ ...base(facts, request),
946
+ outcome: 'ok',
947
+ reject: '',
948
+ status: edge.response.status,
949
+ // Not the container, which is the property this branch exists to
950
+ // create — the same claim the landing page and the list make.
951
+ served: false,
952
+ cold: false,
953
+ ttfbMs: Date.now() - startedAt,
954
+ totalMs: Date.now() - startedAt,
955
+ bytesServed: edge.bytes,
956
+ })
957
+ return edge.response
958
+ }
959
+ forwardable = edge.request
960
+ }
961
+
792
962
  // The container's expiry endpoint trusts INTERNAL_HEADER to mean "the
793
963
  // scheduled handler asked". That is only true because this line makes it
794
964
  // true: every request arriving from the internet has the header removed
795
965
  // before it is proxied, whatever the client set it to. Done for ALL paths,
796
966
  // not just the one, so a future internal endpoint inherits the guarantee
797
967
  // instead of having to remember it.
798
- const forwarded = stripInternal(request)
968
+ const forwarded = stripInternal(forwardable)
799
969
 
800
970
  let response: Response
801
971
  try {
@@ -804,7 +974,7 @@ export default {
804
974
  // and `sync.ts` reconciles on every access, so any container could take any
805
975
  // push — it is cache locality: a second instance starts with an empty disk
806
976
  // and materializes everything it is asked for from the log.
807
- response = await getContainer(env.WALGIT_CONTAINER).fetch(forwarded)
977
+ response = await containerFor(env).fetch(forwarded)
808
978
  } catch (error) {
809
979
  // The container never answered, so nothing downstream can name this
810
980
  // refusal — it is an `edge` one by construction, and counting it as such
@@ -972,12 +1142,13 @@ async function events(request: Request, url: URL, env: Env, caps: Capabilities):
972
1142
  }
973
1143
 
974
1144
  async function sweep(event: ScheduledController, env: Env): Promise<void> {
975
- const request = new Request(`https://walgit.internal${EXPIRE_PATH}`, {
1145
+ const mode = event.cron === COLLECT_CRON ? '?collect=only' : ''
1146
+ const request = new Request(`https://walgit.internal${EXPIRE_PATH}${mode}`, {
976
1147
  method: 'POST',
977
1148
  headers: { [INTERNAL_HEADER]: '1' },
978
1149
  })
979
1150
  try {
980
- const response = await getContainer(env.WALGIT_CONTAINER).fetch(request)
1151
+ const response = await containerFor(env).fetch(request)
981
1152
  const body = (await response.text()).trim()
982
1153
  console.log(`walgit expire [cron ${event.cron}]: ${response.status} ${body}`)
983
1154
  } catch (error) {
@@ -996,6 +1167,53 @@ async function sweep(event: ScheduledController, env: Env): Promise<void> {
996
1167
  * same the container makes; what is here is only the dependency it takes, since
997
1168
  * the signer belongs to whichever half has `aws4fetch` to hand.
998
1169
  */
1170
+ /** The container's `NOT_FOUND` body (`src/http.ts`), which the edge repeats. */
1171
+ const NOT_FOUND_BODY = 'not found\n'
1172
+
1173
+ function edgeNotFound(method: string): Response {
1174
+ return new Response(method === 'HEAD' ? null : NOT_FOUND_BODY, {
1175
+ status: 404,
1176
+ headers: { 'content-type': 'text/plain;charset=UTF-8' },
1177
+ })
1178
+ }
1179
+
1180
+ /**
1181
+ * How a 404 the edge answered itself is counted: `not-found`, as the
1182
+ * container would have named it, and `served: false`, because it did not.
1183
+ */
1184
+ const EDGE_NOT_FOUND_METRIC = {
1185
+ outcome: 'reject',
1186
+ reject: 'not-found',
1187
+ status: 404,
1188
+ served: false,
1189
+ cold: false,
1190
+ bytesServed: 0,
1191
+ } as const
1192
+
1193
+ /**
1194
+ * Does the log say this name has never been pushed to?
1195
+ *
1196
+ * The container's browse answers a name with no Index 404 once the Private
1197
+ * gate has passed, and the gate cannot refuse a name with no Index: the Claim
1198
+ * lives IN the Index (`src/server.ts`'s `readClaim`), so there is nothing for
1199
+ * it to read. So on a public deployment, an absent `index.json` is the
1200
+ * container's answer known in advance. Any doubt is `false` and the request
1201
+ * goes to the container as before: no store, a name the container would
1202
+ * normalize differently, or a read that failed.
1203
+ */
1204
+ async function absentAtEdge(env: Env, caps: Capabilities, repo: string): Promise<boolean> {
1205
+ if (!caps.publicAccess) return false
1206
+ // `normalizeRepoId` strips a `.git` suffix, so `/alpha.git` browses `alpha`.
1207
+ if (repo.endsWith('.git')) return false
1208
+ const store = edgeStore(env)
1209
+ if (!store) return false
1210
+ try {
1211
+ return (await store.get(indexKey(repo))) === null
1212
+ } catch {
1213
+ return false
1214
+ }
1215
+ }
1216
+
999
1217
  function edgeStore(env: Env): ObjectStore | null {
1000
1218
  return s3StoreFrom(env, (credentials) => new AwsClient(credentials))
1001
1219
  }
@@ -36,7 +36,6 @@
36
36
  */
37
37
 
38
38
  import { StreamableHTTPTransport } from '@hono/mcp'
39
- import { getContainer } from '@cloudflare/containers'
40
39
  import { Hono } from 'hono'
41
40
 
42
41
  import type { Capabilities } from '../shared/capabilities'
@@ -58,6 +57,7 @@ import {
58
57
  PROVENANCE_PATH,
59
58
  REFS_PATH,
60
59
  } from '../shared/protocol'
60
+ import { containerFor } from './container-binding'
61
61
  import { EVENTS_OBJECT_NAME } from './events-do'
62
62
  import type { Env } from './index'
63
63
 
@@ -156,7 +156,7 @@ async function provenanceRead(
156
156
  ): Promise<Read<{ provenance: ProvenanceFacts; claim?: Claim }>> {
157
157
  const headers = new Headers()
158
158
  if (authorization) headers.set('authorization', authorization)
159
- const response = await getContainer(env.WALGIT_CONTAINER).fetch(
159
+ const response = await containerFor(env).fetch(
160
160
  new Request(`https://walgit.internal${PROVENANCE_PATH}?repo=${encodeURIComponent(name)}`, {
161
161
  headers,
162
162
  }),
@@ -175,7 +175,7 @@ async function provenanceRead(
175
175
 
176
176
  /** One repository's ref state, read from the Index through the container. */
177
177
  async function readRefs(env: Env, name: string): Promise<Record<string, string>> {
178
- const response = await getContainer(env.WALGIT_CONTAINER).fetch(
178
+ const response = await containerFor(env).fetch(
179
179
  new Request(`https://walgit.internal${REFS_PATH}?repo=${encodeURIComponent(name)}`, {
180
180
  headers: { [INTERNAL_HEADER]: '1' },
181
181
  }),
@@ -183,7 +183,12 @@ async function readRefs(env: Env, name: string): Promise<Record<string, string>>
183
183
  // Empty rather than thrown: the gate above already said this name may be
184
184
  // read, and a refs lookup that did not answer is a repository with nothing
185
185
  // known about it — which is what `exists: false` says.
186
- if (!response.ok) return {}
186
+ if (!response.ok) {
187
+ // Cancelled rather than dropped: an unread body is a request the
188
+ // container's object keeps counting in flight (worker/durable-container.ts).
189
+ await response.body?.cancel()
190
+ return {}
191
+ }
187
192
  const body = (await response.json()) as { refs?: Record<string, string> }
188
193
  return body.refs ?? {}
189
194
  }
@@ -25,41 +25,37 @@
25
25
  // replaces the built-in.
26
26
  "rules": [{ "type": "Data", "globs": ["**/*.png"], "fallthrough": true }],
27
27
  "containers": [
28
+ // The container walgit runs in: the `durable_object` scheduling policy,
29
+ // driven by `WalgitDurableContainer` (worker/durable-container.ts) through
30
+ // `ctx.container`. Under this policy wrangler configures almost nothing —
31
+ // which image may be started, and that is all. The instance size is chosen
32
+ // in code at each start (`CONTAINER_INSTANCE`, shared/container-lifecycle.ts,
33
+ // which says why it is `standard-1`); there is no `max_instances`, because
34
+ // the policy has none and one named object already means one container; and
35
+ // there are no rollouts, because the Durable Object decides when a running
36
+ // container is replaced (it fingerprints the image it booted from). What the
37
+ // policy adds is a start in well under a second and filesystem snapshots,
38
+ // which `WALGIT_SNAPSHOTS` turns on.
39
+ //
40
+ // No `name`: wrangler derives `<worker>-<class>`, which differs from the
41
+ // retired `default`-policy entry's because the class does — and an explicit
42
+ // name would be shared by every deployment of this file in an account.
28
43
  {
29
- "class_name": "WalgitContainer",
30
- "image": "./Dockerfile",
31
- // 1 GiB, and the tier above it was paying for a copy nobody needed.
32
- //
33
- // The old sizing said "git is not memory-hungry until it packs, and
34
- // `git repack -adf` on a 250 MiB repository is the sizing case". Measured,
35
- // that is not what happens. Repacking a 250 MiB repository — the
36
- // `WALGIT_MAX_REPO_BYTES` cap — peaks at 82 MiB RSS. git is never the
37
- // sizing case. What follows the repack is: `compact.ts` reads the produced
38
- // pack into memory to hash and upload it, and peak RSS for the whole
39
- // operation is ~583 MiB.
40
- //
41
- // Half of that is avoidable and is being removed separately: a Node
42
- // `Buffer` already IS a `Uint8Array`, so `new Uint8Array(readFileSync(…))`
43
- // allocates a second full copy of every pack (+502 MiB for a 250 MiB file,
44
- // against +251 MiB without the wrapper, same digest). Once that lands the
45
- // peak is ~330 MiB and this tier is roomy rather than merely adequate.
46
- //
47
- // Headroom to keep in mind when raising `WALGIT_MAX_REPO_BYTES` or
48
- // `WALGIT_MAX_PUSH_BYTES`: one container serves concurrent requests and
49
- // each in-flight push buffers its own pack, so two simultaneous 99 MiB
50
- // pushes cost ~400 MiB today and ~200 MiB after the copy goes. Nothing
51
- // bounds how many land at once, which is the real limit on sizing down
52
- // again.
53
- "instance_type": "basic",
54
- // One instance, deliberately — see worker/index.ts. The disk is a cache,
55
- // so a second instance is correct but starts cold and materializes
56
- // everything it serves.
57
- "max_instances": 1
44
+ "class_name": "WalgitDurableContainer",
45
+ "scheduling_policy": "durable_object",
46
+ // Read as `ctx.container.images.walgit`: a digest-pinned reference that
47
+ // changes exactly when this image does.
48
+ "images": { "walgit": { "dockerfile": "./Dockerfile" } }
58
49
  }
59
50
  ],
60
51
  "durable_objects": {
61
52
  "bindings": [
62
- { "class_name": "WalgitContainer", "name": "WALGIT_CONTAINER" },
53
+ // The container's object. `WalgitContainer`, the `default`-policy class
54
+ // this replaced, keeps its export and its `v1` migration (its namespace
55
+ // exists) but is bound to nothing: a deployment still on it moves in
56
+ // the three phases README.md, "Deployment", describes, with the release
57
+ // that carried both bindings.
58
+ { "class_name": "WalgitDurableContainer", "name": "WALGIT_DURABLE_CONTAINER" },
63
59
  // The ref-event stream's rendezvous: one object holding every subscriber's
64
60
  // socket, so a push published in one colo reaches a client connected to
65
61
  // another (worker/events-do.ts). Bound unconditionally — the endpoints
@@ -81,10 +77,19 @@
81
77
  // between 24 and 48 hours after the last push. Over-retaining is the safe
82
78
  // direction; nothing is collected EARLY.
83
79
  //
80
+ // Two expressions, not one, because collection is two steps: the 04:00 sweep
81
+ // only TOMBSTONES an expired repository (a clone already in flight must be
82
+ // allowed to finish, `src/delete-repo.ts`), and with one daily sweep the
83
+ // removal then waited a whole day for the next one — 48 to 72 hours, not the
84
+ // 24 to 48 above. The 05:15 sweep collects only, a grace period after the
85
+ // first, so removal lands 75 minutes after the tombstone. Both expressions are `SWEEP_CRON` and `COLLECT_CRON` in
86
+ // `shared/protocol.ts`, which is how the Worker tells them apart; edit them
87
+ // together. The second costs one more container wake a day.
88
+ //
84
89
  // It was hourly, and the reason it is not is the half of the cost the old
85
90
  // comment named without weighing: "a sweep with nothing to collect is one
86
91
  // delimited LIST plus a container wake". A wake is not free the way a LIST
87
- // is. `WalgitContainer.sleepAfter` is 20m, so an hourly sweep holds the
92
+ // is. `WALGIT_SLEEP_AFTER` is 20m unless set, so an hourly sweep holds the
88
93
  // container up for at least a third of every hour on a deployment with no
89
94
  // traffic at all, and the sweeper is the only thing asking. Daily makes the
90
95
  // floor a twenty-fourth of that.
@@ -94,10 +99,16 @@
94
99
  // then exposes no sweep endpoint at all, so the cron logs a 404 and collects
95
100
  // nothing. Unlike a route, a Cron Trigger is per-Worker rather than per-zone,
96
101
  // so it cannot be stolen by another deployment of this same config.
97
- "triggers": { "crons": ["0 4 * * *"] },
102
+ "triggers": { "crons": ["0 4 * * *", "15 5 * * *"] },
98
103
  "migrations": [
99
104
  { "tag": "v1", "new_sqlite_classes": ["WalgitContainer"] },
100
- { "tag": "v2", "new_sqlite_classes": ["WalgitEvents"] }
105
+ { "tag": "v2", "new_sqlite_classes": ["WalgitEvents"] },
106
+ // A new namespace rather than a renamed one: the old namespace is attached
107
+ // to the `default`-policy application, and a namespace attaches to one.
108
+ // Never removed to roll back: `wrangler rollback` refuses to cross a
109
+ // Durable Object class change, so rolling back is a forward deploy that
110
+ // unsets `WALGIT_CONTAINER_POLICY`, with this migration and the class kept.
111
+ { "tag": "v3", "new_sqlite_classes": ["WalgitDurableContainer"] }
101
112
  ]
102
113
  // No r2_buckets binding. The container writes the log itself, outside the
103
114
  // Worker's binding graph, so it needs real S3 credentials (WALGIT_S3_*) —
@@ -7,5 +7,13 @@
7
7
  "Bash(gh:*)",
8
8
  "Bash(zbc:*)"
9
9
  ]
10
+ },
11
+ "extraKnownMarketplaces": {
12
+ "zbc": {
13
+ "source": { "source": "github", "repo": "Zabaca/zbc" }
14
+ }
15
+ },
16
+ "enabledPlugins": {
17
+ "zbc@zbc": true
10
18
  }
11
19
  }
@@ -570,6 +570,15 @@ export const cloudflareModule = defineModule({
570
570
  * So it is necessary and not sufficient. Replacing a running instance is
571
571
  * the payload's own job, and `deployIdVar` above is what lets it know it
572
572
  * has one to do.
573
+ *
574
+ * `default` SCHEDULING POLICY ONLY. A container application under the
575
+ * `durable_object` policy has no rollouts at all — its Durable Object
576
+ * picks an image from `ctx.container.images` each time it starts one —
577
+ * and wrangler (4.147) accepts the flag on such a Worker and applies it to
578
+ * the `default`-policy applications alone, skipping the others without a
579
+ * word. So it is harmless to leave set across a migration between the two
580
+ * (walgit carries one of each while its old application is retired), and
581
+ * meaningless once a Worker has only `durable_object` containers.
573
582
  */
574
583
  immediateContainerRollout: z.boolean().default(false),
575
584
  /**