@zabaca/zbc 0.11.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 (74) 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/cloudflare-access/index.ts +85 -14
  68. package/templates/infra/modules/fly/index.ts +150 -10
  69. package/templates/infra/modules/turso/index.ts +43 -3
  70. package/templates/infra/package.json +1 -1
  71. package/templates/apps/walgit/entrypoint.sh +0 -59
  72. package/templates/apps/walgit/fly.toml +0 -52
  73. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  74. package/templates/apps/walgit/sshd_config +0 -38
@@ -0,0 +1,572 @@
1
+ /**
2
+ * The Worker half of walgit: a thin proxy in front of the Container.
3
+ *
4
+ * Thin is the whole design. Every decision about a request — which repository
5
+ * it names, whether the credential is good, whether the cache is current
6
+ * against the log — already lives in `src/http.ts` and is unit-tested there
7
+ * without a socket. Re-deciding any of it here would be a second copy of the
8
+ * gate, and the two would drift.
9
+ *
10
+ * What this file DOES own is the environment the container boots with: the
11
+ * container runs outside the Worker's binding graph, so the object store's
12
+ * credentials can only reach it as environment variables, forwarded here from
13
+ * the Worker's own secrets (shared/container-env.ts) — and, because a container
14
+ * reads them exactly once at start, it owns replacing the container when a
15
+ * deploy changes them (`reconcileEnv`).
16
+ *
17
+ * It also owns the one thing only this side can see: request-level telemetry.
18
+ * The log is already a usage ledger for pushes and storage, but a clone writes
19
+ * nothing to it, so read volume, latency, cold starts and refusals are counted
20
+ * here instead — off the serving path, and only for what the log cannot answer
21
+ * (shared/telemetry.ts).
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.
26
+ */
27
+
28
+ import { Container, getContainer } from '@cloudflare/containers'
29
+
30
+ import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
31
+ import { containerEnv, fingerprintEnv } from '../shared/container-env'
32
+ import { parseTokens } from '../shared/credentials'
33
+ import { authorizeAnnounce, authorizeSubscribe } from '../shared/events'
34
+ import { renderLanding, wantsLanding } from '../shared/landing'
35
+ import { renderLlms, wantsLlms } from '../shared/llms'
36
+ import {
37
+ ANNOUNCE_PATH,
38
+ COLD_HEADER,
39
+ EVENTS_PATH,
40
+ EXPIRE_PATH,
41
+ INTERNAL_HEADER,
42
+ INTERNAL_HEADERS,
43
+ SERVED_HEADER,
44
+ } from '../shared/protocol'
45
+ import {
46
+ classifyOutcome,
47
+ classifyRequest,
48
+ toDataPoint,
49
+ type RequestMetric,
50
+ } from '../shared/telemetry'
51
+ import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
52
+
53
+ export interface Env {
54
+ WALGIT_CONTAINER: DurableObjectNamespace<WalgitContainer>
55
+ /** Comma-separated bearer tokens; git sends one as the Basic-auth password. */
56
+ WALGIT_HTTP_TOKENS?: string
57
+ /** The write-ahead log's home — see src/store-env.ts. */
58
+ WALGIT_S3_ENDPOINT?: string
59
+ WALGIT_S3_BUCKET?: string
60
+ WALGIT_S3_ACCESS_KEY_ID?: string
61
+ WALGIT_S3_SECRET_ACCESS_KEY?: string
62
+ WALGIT_S3_REGION?: string
63
+ /** Optional knobs, not secrets (see the app README). */
64
+ WALGIT_COMPACTION_THRESHOLD?: string
65
+ WALGIT_GC_GRACE_MS?: string
66
+ WALGIT_DELETE_GRACE_MS?: string
67
+ /**
68
+ * The policy the documents state and the push path enforces. Read ONLY
69
+ * through `capabilitiesFrom` (`shared/capabilities.ts`) — a second read here
70
+ * is how the three spellings of `WALGIT_PUBLIC` drifted apart.
71
+ */
72
+ WALGIT_PUBLIC?: string
73
+ WALGIT_APPEND_ONLY?: string
74
+ WALGIT_RETENTION_HOURS?: string
75
+ WALGIT_MAX_PUSH_BYTES?: string
76
+ WALGIT_MAX_REPO_BYTES?: string
77
+ /**
78
+ * Where request-level telemetry goes — the half of observability the log
79
+ * cannot produce (shared/telemetry.ts). Optional: a deployment without the
80
+ * binding simply records nothing, and serves exactly as before.
81
+ */
82
+ WALGIT_METRICS?: AnalyticsEngineDataset
83
+ /**
84
+ * The ref-event stream (shared/events.ts). Off unless BOTH are set: the
85
+ * token is the shared secret the container's push path presents when it
86
+ * announces, and the URL is where it announces TO. With only the token the
87
+ * socket is claimed, the handshake answers with current refs, and no event
88
+ * ever arrives, because `post-receive` has nowhere to send one — so the
89
+ * endpoints do not exist unless both halves are configured
90
+ * (`shared/capabilities.ts`). The container gets both through the forward
91
+ * list.
92
+ */
93
+ WALGIT_EVENTS_TOKEN?: string
94
+ WALGIT_EVENTS_URL?: string
95
+ /**
96
+ * The nonce seed that makes signed pushes possible (src/push-cert.ts). Unset
97
+ * is the default and means the container never advertises the capability, so
98
+ * a client asking for `--signed=yes` is refused by its own git. A secret:
99
+ * the nonce it derives is what makes a push certificate un-replayable.
100
+ */
101
+ WALGIT_PUSH_CERT_SEED?: string
102
+ /**
103
+ * `1` to give repositories Signer Lists (src/signers.ts, docs/adr/0012).
104
+ * Its own variable rather than a consequence of the seed above: signing is
105
+ * refused client-side where it is not offered, while ownership is a
106
+ * server-side refusal that would otherwise arrive on a deployment that
107
+ * already set a seed, unasked.
108
+ */
109
+ WALGIT_SIGNER_LISTS?: string
110
+ WALGIT_EVENTS: DurableObjectNamespace<WalgitEvents>
111
+ }
112
+
113
+ export { WalgitEvents }
114
+
115
+ /** Where `reconcileEnv` remembers the environment the container booted with. */
116
+ const ENV_FINGERPRINT_KEY = 'container-env-fingerprint'
117
+
118
+ export class WalgitContainer extends Container<Env> {
119
+ /**
120
+ * Was this instance's container only just started?
121
+ *
122
+ * Cold start is the latency an operator most needs to see and the one a spike
123
+ * test cannot show them in production, and only this side knows it: from the
124
+ * Worker every request is a `fetch` that took as long as it took. So the
125
+ * first response after a start is stamped, once, and the Worker reads it off.
126
+ */
127
+ private freshStart = true
128
+
129
+ // src/server.ts's PORT default, and the Dockerfile's.
130
+ defaultPort = 8080
131
+
132
+ // A clone of a cold repository has to materialize it from the log first, and
133
+ // a large push writes a pack before it is acknowledged. Neither is fast, and
134
+ // both are the normal path here rather than an edge case.
135
+ sleepAfter = '20m'
136
+
137
+ // The container is a separate process on a separate machine: `wrangler secret
138
+ // put` reaches this Worker and stops there. Forwarding is what gives the push
139
+ // path an object store at all — without it every push is REFUSED, correctly
140
+ // but confusingly, by hooks three processes down (src/store-env.ts).
141
+ //
142
+ // Read here rather than in `shared/container-env.ts` only because `this.env`
143
+ // is what the class has; the shape and the exclusion rules live there.
144
+ envVars = containerEnv(this.env)
145
+
146
+ /**
147
+ * Has the container been checked against the environment this Worker version
148
+ * would boot it with, since this Durable Object was constructed?
149
+ *
150
+ * One promise rather than a boolean so concurrent requests await the same
151
+ * check instead of each racing to replace the container.
152
+ */
153
+ private reconciled: Promise<void> | null = null
154
+
155
+ onStart(): void {
156
+ this.freshStart = true
157
+ }
158
+
159
+ /**
160
+ * Replace the container if it is running an environment this deploy changed.
161
+ *
162
+ * `envVars` above is re-read on every Durable Object construction, and a
163
+ * `wrangler deploy` constructs a new one — so this side is never stale. The
164
+ * container is: it read `process.env` once at start and cannot be told
165
+ * anything afterwards, and a vars-only deploy produces no new container image
166
+ * for `--containers-rollout immediate` to roll. Without this, the new value
167
+ * takes effect whenever the container next happens to idle out, which under
168
+ * sustained traffic is never.
169
+ *
170
+ * The fingerprint is persisted in Durable Object storage because that is the
171
+ * only state that survives the very event being detected — a redeploy
172
+ * discards every in-memory field, so an in-memory copy would compare the new
173
+ * environment against itself and always agree.
174
+ */
175
+ private async reconcileEnv(): Promise<void> {
176
+ const current = fingerprintEnv(this.envVars ?? {})
177
+ const booted = await this.ctx.storage.get<string>(ENV_FINGERPRINT_KEY)
178
+ if (booted === current) return
179
+
180
+ // Only a RUNNING container can be stale. A stopped one has nothing to
181
+ // replace: its next start reads `envVars` as it now is, which is already
182
+ // the new environment.
183
+ //
184
+ // No recorded fingerprint counts as a mismatch rather than as a fresh
185
+ // start, deliberately. A running container with no record predates this
186
+ // code, so what it booted with is unknowable — and on the deploy that
187
+ // ships this, that container is exactly the one already serving a
188
+ // superseded policy. Assuming it is current would leave the bug live
189
+ // until the next idle. A DO that has never started a container reaches
190
+ // here with `running` false and simply records.
191
+ if (this.ctx.container?.running) {
192
+ // SIGKILL rather than a graceful stop: the container serves git over
193
+ // HTTP and holds nothing worth draining — every durable effect of a push
194
+ // is in the log before it is acknowledged (docs/adr/0007) — and
195
+ // `sleepAfter` already covers the polite path. `destroy` triggers
196
+ // `onStop`; the next `containerFetch` starts a fresh one.
197
+ await this.destroy()
198
+ console.log(
199
+ `walgit container env changed (${booted ?? 'unrecorded'} -> ${current}); container replaced`,
200
+ )
201
+ }
202
+ // Written last, and only after a successful destroy: recording first would
203
+ // make a failed replacement look reconciled forever.
204
+ await this.ctx.storage.put(ENV_FINGERPRINT_KEY, current)
205
+ }
206
+
207
+ async fetch(request: Request): Promise<Response> {
208
+ // Before anything is proxied, so a request never reaches a container whose
209
+ // policy this deploy already superseded. Single-flight and memoized: the
210
+ // storage read happens once per Durable Object lifetime, not per request.
211
+ if (!this.reconciled) {
212
+ this.reconciled = this.reconcileEnv().catch((error) => {
213
+ // Cleared so the next request retries. Never rethrown: a container
214
+ // serving a stale limit is a worse day than an outage only if it is
215
+ // ALSO the reason git stopped working, and it should not be.
216
+ this.reconciled = null
217
+ console.error(`walgit container env reconcile failed: ${(error as Error).message}`)
218
+ })
219
+ }
220
+ await this.reconciled
221
+
222
+ const cold = this.freshStart
223
+ this.freshStart = false
224
+ const response = await super.fetch(request)
225
+ if (!cold) return response
226
+ // Rebuilt rather than mutated (Response headers are immutable), passing the
227
+ // body by reference so a clone is not buffered to add one header.
228
+ const stamped = new Response(response.body, response)
229
+ stamped.headers.set(COLD_HEADER, '1')
230
+ return stamped
231
+ }
232
+ }
233
+
234
+ export default {
235
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
236
+ const startedAt = Date.now()
237
+ const url = new URL(request.url)
238
+
239
+ // What this deployment offers, derived once for the whole request
240
+ // (`shared/capabilities.ts`). The two documents below state themselves
241
+ // from it and the event route is claimed from it, so the page, the manual
242
+ // and the socket cannot describe three different deployments — they used
243
+ // to read the environment three times, and only the size caps were shared.
244
+ const caps = capabilitiesFrom(env)
245
+
246
+ // The browser half of `/`, answered at the edge (shared/landing.ts). Placed
247
+ // before every other decision on purpose: a link on an aggregator points at
248
+ // this exact URL, and none of that traffic should wake the container, queue
249
+ // behind a clone, or count against the one instance serving git. git never
250
+ // asks for HTML, so a clone cannot land here.
251
+ const accept = request.headers.get('accept') ?? ''
252
+ if (wantsLanding(request.method, url.pathname, accept)) {
253
+ // The host is passed beside the capabilities rather than folded into
254
+ // them: this document and `/llms.txt` want a bare hostname they prefix
255
+ // with `https://`/`wss://` themselves, while `GET /` needs a full origin
256
+ // including the scheme, and one field could not serve both.
257
+ const page = renderLanding(url.host, caps)
258
+ const bytes = new TextEncoder().encode(page)
259
+ record(env, ctx, {
260
+ kind: 'landing',
261
+ repo: '',
262
+ outcome: 'ok',
263
+ reject: '',
264
+ status: 200,
265
+ // Neither is a lie by omission: the container was not involved at all,
266
+ // which is the property this branch exists to create and the one an
267
+ // operator should be able to see in the data.
268
+ served: false,
269
+ cold: false,
270
+ ttfbMs: Date.now() - startedAt,
271
+ totalMs: Date.now() - startedAt,
272
+ bytesServed: bytes.byteLength,
273
+ bytesReceived: 0,
274
+ })
275
+ return new Response(request.method === 'HEAD' ? null : bytes, {
276
+ status: 200,
277
+ headers: {
278
+ 'content-type': 'text/html; charset=utf-8',
279
+ // Short, and deliberately not longer: the page renders the limits
280
+ // this deployment enforces, so a stale copy at the edge would state a
281
+ // cap the push path no longer has. A minute absorbs a launch spike
282
+ // without outliving a config change by anything that matters.
283
+ 'cache-control': 'public, max-age=60',
284
+ },
285
+ })
286
+ }
287
+
288
+ // `/llms.txt`, answered at the edge for the same reasons the page is, and
289
+ // for one more: it is the LONG document, so serving it from the container
290
+ // would trade a cold start for text that changes only on deploy. It is
291
+ // rendered from the same environment the push path enforces, so the manual
292
+ // cannot promise a cap this deployment does not have.
293
+ //
294
+ // No collision with a repository: smart-HTTP paths are `/<name>.git/…`, so
295
+ // `/llms.txt` is not reachable as a repo route even for a repository called
296
+ // `llms.txt`.
297
+ if (wantsLlms(request.method, url.pathname)) {
298
+ const doc = renderLlms(url.host, caps)
299
+ const bytes = new TextEncoder().encode(doc)
300
+ record(env, ctx, {
301
+ kind: 'landing',
302
+ repo: '',
303
+ outcome: 'ok',
304
+ reject: '',
305
+ status: 200,
306
+ served: false,
307
+ cold: false,
308
+ ttfbMs: Date.now() - startedAt,
309
+ totalMs: Date.now() - startedAt,
310
+ bytesServed: bytes.byteLength,
311
+ bytesReceived: 0,
312
+ })
313
+ return new Response(request.method === 'HEAD' ? null : bytes, {
314
+ status: 200,
315
+ headers: {
316
+ 'content-type': 'text/markdown; charset=utf-8',
317
+ // Same minute as the page, and for the same reason: it states the
318
+ // limits this deployment enforces, so a stale copy would outlive a
319
+ // config change.
320
+ 'cache-control': 'public, max-age=60',
321
+ },
322
+ })
323
+ }
324
+
325
+ // The ref-event stream, answered at the edge for the same reason the
326
+ // landing page is: a subscription is a socket the container has no reason
327
+ // to hold, and holding one would keep the single container awake for as
328
+ // long as anybody is watching. When the feature is unconfigured neither
329
+ // path is claimed at all — the request falls through to the container,
330
+ // which does not route it, and the client gets the same 404 as for any
331
+ // other path that does not exist.
332
+ //
333
+ // Claimed from the same `caps.events` the two documents advertise from, so
334
+ // the route and the documents cannot disagree. That takes BOTH halves: with
335
+ // only the token this used to claim the socket, answer the handshake with
336
+ // current refs, and then deliver nothing forever, because the container's
337
+ // `post-receive` had no URL to announce to.
338
+ if ((url.pathname === EVENTS_PATH || url.pathname === ANNOUNCE_PATH) && caps.events) {
339
+ return events(request, url, env, caps)
340
+ }
341
+
342
+ const facts = classifyRequest(request.method, url.pathname, url.search)
343
+
344
+ // The container's expiry endpoint trusts INTERNAL_HEADER to mean "the
345
+ // scheduled handler asked". That is only true because this line makes it
346
+ // true: every request arriving from the internet has the header removed
347
+ // before it is proxied, whatever the client set it to. Done for ALL paths,
348
+ // not just the one, so a future internal endpoint inherits the guarantee
349
+ // instead of having to remember it.
350
+ const forwarded = stripInternal(request)
351
+
352
+ let response: Response
353
+ try {
354
+ // No id, so one singleton container serves every repository. That is not a
355
+ // scaling ceiling imposed by the design — `index.json` is compare-and-swap
356
+ // and `sync.ts` reconciles on every access, so any container could take any
357
+ // push — it is cache locality: a second instance starts with an empty disk
358
+ // and materializes everything it is asked for from the log.
359
+ response = await getContainer(env.WALGIT_CONTAINER).fetch(forwarded)
360
+ } catch (error) {
361
+ // The container never answered, so nothing downstream can name this
362
+ // refusal — it is an `edge` one by construction, and counting it as such
363
+ // is the point: walgit refusing things itself, with an explanation, is
364
+ // the product, so a refusal made in front of it is a bug signal.
365
+ record(env, ctx, {
366
+ ...base(facts, request),
367
+ outcome: 'reject',
368
+ reject: 'edge',
369
+ status: 0,
370
+ served: false,
371
+ cold: false,
372
+ ttfbMs: Date.now() - startedAt,
373
+ totalMs: Date.now() - startedAt,
374
+ bytesServed: 0,
375
+ })
376
+ throw error
377
+ }
378
+
379
+ const ttfbMs = Date.now() - startedAt
380
+ const { outcome, reject } = classifyOutcome(response.status, response.headers)
381
+ const metric: RequestMetric = {
382
+ ...base(facts, request),
383
+ outcome,
384
+ reject,
385
+ status: response.status,
386
+ served: response.headers.get(SERVED_HEADER) !== null,
387
+ cold: response.headers.get(COLD_HEADER) !== null,
388
+ ttfbMs,
389
+ totalMs: ttfbMs,
390
+ bytesServed: 0,
391
+ }
392
+
393
+ const headers = new Headers(response.headers)
394
+ for (const name of INTERNAL_HEADERS) headers.delete(name)
395
+
396
+ if (!response.body) {
397
+ record(env, ctx, metric)
398
+ return new Response(null, {
399
+ status: response.status,
400
+ statusText: response.statusText,
401
+ headers,
402
+ })
403
+ }
404
+
405
+ // Bytes served and total time are only known when the last byte is written,
406
+ // and a clone is a long stream. Counting them in a pass-through transform
407
+ // adds no copy and no buffering: the chunk is measured and forwarded, and
408
+ // the datapoint is written after the client already has its response.
409
+ const counted = response.body.pipeThrough(
410
+ new TransformStream<Uint8Array, Uint8Array>({
411
+ transform(chunk, controller) {
412
+ metric.bytesServed += chunk.byteLength
413
+ controller.enqueue(chunk)
414
+ },
415
+ flush() {
416
+ metric.totalMs = Date.now() - startedAt
417
+ record(env, ctx, metric)
418
+ },
419
+ cancel() {
420
+ // An abandoned clone still cost what it cost; recording it as if it
421
+ // completed would quietly under-count the bytes this service serves.
422
+ metric.totalMs = Date.now() - startedAt
423
+ record(env, ctx, metric)
424
+ },
425
+ }),
426
+ )
427
+ return new Response(counted, {
428
+ status: response.status,
429
+ statusText: response.statusText,
430
+ headers,
431
+ })
432
+ },
433
+
434
+ /**
435
+ * The expiry sweeper's timer (`wrangler.jsonc` → `triggers.crons`).
436
+ *
437
+ * It lives here rather than inside the container because the container SLEEPS
438
+ * when idle: an interval running in there would stop firing precisely when
439
+ * nothing is keeping it awake, which is exactly the state a repository has to
440
+ * be in to be collectable. The Cron Trigger wakes it instead, and the wake is
441
+ * the only cost — a sweep with nothing to collect is one delimited LIST.
442
+ *
443
+ * The report is logged rather than swallowed, because "the sweeper runs on a
444
+ * schedule and its output is visible" is the requirement, and a sweep that
445
+ * deletes repositories silently is the one failure mode nobody notices until
446
+ * the repositories are gone. A deployment with no `WALGIT_RETENTION_HOURS`
447
+ * has no sweep endpoint at all: the container answers 404, this logs it, and
448
+ * nothing is collected — which is correct for an instance that never promised
449
+ * a retention window.
450
+ */
451
+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
452
+ ctx.waitUntil(sweep(event, env))
453
+ },
454
+ }
455
+
456
+ /**
457
+ * The two ends of the ref-event stream: a subscriber connecting, and the push
458
+ * path publishing.
459
+ *
460
+ * Both are gated here rather than inside the Durable Object, because this is
461
+ * the layer that holds the environment — the read tokens and the announce
462
+ * secret — and the object should not carry a second copy of either. What it
463
+ * gets is a request that has already been allowed.
464
+ *
465
+ * The capabilities are PASSED IN rather than derived again, so the socket
466
+ * cannot reach a different verdict from the route that claimed it or from the
467
+ * documents that advertised it.
468
+ */
469
+ async function events(request: Request, url: URL, env: Env, caps: Capabilities): Promise<Response> {
470
+ const stub = env.WALGIT_EVENTS.get(env.WALGIT_EVENTS.idFromName(EVENTS_OBJECT_NAME))
471
+
472
+ if (url.pathname === ANNOUNCE_PATH) {
473
+ if (request.method !== 'POST') return new Response('method not allowed\n', { status: 405 })
474
+ if (!authorizeAnnounce(request.headers.get('authorization'), env.WALGIT_EVENTS_TOKEN ?? '')) {
475
+ return new Response('unauthorized\n', { status: 401 })
476
+ }
477
+ return stub.fetch(
478
+ new Request(`https://walgit.internal${BROADCAST_PATH}`, {
479
+ method: 'POST',
480
+ headers: { 'content-type': 'application/json' },
481
+ body: request.body,
482
+ }),
483
+ )
484
+ }
485
+
486
+ if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
487
+ return new Response('expected a websocket upgrade\n', { status: 426 })
488
+ }
489
+ // Exactly the credential a read of the repository needs — see
490
+ // `authorizeSubscribe`. The challenge header is sent for the same reason the
491
+ // container sends it: a client that can be prompted should be.
492
+ //
493
+ // `caps.publicAccess`, not `env.WALGIT_PUBLIC === '1'`. This line used to
494
+ // read the variable a third way: `flagEnabled` (`1` or `true`) fed
495
+ // `/llms.txt`'s access claim, `=== '1'` fed this socket and the container's
496
+ // git auth. On a deployment spelling it `true` the manual told an agent that
497
+ // reads need no credential while every subscribe answered 401 — the exact
498
+ // hazard `flagEnabled` was written for (`shared/policy.ts`).
499
+ const allowed = authorizeSubscribe({
500
+ authorization: request.headers.get('authorization'),
501
+ tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
502
+ isPublic: caps.publicAccess,
503
+ })
504
+ if (!allowed) {
505
+ return new Response('unauthorized\n', {
506
+ status: 401,
507
+ headers: { 'www-authenticate': 'Basic realm="walgit"' },
508
+ })
509
+ }
510
+ return stub.fetch(request)
511
+ }
512
+
513
+ async function sweep(event: ScheduledController, env: Env): Promise<void> {
514
+ const request = new Request(`https://walgit.internal${EXPIRE_PATH}`, {
515
+ method: 'POST',
516
+ headers: { [INTERNAL_HEADER]: '1' },
517
+ })
518
+ try {
519
+ const response = await getContainer(env.WALGIT_CONTAINER).fetch(request)
520
+ const body = (await response.text()).trim()
521
+ console.log(`walgit expire [cron ${event.cron}]: ${response.status} ${body}`)
522
+ } catch (error) {
523
+ // Logged, never thrown: a failed sweep is storage that stays a little
524
+ // longer, and over-retaining is the safe direction. Throwing would only
525
+ // turn it into an unhandled rejection nobody reads.
526
+ console.error(`walgit expire [cron ${event.cron}] failed: ${(error as Error).message}`)
527
+ }
528
+ }
529
+
530
+ /**
531
+ * The same request with any client-supplied INTERNAL_HEADER removed.
532
+ *
533
+ * Rebuilt rather than mutated — a Request's headers are immutable — with the
534
+ * body passed through by reference, so a 90 MiB push is not buffered to drop
535
+ * one header.
536
+ */
537
+ function stripInternal(request: Request): Request {
538
+ if (!request.headers.has(INTERNAL_HEADER)) return request
539
+ const headers = new Headers(request.headers)
540
+ headers.delete(INTERNAL_HEADER)
541
+ return new Request(request, { headers })
542
+ }
543
+
544
+ /** The facts known before the container answers. */
545
+ function base(
546
+ facts: { kind: RequestMetric['kind']; repo: string },
547
+ request: Request,
548
+ ): Pick<RequestMetric, 'kind' | 'repo' | 'bytesReceived'> {
549
+ const declared = Number(request.headers.get('content-length') ?? '0')
550
+ return {
551
+ kind: facts.kind,
552
+ repo: facts.repo,
553
+ bytesReceived: Number.isFinite(declared) ? declared : 0,
554
+ }
555
+ }
556
+
557
+ /**
558
+ * Write one datapoint, off the serving path.
559
+ *
560
+ * `waitUntil` is what keeps the promise in the acceptance criteria — the client
561
+ * is never waiting on a metric — and the try/catch is what keeps telemetry from
562
+ * ever being the reason a git request failed.
563
+ */
564
+ function record(env: Env, ctx: ExecutionContext, metric: RequestMetric): void {
565
+ if (!env.WALGIT_METRICS) return
566
+ try {
567
+ ctx.waitUntil(Promise.resolve(env.WALGIT_METRICS.writeDataPoint(toDataPoint(metric))))
568
+ } catch {
569
+ // Deliberately silent: a dropped datapoint is a gap in a chart, and
570
+ // anything louder would turn one into a failed clone.
571
+ }
572
+ }
@@ -0,0 +1,95 @@
1
+ {
2
+ "$schema": "node_modules/wrangler/config-schema.json",
3
+ // walgit as a Durable-Object-bound Cloudflare Container: one Bun process
4
+ // serving git smart-HTTP (worker/index.ts proxies straight to it), with the
5
+ // write-ahead log in R2 reached over the S3 API from inside the container.
6
+ // Container-backed: needs Docker running locally at apply time and a Workers
7
+ // Paid plan with Containers enabled.
8
+ //
9
+ // Generic defaults only — per-project identity (the worker name, the custom
10
+ // domain, the secrets) lives in the zbc instance file, so this file is
11
+ // identical across projects.
12
+ "name": "walgit",
13
+ "main": "worker/index.ts",
14
+ "compatibility_date": "2026-07-01",
15
+ "compatibility_flags": ["nodejs_compat"],
16
+ "observability": { "enabled": true },
17
+ "containers": [
18
+ {
19
+ "class_name": "WalgitContainer",
20
+ "image": "./Dockerfile",
21
+ // 1 GiB, and the tier above it was paying for a copy nobody needed.
22
+ //
23
+ // The old sizing said "git is not memory-hungry until it packs, and
24
+ // `git repack -adf` on a 250 MiB repository is the sizing case". Measured,
25
+ // that is not what happens. Repacking a 250 MiB repository — the
26
+ // `WALGIT_MAX_REPO_BYTES` cap — peaks at 82 MiB RSS. git is never the
27
+ // sizing case. What follows the repack is: `compact.ts` reads the produced
28
+ // pack into memory to hash and upload it, and peak RSS for the whole
29
+ // operation is ~583 MiB.
30
+ //
31
+ // Half of that is avoidable and is being removed separately: a Node
32
+ // `Buffer` already IS a `Uint8Array`, so `new Uint8Array(readFileSync(…))`
33
+ // allocates a second full copy of every pack (+502 MiB for a 250 MiB file,
34
+ // against +251 MiB without the wrapper, same digest). Once that lands the
35
+ // peak is ~330 MiB and this tier is roomy rather than merely adequate.
36
+ //
37
+ // Headroom to keep in mind when raising `WALGIT_MAX_REPO_BYTES` or
38
+ // `WALGIT_MAX_PUSH_BYTES`: one container serves concurrent requests and
39
+ // each in-flight push buffers its own pack, so two simultaneous 99 MiB
40
+ // pushes cost ~400 MiB today and ~200 MiB after the copy goes. Nothing
41
+ // bounds how many land at once, which is the real limit on sizing down
42
+ // again.
43
+ "instance_type": "basic",
44
+ // One instance, deliberately — see worker/index.ts. The disk is a cache,
45
+ // so a second instance is correct but starts cold and materializes
46
+ // everything it serves.
47
+ "max_instances": 1
48
+ }
49
+ ],
50
+ "durable_objects": {
51
+ "bindings": [
52
+ { "class_name": "WalgitContainer", "name": "WALGIT_CONTAINER" },
53
+ // The ref-event stream's rendezvous: one object holding every subscriber's
54
+ // socket, so a push published in one colo reaches a client connected to
55
+ // another (worker/events-do.ts). Bound unconditionally — the endpoints
56
+ // only exist when WALGIT_EVENTS_TOKEN and WALGIT_EVENTS_URL are BOTH set
57
+ // (shared/capabilities.ts), and an unused binding costs nothing.
58
+ { "class_name": "WalgitEvents", "name": "WALGIT_EVENTS" }
59
+ ]
60
+ },
61
+ // Request-level telemetry: clones, bytes served, latency, cold starts and
62
+ // refusals by kind — the half of observability the write-ahead log cannot
63
+ // produce (shared/telemetry.ts). Storage and push volume are NOT written
64
+ // here; `walgit usage` derives those from the log, and a second copy would
65
+ // disagree with it. Analytics Engine keeps the data inside the account.
66
+ "analytics_engine_datasets": [{ "binding": "WALGIT_METRICS", "dataset": "walgit_requests" }],
67
+ // The expiry sweeper's timer (worker/index.ts's `scheduled`). DAILY, and the
68
+ // cost it trades away is stated rather than left to be discovered: the window
69
+ // is `WALGIT_RETENTION_HOURS`, so a daily sweep lets a repository linger up
70
+ // to a further 24 hours past it — a 24-hour retention collects somewhere
71
+ // between 24 and 48 hours after the last push. Over-retaining is the safe
72
+ // direction; nothing is collected EARLY.
73
+ //
74
+ // It was hourly, and the reason it is not is the half of the cost the old
75
+ // comment named without weighing: "a sweep with nothing to collect is one
76
+ // delimited LIST plus a container wake". A wake is not free the way a LIST
77
+ // is. `WalgitContainer.sleepAfter` is 20m, so an hourly sweep holds the
78
+ // container up for at least a third of every hour on a deployment with no
79
+ // traffic at all, and the sweeper is the only thing asking. Daily makes the
80
+ // floor a twenty-fourth of that.
81
+ //
82
+ // Safe in every deployment that shares this file, including a preview one:
83
+ // expiry is off unless `WALGIT_RETENTION_HOURS` is set, and the container
84
+ // then exposes no sweep endpoint at all, so the cron logs a 404 and collects
85
+ // nothing. Unlike a route, a Cron Trigger is per-Worker rather than per-zone,
86
+ // so it cannot be stolen by another deployment of this same config.
87
+ "triggers": { "crons": ["0 4 * * *"] },
88
+ "migrations": [
89
+ { "tag": "v1", "new_sqlite_classes": ["WalgitContainer"] },
90
+ { "tag": "v2", "new_sqlite_classes": ["WalgitEvents"] }
91
+ ]
92
+ // No r2_buckets binding. The container writes the log itself, outside the
93
+ // Worker's binding graph, so it needs real S3 credentials (WALGIT_S3_*) —
94
+ // a binding here would reach only the Worker, which never touches the log.
95
+ }
@@ -17,7 +17,7 @@
17
17
  "devDependencies": {
18
18
  "@cloudflare/workers-types": "^4.20250101.0",
19
19
  "@types/bun": "^1.3.14",
20
- "typescript": "^5.7.0",
20
+ "typescript": "^7.0.2",
21
21
  "wrangler": "^4.0.0"
22
22
  }
23
23
  }