@zabaca/zbc 0.17.0 → 0.19.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.
@@ -0,0 +1,449 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * One bounded load run against a walgit DEPLOYMENT.
4
+ *
5
+ * bun run e2e/load.ts --origin https://agentgit.zabaca.com
6
+ * bun run e2e/load.ts --origin https://… --clones 8 --pushes 8 --watchers 8 --json run.json
7
+ *
8
+ * `suite.ts` measures one stream against a node it starts itself, which is the
9
+ * right shape for a regression gate and answers nothing about capacity: it has
10
+ * no edge, no Durable Object, no R2 and no contention. `live.ts` asks a
11
+ * deployment a yes/no question about its configuration. Neither produces a
12
+ * NUMBER for the question an operator actually has before handing the URL to a
13
+ * crowd — how many at once, and what gives way first.
14
+ *
15
+ * This does, for the three things a visitor does: clone, push, and subscribe to
16
+ * the ref-event stream. Every workload is real (`git` over HTTP, a real
17
+ * WebSocket); nothing here is stood in for, because a deployment is the thing
18
+ * being measured.
19
+ *
20
+ * ## What it spends, and why it refuses to spend more
21
+ *
22
+ * Every seeded repository is a NEW NAME and every push is a push, against a
23
+ * deployment that may rate-limit both per source (docs: the `WALGIT_MAX_*_PER_SOURCE`
24
+ * block in the instance). `parseLoadArgs` refuses a plan that would take more
25
+ * than half of agentgit production's hourly per-source budget: a run that spends
26
+ * it measures `src/rate-limit.ts` rather than the service, and leaves the rest
27
+ * of the hour unmeasurable for whoever runs next from the same address — which
28
+ * behind a NAT is more people than the operator.
29
+ *
30
+ * The run is also ordered so that the cheap questions are answered first:
31
+ * seeding is sequential (it is the reference number, uncontended), then the
32
+ * clone burst, then the push burst, then the fan-out. A saturated container
33
+ * shows up in the later phases, and stopping early still leaves a usable
34
+ * report rather than nothing.
35
+ *
36
+ * ## What it leaves behind
37
+ *
38
+ * `load-<run id>-*` repositories on the origin, world-readable, named on the
39
+ * way out. On a deployment with a retention window they are collected by it;
40
+ * on one without, they are permanent — which is stated rather than assumed,
41
+ * because this file must not be the reason a private host fills up.
42
+ *
43
+ * ## Exit codes
44
+ *
45
+ * | 0 | the run completed — read the report for the verdict |
46
+ * | 1 | the origin could not be measured at all |
47
+ * | 64 | the arguments were wrong |
48
+ */
49
+
50
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
51
+ import { tmpdir } from 'node:os'
52
+ import { join } from 'node:path'
53
+ import {
54
+ type OpSummary,
55
+ type Sample,
56
+ nameBottleneck,
57
+ parseLoadArgs,
58
+ summarize,
59
+ } from './load-report'
60
+
61
+ const parsed = parseLoadArgs(Bun.argv.slice(2))
62
+ if (!parsed.ok) {
63
+ console.error(`walgit load: ${parsed.error}`)
64
+ process.exit(64)
65
+ }
66
+ const options = parsed.value
67
+
68
+ const runId = Math.random().toString(36).slice(2, 8)
69
+ const scratch = mkdtempSync(join(tmpdir(), 'walgit-load-'))
70
+
71
+ /**
72
+ * The repositories this run actually created, each with the working copy it
73
+ * was pushed from.
74
+ *
75
+ * The pair travels together rather than as two lists indexed in parallel: a
76
+ * seed that FAILS leaves a gap, and a later phase indexing names by the
77
+ * position it seeded from would push one repository's working copy at another
78
+ * repository's name — arriving as a non-fast-forward and being recorded as the
79
+ * host giving way under load, which is the one mistake this tool exists to
80
+ * avoid making.
81
+ */
82
+ const seeded: { name: string; dir: string }[] = []
83
+
84
+ process.on('exit', () => rmSync(scratch, { recursive: true, force: true }))
85
+
86
+ /** `git`, with the ambient config out of the way, as the suite runs it. */
87
+ async function git(
88
+ args: readonly string[],
89
+ cwd: string,
90
+ ): Promise<{ code: number; stderr: string }> {
91
+ const proc = Bun.spawn(['git', ...args], {
92
+ cwd,
93
+ stdout: 'pipe',
94
+ stderr: 'pipe',
95
+ env: {
96
+ ...process.env,
97
+ GIT_CONFIG_GLOBAL: '/dev/null',
98
+ GIT_CONFIG_SYSTEM: '/dev/null',
99
+ GIT_TERMINAL_PROMPT: '0',
100
+ GIT_ASKPASS: '/bin/false',
101
+ },
102
+ })
103
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited])
104
+ return { code, stderr }
105
+ }
106
+
107
+ /**
108
+ * One timed attempt.
109
+ *
110
+ * A rate-limit refusal is its own outcome rather than an error: the two mean
111
+ * opposite things about a deployment — one is the host working exactly as
112
+ * configured, the other is it failing — and a report that blends them says
113
+ * neither. `pre-receive` speaks the refusal, so it arrives as a `remote:`
114
+ * line on stderr with walgit's own words in it.
115
+ */
116
+ async function timed(run: () => Promise<{ code: number; stderr: string }>): Promise<Sample> {
117
+ const started = Bun.nanoseconds()
118
+ const { code, stderr } = await run()
119
+ const ms = (Bun.nanoseconds() - started) / 1e6
120
+ if (code === 0) return { ms, outcome: 'ok' }
121
+ const limited = stderr.includes('This is a walgit limit')
122
+ return {
123
+ ms,
124
+ outcome: limited ? 'limited' : 'error',
125
+ detail: firstMeaningfulLine(stderr),
126
+ }
127
+ }
128
+
129
+ function firstMeaningfulLine(stderr: string): string {
130
+ const line = stderr
131
+ .split('\n')
132
+ .map((each) => each.replace(/^remote:\s*/, '').trim())
133
+ .find((each) => each.length > 0 && !each.startsWith('Cloning into'))
134
+ return (line ?? 'no output').slice(0, 200)
135
+ }
136
+
137
+ /** Run `count` tasks with no more than `count` in flight — the burst IS the point. */
138
+ async function burst<T>(count: number, task: (index: number) => Promise<T>): Promise<T[]> {
139
+ return Promise.all(Array.from({ length: count }, (_, index) => task(index)))
140
+ }
141
+
142
+ async function seedRepo(index: number): Promise<Sample> {
143
+ const name = `load-${runId}-${index}`
144
+ const dir = join(scratch, `seed-${index}`)
145
+ await Bun.write(join(dir, 'README.md'), `walgit load run ${runId}, repository ${index}\n`)
146
+ await git(['init', '-q', '-b', 'main'], dir)
147
+ await git(['add', '-A'], dir)
148
+ await git(
149
+ ['-c', 'user.email=load@localhost', '-c', 'user.name=load', 'commit', '-q', '-m', 'seed'],
150
+ dir,
151
+ )
152
+ const sample = await timed(() =>
153
+ git(['push', '-q', `${options.origin}/${name}.git`, 'HEAD:refs/heads/main'], dir),
154
+ )
155
+ if (sample.outcome === 'ok') seeded.push({ name, dir })
156
+ return sample
157
+ }
158
+
159
+ async function cloneOnce(index: number): Promise<Sample> {
160
+ const { name } = seeded[index % seeded.length] as { name: string; dir: string }
161
+ return timed(() =>
162
+ git(['clone', '-q', `${options.origin}/${name}.git`, join(scratch, `clone-${index}`)], scratch),
163
+ )
164
+ }
165
+
166
+ /**
167
+ * One more commit onto a repository this run already owns.
168
+ *
169
+ * Distinct repositories per worker, deliberately: concurrent pushes to the SAME
170
+ * ref lose the compare-and-swap and would be measuring git's non-fast-forward
171
+ * refusal rather than the host's throughput.
172
+ */
173
+ async function pushOnce(index: number): Promise<Sample> {
174
+ const { name, dir } = seeded[index % seeded.length] as { name: string; dir: string }
175
+ await Bun.write(join(dir, `change-${index}.txt`), `${index} ${Date.now()}\n`)
176
+ await git(['add', '-A'], dir)
177
+ await git(
178
+ [
179
+ '-c',
180
+ 'user.email=load@localhost',
181
+ '-c',
182
+ 'user.name=load',
183
+ 'commit',
184
+ '-q',
185
+ '-m',
186
+ `change ${index}`,
187
+ ],
188
+ dir,
189
+ )
190
+ return timed(() =>
191
+ git(['push', '-q', `${options.origin}/${name}.git`, 'HEAD:refs/heads/main'], dir),
192
+ )
193
+ }
194
+
195
+ interface Watcher {
196
+ handshake: Sample
197
+ /**
198
+ * `Bun.nanoseconds()` at the moment the event for the target repository
199
+ * arrived, or null if none did.
200
+ *
201
+ * An absolute instant rather than a duration, because the interval that means
202
+ * anything — fan-out — starts at the wake-up push, which has not happened
203
+ * when the socket opens. The caller subtracts.
204
+ */
205
+ arrivedAt: Promise<number | null>
206
+ close: () => void
207
+ }
208
+
209
+ /**
210
+ * One subscriber on the ref-event stream: connect, `watch`, wait for the
211
+ * handshake, then wait for the event the wake-up push produces.
212
+ *
213
+ * The handshake is timed separately from delivery because they fail
214
+ * differently — the first is the Durable Object reading the Index once per
215
+ * repository named, the second is fan-out — and a report that adds them
216
+ * together cannot tell a slow subscribe from a slow push.
217
+ */
218
+ function openWatcher(repos: readonly string[], target: string): Promise<Watcher> {
219
+ const url = `${options.origin.replace(/^http/, 'ws')}/_walgit/events`
220
+ const started = Bun.nanoseconds()
221
+ return new Promise<Watcher>((resolve) => {
222
+ const socket = new WebSocket(url)
223
+ let handshaken = false
224
+ let resolveDelivered: (value: number | null) => void = () => {}
225
+ const arrivedAt = new Promise<number | null>((done) => {
226
+ resolveDelivered = done
227
+ })
228
+
229
+ const settle = (handshake: Sample) =>
230
+ resolve({
231
+ handshake,
232
+ arrivedAt,
233
+ close: () => {
234
+ resolveDelivered(null)
235
+ try {
236
+ socket.close()
237
+ } catch {
238
+ // Already gone; a closed socket is the state we wanted.
239
+ }
240
+ },
241
+ })
242
+
243
+ socket.addEventListener('open', () => {
244
+ socket.send(JSON.stringify({ watch: repos.map((repo) => ({ repo })) }))
245
+ })
246
+ socket.addEventListener('message', (event) => {
247
+ const message = JSON.parse(String(event.data)) as {
248
+ ok?: true
249
+ error?: string
250
+ repo?: string
251
+ ref?: string
252
+ }
253
+ if (!handshaken) {
254
+ handshaken = true
255
+ if (message.error !== undefined) {
256
+ settle({
257
+ ms: (Bun.nanoseconds() - started) / 1e6,
258
+ outcome: 'error',
259
+ detail: message.error,
260
+ })
261
+ return
262
+ }
263
+ settle({ ms: (Bun.nanoseconds() - started) / 1e6, outcome: 'ok' })
264
+ return
265
+ }
266
+ if (message.repo === target) resolveDelivered(Bun.nanoseconds())
267
+ })
268
+ socket.addEventListener('error', () => {
269
+ if (handshaken) {
270
+ resolveDelivered(null)
271
+ return
272
+ }
273
+ handshaken = true
274
+ settle({
275
+ ms: (Bun.nanoseconds() - started) / 1e6,
276
+ outcome: 'error',
277
+ detail: 'websocket error',
278
+ })
279
+ })
280
+ socket.addEventListener('close', () => resolveDelivered(null))
281
+ })
282
+ }
283
+
284
+ const ms = (value: number | null) => (value === null ? ' —' : `${Math.round(value)}`.padStart(5))
285
+
286
+ function row(label: string, summary: OpSummary): string {
287
+ return [
288
+ label.padEnd(12),
289
+ `n=${String(summary.n).padStart(3)}`,
290
+ `ok=${String(summary.ok).padStart(3)}`,
291
+ `err=${String(summary.errors).padStart(2)}`,
292
+ `limited=${String(summary.limited).padStart(2)}`,
293
+ `p50=${ms(summary.p50)}ms`,
294
+ `p95=${ms(summary.p95)}ms`,
295
+ `p99=${ms(summary.p99)}ms`,
296
+ `max=${ms(summary.max)}ms`,
297
+ ].join(' ')
298
+ }
299
+
300
+ async function main(): Promise<number> {
301
+ // Preflight: measure nothing against an origin that is not there, and record
302
+ // WHAT was measured — there is no version endpoint, so the deployment is
303
+ // identified by a fingerprint of the document it serves.
304
+ const started = Date.now()
305
+ let landing: Response
306
+ try {
307
+ landing = await fetch(`${options.origin}/llms.txt`)
308
+ } catch (error) {
309
+ console.error(`walgit load: could not reach ${options.origin}: ${(error as Error).message}`)
310
+ return 1
311
+ }
312
+ if (!landing.ok) {
313
+ console.error(`walgit load: ${options.origin}/llms.txt answered ${landing.status}`)
314
+ return 1
315
+ }
316
+ const document = await landing.text()
317
+ const fingerprint = Bun.hash(document).toString(16)
318
+
319
+ console.log(`walgit load run ${runId} against ${options.origin}`)
320
+ console.log(` /llms.txt fingerprint ${fingerprint} (${document.length} bytes)`)
321
+ console.log(
322
+ ` plan: ${options.repos} new names, ${options.clones} concurrent clones, ${options.pushes} concurrent pushes, ${options.watchers} subscribers`,
323
+ )
324
+
325
+ // Sequential on purpose: this is the uncontended reference the later phases
326
+ // are read against.
327
+ const seed: Sample[] = []
328
+ for (let index = 0; index < options.repos; index += 1) seed.push(await seedRepo(index))
329
+ if (seeded.length === 0) {
330
+ console.error('walgit load: no repository could be seeded; nothing to measure')
331
+ console.error(` ${seed[0]?.detail ?? 'no detail'}`)
332
+ return 1
333
+ }
334
+
335
+ const clone = options.clones > 0 ? await burst(options.clones, cloneOnce) : []
336
+
337
+ // One repository per concurrent push, held here as well as in the plan: a
338
+ // seed that failed means there are fewer repositories than the plan assumed,
339
+ // and pushing the difference anyway would put two workers on one ref and
340
+ // record git's non-fast-forward refusal as a load failure.
341
+ const pushers = Math.min(options.pushes, seeded.length)
342
+ if (pushers < options.pushes) {
343
+ console.log(
344
+ ` note: ${options.pushes - pushers} push worker(s) dropped — only ${seeded.length} of ${options.repos} repositories were seeded`,
345
+ )
346
+ }
347
+ const push = pushers > 0 ? await burst(pushers, pushOnce) : []
348
+
349
+ const handshakes: Sample[] = []
350
+ const deliveries: Sample[] = []
351
+ if (options.watchers > 0) {
352
+ const target = (seeded[0] as { name: string }).name
353
+ const names = seeded.map((repo) => repo.name)
354
+ const watchers = await Promise.all(
355
+ Array.from({ length: options.watchers }, () => openWatcher(names, target)),
356
+ )
357
+ handshakes.push(...watchers.map((watcher) => watcher.handshake))
358
+
359
+ // One push wakes every subscriber at once, which is the fan-out question.
360
+ //
361
+ // Measured from when that push STARTED, not from when it returned: the
362
+ // container announces in `post-receive`, so an event can and does arrive
363
+ // before the client's `git push` finishes, and measuring from the end
364
+ // would produce a negative number for the healthy case. The interval
365
+ // therefore contains the push itself — `push` in the table is what to
366
+ // subtract, and the spread across subscribers is the fan-out cost.
367
+ const wokeAt = Bun.nanoseconds()
368
+ const wake = await pushOnce(0)
369
+ const results = await Promise.all(
370
+ watchers.map((watcher) =>
371
+ Promise.race([
372
+ watcher.arrivedAt,
373
+ new Promise<number | null>((resolve) => setTimeout(() => resolve(null), 20_000)),
374
+ ]),
375
+ ),
376
+ )
377
+ for (const watcher of watchers) watcher.close()
378
+ for (const arrival of results) {
379
+ deliveries.push(
380
+ arrival === null
381
+ ? { ms: 20_000, outcome: 'error', detail: 'no event within 20s' }
382
+ : { ms: (arrival - wokeAt) / 1e6, outcome: 'ok' },
383
+ )
384
+ }
385
+ push.push(wake)
386
+ }
387
+
388
+ const byOp: Record<string, Sample[]> = {
389
+ 'seed-push': seed,
390
+ clone,
391
+ push,
392
+ subscribe: handshakes,
393
+ 'event-fanout': deliveries,
394
+ }
395
+ const summaries: Record<string, OpSummary> = Object.fromEntries(
396
+ Object.entries(byOp).map(([label, samples]) => [label, summarize(samples)]),
397
+ )
398
+ const verdict = nameBottleneck(summaries)
399
+
400
+ console.log('')
401
+ for (const [label, summary] of Object.entries(summaries)) {
402
+ if (summary.n > 0) console.log(` ${row(label, summary)}`)
403
+ }
404
+ console.log('')
405
+ console.log(` first to degrade: ${verdict.op ?? 'nothing'} — ${verdict.reason}`)
406
+ // The remote's own words, once per distinct refusal. A bottleneck named with
407
+ // no evidence is an opinion, and the difference between a saturated queue, a
408
+ // lost compare-and-swap and a rate limit is entirely in this line.
409
+ for (const [label, samples] of Object.entries(byOp)) {
410
+ const reasons = new Map<string, number>()
411
+ for (const sample of samples) {
412
+ if (sample.outcome === 'ok') continue
413
+ const detail = sample.detail ?? 'no detail'
414
+ reasons.set(detail, (reasons.get(detail) ?? 0) + 1)
415
+ }
416
+ for (const [detail, count] of reasons) console.log(` ${label} ×${count}: ${detail}`)
417
+ }
418
+ console.log(` left behind on ${options.origin}: ${seeded.map((repo) => repo.name).join(', ')}`)
419
+ console.log(" (collected by the deployment's retention window, if it has one)")
420
+
421
+ if (options.json !== null) {
422
+ writeFileSync(
423
+ options.json,
424
+ `${JSON.stringify(
425
+ {
426
+ runId,
427
+ origin: options.origin,
428
+ startedAt: new Date(started).toISOString(),
429
+ finishedAt: new Date().toISOString(),
430
+ documentFingerprint: fingerprint,
431
+ plan: options,
432
+ summaries,
433
+ // Every attempt, so a reader can recompute the table and read the
434
+ // refusals in the remote's own words rather than take this file's.
435
+ samples: byOp,
436
+ verdict,
437
+ repositories: seeded.map((repo) => repo.name),
438
+ },
439
+ null,
440
+ 2,
441
+ )}\n`,
442
+ )
443
+ console.log(` wrote ${options.json}`)
444
+ }
445
+
446
+ return 0
447
+ }
448
+
449
+ process.exit(await main())
@@ -7,12 +7,13 @@
7
7
  "walgit": "./src/cli.ts"
8
8
  },
9
9
  "scripts": {
10
- "test": "bun test src",
10
+ "test": "bun test src e2e",
11
11
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.worker.json",
12
12
  "bench:materialize": "bun run src/materialize.bench.ts",
13
13
  "walgit": "bun run src/cli.ts",
14
14
  "e2e": "bun run e2e/suite.ts",
15
15
  "e2e:live": "bun run e2e/live.ts",
16
+ "e2e:load": "bun run e2e/load.ts",
16
17
  "deploy": "wrangler deploy"
17
18
  },
18
19
  "dependencies": {
@@ -63,6 +63,10 @@ type CapabilityVar = Extract<
63
63
  | 'WALGIT_SIGNER_LISTS'
64
64
  | 'WALGIT_PRIVATE_REPOS'
65
65
  | 'WALGIT_PROPOSALS'
66
+ | 'WALGIT_RATE_WINDOW_SECONDS'
67
+ | 'WALGIT_MAX_NEW_REPOS_PER_SOURCE'
68
+ | 'WALGIT_MAX_PUSHES_PER_SOURCE'
69
+ | 'WALGIT_MAX_PUSH_BYTES_PER_SOURCE'
66
70
  >
67
71
 
68
72
  /**
@@ -182,8 +186,43 @@ export type Capabilities = {
182
186
  maxPushBytes: number | null
183
187
  /** Largest total size of one repository, in bytes. */
184
188
  maxRepoBytes: number | null
189
+ /**
190
+ * Anything at all is bounded PER SOURCE — what one client may spend in a
191
+ * window (`src/rate-limit.ts`).
192
+ *
193
+ * A predicate rather than three `!== null` tests at each renderer, for the
194
+ * reason `namesCanRefuse` and `namesCanBeClaimed` are both fields: a document
195
+ * that combined them for itself would be a fourth place the rule lives.
196
+ */
197
+ sourceLimited: boolean
198
+ /**
199
+ * The window the three limits below are counted in, in seconds.
200
+ *
201
+ * The one number here that is never `null`: it is not a limit, it is the unit
202
+ * the limits are stated in, and a deployment that sets a count without a
203
+ * window means the default one rather than no window at all. Unset,
204
+ * unparseable and non-positive all read as the default, for the reason
205
+ * `positiveNumber` collapses them everywhere else — a typo must not become a
206
+ * zero-length window, which would refuse nothing, or an infinite one, which
207
+ * would refuse a client forever.
208
+ */
209
+ rateWindowSeconds: number
210
+ /** New repository names one source may create per window. */
211
+ maxNewReposPerSource: number | null
212
+ /** Pushes one source may make per window. */
213
+ maxPushesPerSource: number | null
214
+ /** Bytes one source may push per window. */
215
+ maxPushBytesPerSource: number | null
185
216
  }
186
217
 
218
+ /**
219
+ * The window a deployment gets when it bounds a count and says nothing about
220
+ * over what. An hour: long enough that an ordinary working session is one
221
+ * window, short enough that a client refused inside it does not give up on the
222
+ * host.
223
+ */
224
+ export const DEFAULT_RATE_WINDOW_SECONDS = 3600
225
+
187
226
  /**
188
227
  * Read an environment into what it advertises.
189
228
  *
@@ -216,6 +255,10 @@ export function capabilitiesFrom(
216
255
  const signedPushes = signedPushEnabled(env.WALGIT_PUSH_CERT_SEED)
217
256
  const publicAccess = flagEnabled(env.WALGIT_PUBLIC)
218
257
 
258
+ const maxNewReposPerSource = positiveNumber(env.WALGIT_MAX_NEW_REPOS_PER_SOURCE)
259
+ const maxPushesPerSource = positiveNumber(env.WALGIT_MAX_PUSHES_PER_SOURCE)
260
+ const maxPushBytesPerSource = positiveNumber(env.WALGIT_MAX_PUSH_BYTES_PER_SOURCE)
261
+
219
262
  return {
220
263
  publicAccess,
221
264
  appendOnly: flagEnabled(env.WALGIT_APPEND_ONLY),
@@ -235,6 +278,15 @@ export function capabilitiesFrom(
235
278
  retentionHours: positiveNumber(env.WALGIT_RETENTION_HOURS),
236
279
  maxPushBytes: positiveNumber(env.WALGIT_MAX_PUSH_BYTES),
237
280
  maxRepoBytes: positiveNumber(env.WALGIT_MAX_REPO_BYTES),
281
+ sourceLimited:
282
+ maxNewReposPerSource !== null ||
283
+ maxPushesPerSource !== null ||
284
+ maxPushBytesPerSource !== null,
285
+ rateWindowSeconds:
286
+ positiveNumber(env.WALGIT_RATE_WINDOW_SECONDS) ?? DEFAULT_RATE_WINDOW_SECONDS,
287
+ maxNewReposPerSource,
288
+ maxPushesPerSource,
289
+ maxPushBytesPerSource,
238
290
  }
239
291
  }
240
292
 
@@ -24,6 +24,24 @@
24
24
  * and an unset one simply means unenforced.
25
25
  */
26
26
  export const CONTAINER_ENV = [
27
+ // Which deploy this is, and the one variable here that configures nothing.
28
+ //
29
+ // Everything else on this list changes what the container DOES; this changes
30
+ // only the fingerprint, which is the point. A deploy that ships a new image
31
+ // and no new configuration moves no value above, so the Durable Object sees
32
+ // an unchanged environment and leaves the old container serving — observed
33
+ // on the 0.16.1 production deploy, where `--containers-rollout immediate`
34
+ // reported a completed rollout and the instance answering git was the one
35
+ // started an hour before. The image is not something this side can inspect,
36
+ // so the deploy names itself instead: the cloudflare module's `deployIdVar`
37
+ // passes the deployed commit as a var, and this line is what carries it the
38
+ // last hop into the container.
39
+ //
40
+ // Nothing reads it. It is visible in the container's own environment and on
41
+ // the Worker's variables in the dashboard, which is the second thing it buys
42
+ // — Cloudflare numbers container versions itself (v50, v51) and nothing else
43
+ // in the deploy says which commit that is.
44
+ 'WALGIT_BUILD_ID',
27
45
  'WALGIT_HTTP_TOKENS',
28
46
  'WALGIT_S3_ENDPOINT',
29
47
  'WALGIT_S3_BUCKET',
@@ -64,6 +82,14 @@ export const CONTAINER_ENV = [
64
82
  // nonce and mints nothing — it only widens what `pre-receive` accepts on a
65
83
  // claimed name, and the hook that widens runs in the container.
66
84
  'WALGIT_PROPOSALS',
85
+ // Per-source rate limits (src/rate-limit.ts). The verdict is reached in the
86
+ // container's own HTTP handler — the only place that sees both the source the
87
+ // edge attributed the request to and the repository it names — so the numbers
88
+ // have to reach the container like every other limit here.
89
+ 'WALGIT_RATE_WINDOW_SECONDS',
90
+ 'WALGIT_MAX_NEW_REPOS_PER_SOURCE',
91
+ 'WALGIT_MAX_PUSHES_PER_SOURCE',
92
+ 'WALGIT_MAX_PUSH_BYTES_PER_SOURCE',
67
93
  ] as const
68
94
 
69
95
  export type ContainerEnvName = (typeof CONTAINER_ENV)[number]
@@ -121,3 +147,66 @@ export function fingerprintEnv(env: Record<string, string>): string {
121
147
  }
122
148
  return (hash >>> 0).toString(16).padStart(8, '0')
123
149
  }
150
+
151
+ /**
152
+ * The half of a Durable Object that `reconcileContainerEnv` needs: whether a
153
+ * container is running, how to kill it, and where the fingerprint it booted
154
+ * with is kept.
155
+ *
156
+ * A port rather than the `Container` class itself because this module imports
157
+ * no runtime (ADR-0010) — and because the rule below is about ORDER, which is
158
+ * only observable from outside the object performing it.
159
+ */
160
+ export interface ContainerReconcileTarget {
161
+ /** Is a container process currently running for this Durable Object? */
162
+ readonly running: boolean
163
+ /** The fingerprint recorded by the last reconcile, if there has been one. */
164
+ read(): Promise<string | undefined>
165
+ /** Kill the running container. The next request starts a fresh one. */
166
+ destroy(): Promise<void>
167
+ /** Record the fingerprint the container is now running. */
168
+ write(fingerprint: string): Promise<void>
169
+ }
170
+
171
+ /** What a reconcile did, for the caller to log. */
172
+ export type ContainerReconcileOutcome = 'unchanged' | 'recorded' | 'replaced'
173
+
174
+ /**
175
+ * Replace the container if it is running an environment this deploy changed.
176
+ *
177
+ * The caller re-reads its own environment on every Durable Object
178
+ * construction, and a `wrangler deploy` constructs a new one — so that side is
179
+ * never stale. The container is: it read `process.env` once at start and cannot
180
+ * be told anything afterwards. Without this, a new value takes effect whenever
181
+ * the container next happens to idle out, which under sustained traffic is
182
+ * never.
183
+ *
184
+ * The fingerprint is persisted rather than held in memory because that is the
185
+ * only state that survives the very event being detected — a redeploy discards
186
+ * every in-memory field, so an in-memory copy would compare the new environment
187
+ * against itself and always agree.
188
+ *
189
+ * Two rules the tests pin, both learned the hard way:
190
+ *
191
+ * - NO RECORD counts as a mismatch, not as a fresh start. A running container
192
+ * with no record predates this code, so what it booted with is unknowable,
193
+ * and on the deploy that ships this it is exactly the container already
194
+ * serving a superseded environment. A Durable Object that has never started
195
+ * one arrives here with `running` false and simply records.
196
+ * - The write happens LAST, and only after a successful destroy. Recording
197
+ * first would make a failed replacement look reconciled forever.
198
+ */
199
+ export async function reconcileContainerEnv(
200
+ target: ContainerReconcileTarget,
201
+ current: string,
202
+ ): Promise<ContainerReconcileOutcome> {
203
+ const booted = await target.read()
204
+ if (booted === current) return 'unchanged'
205
+
206
+ // Only a RUNNING container can be stale. A stopped one has nothing to
207
+ // replace: its next start reads the environment as it now is.
208
+ const replaced = target.running
209
+ if (replaced) await target.destroy()
210
+ await target.write(current)
211
+ return replaced ? 'replaced' : 'recorded'
212
+ }