@zabaca/zbc 0.22.0 → 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.
- package/package.json +1 -1
- package/templates/CLAUDE.md +5 -0
- package/templates/apps/walgit/CONTEXT.md +5 -1
- package/templates/apps/walgit/README.md +159 -24
- package/templates/apps/walgit/package.json +2 -2
- package/templates/apps/walgit/registry.json +1 -1
- package/templates/apps/walgit/shared/browse.ts +18 -4
- package/templates/apps/walgit/shared/capabilities.ts +28 -3
- package/templates/apps/walgit/shared/container-env.ts +41 -2
- package/templates/apps/walgit/shared/container-lifecycle.ts +239 -0
- package/templates/apps/walgit/shared/container-snapshot.ts +219 -0
- package/templates/apps/walgit/shared/edge-refs.ts +612 -0
- package/templates/apps/walgit/{src → shared}/instructions.ts +8 -4
- package/templates/apps/walgit/shared/keys.ts +17 -0
- package/templates/apps/walgit/shared/landing.ts +10 -3
- package/templates/apps/walgit/shared/llms.ts +14 -5
- package/templates/apps/walgit/shared/policy.ts +1 -1
- package/templates/apps/walgit/shared/protocol.ts +35 -0
- package/templates/apps/walgit/shared/sleep-after.ts +44 -0
- package/templates/apps/walgit/shared/wal-index.ts +22 -1
- package/templates/apps/walgit/src/boot-residue.ts +58 -0
- package/templates/apps/walgit/src/cache.ts +9 -0
- package/templates/apps/walgit/src/cli.ts +39 -4
- package/templates/apps/walgit/src/delete-repo.ts +58 -9
- package/templates/apps/walgit/src/edge-refs.ts +148 -0
- package/templates/apps/walgit/src/expire.ts +75 -7
- package/templates/apps/walgit/src/hook-main.ts +2 -0
- package/templates/apps/walgit/src/http.ts +17 -4
- package/templates/apps/walgit/src/materialize.ts +34 -15
- package/templates/apps/walgit/src/push.ts +34 -8
- package/templates/apps/walgit/src/reconcile.ts +6 -1
- package/templates/apps/walgit/src/server.ts +69 -8
- package/templates/apps/walgit/src/sync.ts +10 -2
- package/templates/apps/walgit/worker/container-binding.ts +104 -0
- package/templates/apps/walgit/worker/durable-container.ts +786 -0
- package/templates/apps/walgit/worker/events-do.ts +16 -12
- package/templates/apps/walgit/worker/index.ts +235 -17
- package/templates/apps/walgit/worker/mcp.ts +9 -4
- package/templates/apps/walgit/wrangler.jsonc +44 -33
- package/templates/claude/settings.json +8 -0
- package/templates/infra/modules/cloudflare/index.ts +9 -0
- package/templates/infra/modules/d1/index.ts +30 -4
- package/templates/infra/modules/d1/registry.json +1 -1
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two git requests the edge answers without waking the container.
|
|
3
|
+
*
|
|
4
|
+
* Nearly all of a public deployment's git traffic is agents polling a ref: a
|
|
5
|
+
* protocol-v2 `GET /<name>.git/info/refs?service=git-upload-pack` (no body in,
|
|
6
|
+
* the capability advertisement out), then a `POST /<name>.git/git-upload-pack`
|
|
7
|
+
* carrying `command=ls-refs` (about a hundred bytes in, one ref back). Every one
|
|
8
|
+
* of those reached the one container and kept it awake, and a container that
|
|
9
|
+
* never sleeps is paid for around the clock while a cold one costs the next
|
|
10
|
+
* clone 12–22 s. Neither request needs a git object: the advertisement is a
|
|
11
|
+
* fact about the container's git, and the refs are a fact about the Index.
|
|
12
|
+
*
|
|
13
|
+
* So the edge answers both, from two places, and the split is the design:
|
|
14
|
+
*
|
|
15
|
+
* - **What git says about itself** — the advertisement's bytes and every
|
|
16
|
+
* header on both answers — comes from the container's OWN git, which
|
|
17
|
+
* publishes it to the object store when it boots (`UploadPackRecord`,
|
|
18
|
+
* written by `src/edge-refs.ts`). Nothing here is typed out from the spec:
|
|
19
|
+
* a hard-coded advertisement would go on claiming `fetch=shallow` or
|
|
20
|
+
* `ls-refs=unborn` after an image upgrade changed what the git behind it
|
|
21
|
+
* can do, and nothing would say so.
|
|
22
|
+
* - **What the refs are** — from `index.json`, the source of truth. A push is
|
|
23
|
+
* acknowledged only after the Index's compare-and-swap lands, so the Index
|
|
24
|
+
* is never behind anything a client could have been told; the container
|
|
25
|
+
* reconciles its Cache to exactly this map before it serves, and points
|
|
26
|
+
* `HEAD` at `defaultBranch` of it (`src/materialize.ts`'s `ensureHead`),
|
|
27
|
+
* which is the one function this file calls for the same answer.
|
|
28
|
+
*
|
|
29
|
+
* Every rule below has the same failure direction: any doubt is `null`, and the
|
|
30
|
+
* request goes to the container exactly as it did before this file existed.
|
|
31
|
+
* The edge never refuses anything here and never answers a shape it has not
|
|
32
|
+
* been shown byte-for-byte equivalent on (`src/edge-refs.test.ts` holds the
|
|
33
|
+
* output against real `git upload-pack`).
|
|
34
|
+
*
|
|
35
|
+
* Pure apart from `refsAtEdge`, whose only I/O is the two store reads it is
|
|
36
|
+
* handed a store for — so the Worker, which bun cannot run, is a thin caller.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { defaultBranch } from './browse'
|
|
40
|
+
import { containerEnv, fingerprintEnv, type ContainerEnvName } from './container-env'
|
|
41
|
+
import { uploadPackKey } from './keys'
|
|
42
|
+
import { REPO_ID, SMART_HTTP } from './protocol'
|
|
43
|
+
import type { ObjectStore } from './store'
|
|
44
|
+
import { loadIndex, type WalIndex } from './wal-index'
|
|
45
|
+
|
|
46
|
+
/** What `info/refs?service=git-upload-pack` answers with. */
|
|
47
|
+
export const ADVERTISEMENT_TYPE = 'application/x-git-upload-pack-advertisement'
|
|
48
|
+
|
|
49
|
+
/** What a `git-upload-pack` POST answers with. */
|
|
50
|
+
export const RESULT_TYPE = 'application/x-git-upload-pack-result'
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* What a `git-upload-pack` POST must carry. `git http-backend` compares it
|
|
54
|
+
* exactly and answers anything else 415, so the edge does too — by not
|
|
55
|
+
* answering it.
|
|
56
|
+
*/
|
|
57
|
+
export const REQUEST_TYPE = 'application/x-git-upload-pack-request'
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The largest `ls-refs` body the edge will buffer to read.
|
|
61
|
+
*
|
|
62
|
+
* Measured requests are 102–175 bytes. A body has to be buffered to be read,
|
|
63
|
+
* and a buffered body has to be re-sent to the container when it turns out to
|
|
64
|
+
* be a `fetch` — so the cap is what keeps a negotiation, and never a pack,
|
|
65
|
+
* from being held in the Worker's memory. A body that declares no length
|
|
66
|
+
* (chunked) declares nothing to check against the cap, and is not read at all.
|
|
67
|
+
*/
|
|
68
|
+
export const LS_REFS_MAX_BYTES = 4096
|
|
69
|
+
|
|
70
|
+
// ── What the container's git says about itself ──────────────────────────────
|
|
71
|
+
|
|
72
|
+
/** One HTTP answer as `git http-backend` gave it, headers in its own order. */
|
|
73
|
+
export interface CapturedResponse {
|
|
74
|
+
status: number
|
|
75
|
+
/** Lower-cased names, as the container's runtime relays them. */
|
|
76
|
+
headers: [string, string][]
|
|
77
|
+
body: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* What a container publishes about its own git, under `uploadPackKeyFor`.
|
|
82
|
+
*
|
|
83
|
+
* Both answers are captured from `git http-backend` itself, against a probe
|
|
84
|
+
* repository provisioned the way every Cache is (`src/edge-refs.ts`), so the
|
|
85
|
+
* headers are http-backend's and not a copy of them. The advertisement does
|
|
86
|
+
* not depend on which repository answers it — it is the server's capabilities,
|
|
87
|
+
* not its refs — which the golden tests check against a repository with refs.
|
|
88
|
+
*/
|
|
89
|
+
export interface UploadPackRecord {
|
|
90
|
+
version: 1
|
|
91
|
+
/** `git --version` in the image that wrote this, for whoever reads the bucket. */
|
|
92
|
+
git: string
|
|
93
|
+
/** `GET info/refs?service=git-upload-pack` with `Git-Protocol: version=2`. */
|
|
94
|
+
advertisement: CapturedResponse
|
|
95
|
+
/** `command=ls-refs` against the empty probe: only its status and headers are used. */
|
|
96
|
+
lsRefs: CapturedResponse
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A record the edge has checked and may serve from. */
|
|
100
|
+
export interface UploadPackFacts {
|
|
101
|
+
advertisement: { headers: [string, string][]; body: string }
|
|
102
|
+
resultHeaders: [string, string][]
|
|
103
|
+
/** Advertised capability → its value, `null` for one advertised bare. */
|
|
104
|
+
capabilities: Map<string, string | null>
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Where the container booted with THIS environment publishes its record, or
|
|
109
|
+
* `null` when the edge must not trust one at all.
|
|
110
|
+
*
|
|
111
|
+
* Keyed by the same fingerprint the Worker replaces the container on
|
|
112
|
+
* (`shared/container-env.ts`): the Worker computes it from the environment it
|
|
113
|
+
* would boot a container with, the container from the environment it booted
|
|
114
|
+
* with, and `reconcileEnv` makes those the same container. So a deploy that
|
|
115
|
+
* changes anything forwarded — the image included, through `WALGIT_BUILD_ID` —
|
|
116
|
+
* reads a key nobody has written yet, falls through, wakes the new container,
|
|
117
|
+
* and that container publishes what ITS git says. A stale advertisement from
|
|
118
|
+
* the previous image is never read, because it is filed under a fingerprint
|
|
119
|
+
* this Worker no longer computes.
|
|
120
|
+
*
|
|
121
|
+
* `null` without `WALGIT_BUILD_ID`, deliberately: without it an image-only
|
|
122
|
+
* deploy keeps the fingerprint (the Durable Object cannot see an image), and an
|
|
123
|
+
* old git's advertisement would be served in front of a new one until the new
|
|
124
|
+
* container happened to boot. With no way to tell images apart, the edge does
|
|
125
|
+
* not answer — which is today's behaviour, not a refusal.
|
|
126
|
+
*/
|
|
127
|
+
export function uploadPackKeyFor(env: Partial<Record<ContainerEnvName, string>>): string | null {
|
|
128
|
+
const forwarded = containerEnv(env)
|
|
129
|
+
if (!forwarded.WALGIT_BUILD_ID) return null
|
|
130
|
+
return uploadPackKey(fingerprintEnv(forwarded))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The bytes a container writes for `record`. */
|
|
134
|
+
export function serializeUploadPackRecord(record: UploadPackRecord): Uint8Array {
|
|
135
|
+
return new TextEncoder().encode(`${JSON.stringify(record)}\n`)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The record, checked — or `null` when the edge should not serve from it.
|
|
140
|
+
*
|
|
141
|
+
* Checked rather than trusted because it is the one input here that came from
|
|
142
|
+
* a process rather than from a push: a probe that hit an error page, a git
|
|
143
|
+
* that answered v0, or an advertisement with no `ls-refs` would otherwise be
|
|
144
|
+
* served to every client as though it were the container's answer.
|
|
145
|
+
*/
|
|
146
|
+
export function parseUploadPackRecord(bytes: Uint8Array): UploadPackFacts | null {
|
|
147
|
+
let record: UploadPackRecord
|
|
148
|
+
try {
|
|
149
|
+
record = JSON.parse(new TextDecoder().decode(bytes)) as UploadPackRecord
|
|
150
|
+
} catch {
|
|
151
|
+
return null
|
|
152
|
+
}
|
|
153
|
+
if (record?.version !== 1) return null
|
|
154
|
+
const advertisement = captured(record.advertisement, ADVERTISEMENT_TYPE)
|
|
155
|
+
const lsRefs = captured(record.lsRefs, RESULT_TYPE)
|
|
156
|
+
if (!advertisement || !lsRefs) return null
|
|
157
|
+
// The empty probe's `ls-refs` is a bare flush. Anything else means the POST
|
|
158
|
+
// did not reach `ls-refs` at all, and its headers are not the ones to copy.
|
|
159
|
+
if (lsRefs.body !== FLUSH) return null
|
|
160
|
+
|
|
161
|
+
const pkts = readPkts(new TextEncoder().encode(advertisement.body))
|
|
162
|
+
if (!pkts || pkts.length < 2) return null
|
|
163
|
+
// `version 2` first and a flush last, with nothing after it: the shape git
|
|
164
|
+
// gives a v2 client, and NOT the `# service=` preamble a v0 one is sent.
|
|
165
|
+
const [first, ...rest] = pkts
|
|
166
|
+
if (first?.kind !== 'data' || ascii(first.payload) !== 'version 2\n') return null
|
|
167
|
+
if (rest.pop()?.kind !== 'flush') return null
|
|
168
|
+
const capabilities = new Map<string, string | null>()
|
|
169
|
+
for (const p of rest) {
|
|
170
|
+
if (p.kind !== 'data') return null
|
|
171
|
+
const line = ascii(p.payload)
|
|
172
|
+
if (line === null || !line.endsWith('\n')) return null
|
|
173
|
+
const text = line.slice(0, -1)
|
|
174
|
+
const eq = text.indexOf('=')
|
|
175
|
+
capabilities.set(eq === -1 ? text : text.slice(0, eq), eq === -1 ? null : text.slice(eq + 1))
|
|
176
|
+
}
|
|
177
|
+
// The command this file answers must be one the container's git has, and
|
|
178
|
+
// the oids in the Index are SHA-1: a git advertising another object format
|
|
179
|
+
// would be refusing every line rendered below.
|
|
180
|
+
if (!capabilities.has('ls-refs')) return null
|
|
181
|
+
const format = capabilities.get('object-format')
|
|
182
|
+
if (format !== undefined && format !== 'sha1') return null
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
advertisement: { headers: advertisement.headers, body: advertisement.body },
|
|
186
|
+
resultHeaders: lsRefs.headers,
|
|
187
|
+
capabilities,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function captured(value: CapturedResponse | undefined, type: string): CapturedResponse | null {
|
|
192
|
+
if (!value || value.status !== 200 || typeof value.body !== 'string') return null
|
|
193
|
+
if (!Array.isArray(value.headers)) return null
|
|
194
|
+
const pairs: [string, string][] = []
|
|
195
|
+
for (const pair of value.headers) {
|
|
196
|
+
if (!Array.isArray(pair) || typeof pair[0] !== 'string' || typeof pair[1] !== 'string') {
|
|
197
|
+
return null
|
|
198
|
+
}
|
|
199
|
+
pairs.push([pair[0].toLowerCase(), pair[1]])
|
|
200
|
+
}
|
|
201
|
+
if (pairs.find(([name]) => name === 'content-type')?.[1] !== type) return null
|
|
202
|
+
return { status: 200, headers: pairs, body: value.body }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ── pkt-lines ───────────────────────────────────────────────────────────────
|
|
206
|
+
|
|
207
|
+
type Pkt = { kind: 'data'; payload: Uint8Array } | { kind: 'flush' | 'delim' | 'response-end' }
|
|
208
|
+
|
|
209
|
+
/** The flush packet that ends every section. */
|
|
210
|
+
const FLUSH = '0000'
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Every pkt-line in `bytes`, or `null` when they do not frame exactly.
|
|
214
|
+
*
|
|
215
|
+
* Four hex length bytes counting themselves, then the payload; `0000`, `0001`
|
|
216
|
+
* and `0002` are the three special packets. A length git would die on (`0003`,
|
|
217
|
+
* a packet running past the end) and an empty data packet are both `null`:
|
|
218
|
+
* the container's git would refuse those requests, and the edge answering one
|
|
219
|
+
* would be the edge disagreeing with it.
|
|
220
|
+
*/
|
|
221
|
+
function readPkts(bytes: Uint8Array): Pkt[] | null {
|
|
222
|
+
const out: Pkt[] = []
|
|
223
|
+
let at = 0
|
|
224
|
+
while (at < bytes.length) {
|
|
225
|
+
if (at + 4 > bytes.length) return null
|
|
226
|
+
const head = String.fromCharCode(...bytes.subarray(at, at + 4))
|
|
227
|
+
if (!/^[0-9a-fA-F]{4}$/.test(head)) return null
|
|
228
|
+
const length = parseInt(head, 16)
|
|
229
|
+
at += 4
|
|
230
|
+
if (length === 0) out.push({ kind: 'flush' })
|
|
231
|
+
else if (length === 1) out.push({ kind: 'delim' })
|
|
232
|
+
else if (length === 2) out.push({ kind: 'response-end' })
|
|
233
|
+
else if (length <= 4 || at + length - 4 > bytes.length) return null
|
|
234
|
+
else {
|
|
235
|
+
out.push({ kind: 'data', payload: bytes.subarray(at, at + length - 4) })
|
|
236
|
+
at += length - 4
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return out
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The payload as text, or `null` when it holds anything but printable ASCII and
|
|
244
|
+
* newlines.
|
|
245
|
+
*
|
|
246
|
+
* Nothing in either request legitimately carries more, and git reads these
|
|
247
|
+
* payloads as C strings: a NUL would end a `ref-prefix` early on its side and
|
|
248
|
+
* not on this one.
|
|
249
|
+
*/
|
|
250
|
+
function ascii(payload: Uint8Array): string | null {
|
|
251
|
+
for (const byte of payload) if ((byte < 0x20 || byte > 0x7e) && byte !== 0x0a) return null
|
|
252
|
+
return String.fromCharCode(...payload)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** One line, framed. Only ever handed ASCII, so a character is a byte. */
|
|
256
|
+
function pkt(line: string): string {
|
|
257
|
+
return `${(line.length + 4).toString(16).padStart(4, '0')}${line}`
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** git strips exactly one trailing newline from a pkt-line it reads as text. */
|
|
261
|
+
function chomp(line: string): string {
|
|
262
|
+
return line.endsWith('\n') ? line.slice(0, -1) : line
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ── The request ─────────────────────────────────────────────────────────────
|
|
266
|
+
|
|
267
|
+
/** Which of the two requests this is, and the repository it names. */
|
|
268
|
+
export interface EdgeRefsRoute {
|
|
269
|
+
kind: 'advertise' | 'ls-refs'
|
|
270
|
+
repo: string
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Does this client speak protocol v2, as the container's git would read the
|
|
275
|
+
* header?
|
|
276
|
+
*
|
|
277
|
+
* Not `includes('version=2')`. git splits `GIT_PROTOCOL` on `:`, takes the
|
|
278
|
+
* highest of the `version=` items it recognises, and recognises exactly `0`,
|
|
279
|
+
* `1` and `2` — so `version=20` and `version=02` are a v0 client to it, and a
|
|
280
|
+
* v0 client is sent the `# service=` preamble this file never renders.
|
|
281
|
+
*/
|
|
282
|
+
export function speaksV2(header: string | null): boolean {
|
|
283
|
+
if (header === null) return false
|
|
284
|
+
let version = 0
|
|
285
|
+
for (const item of header.split(':')) {
|
|
286
|
+
const value = item.startsWith('version=') ? item.slice('version='.length) : null
|
|
287
|
+
if (value === '0' || value === '1' || value === '2') version = Math.max(version, Number(value))
|
|
288
|
+
}
|
|
289
|
+
return version === 2
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* The request, if it is one the edge may try to answer — decided from the
|
|
294
|
+
* method, URL and headers alone, before a byte of the body is read.
|
|
295
|
+
*
|
|
296
|
+
* `null` is "forward it", for everything else: a push or its advertisement, a
|
|
297
|
+
* v0/v1 client, a `HEAD` (no git client sends one), a POST whose body is
|
|
298
|
+
* compressed (git gzips the large ones) or too large to inspect, or one with
|
|
299
|
+
* no length to check.
|
|
300
|
+
*/
|
|
301
|
+
export function edgeRefsRoute(request: Request): EdgeRefsRoute | null {
|
|
302
|
+
const url = new URL(request.url)
|
|
303
|
+
const route = SMART_HTTP.exec(url.pathname)
|
|
304
|
+
if (!route) return null
|
|
305
|
+
// The container strips one `.git` and the URL grammar another, so
|
|
306
|
+
// `/alpha.git.git` is the repository `alpha` there. Left to it rather than
|
|
307
|
+
// re-derived here, exactly as `absentAtEdge` does in the Worker.
|
|
308
|
+
const repo = route[1]!
|
|
309
|
+
if (repo.endsWith('.git') || !REPO_ID.test(repo)) return null
|
|
310
|
+
if (!speaksV2(request.headers.get('git-protocol'))) return null
|
|
311
|
+
|
|
312
|
+
if (route[2] === 'info/refs') {
|
|
313
|
+
if (request.method !== 'GET') return null
|
|
314
|
+
const service = url.searchParams.getAll('service')
|
|
315
|
+
if (service.length !== 1 || service[0] !== 'git-upload-pack') return null
|
|
316
|
+
return { kind: 'advertise', repo }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (route[2] !== 'git-upload-pack' || request.method !== 'POST') return null
|
|
320
|
+
if (request.headers.get('content-type') !== REQUEST_TYPE) return null
|
|
321
|
+
// Any encoding at all, including one http-backend would pass through: the
|
|
322
|
+
// only bytes the edge reads are the ones it was not asked to decode.
|
|
323
|
+
if ((request.headers.get('content-encoding') ?? '') !== '') return null
|
|
324
|
+
const declared = request.headers.get('content-length') ?? ''
|
|
325
|
+
if (!/^\d+$/.test(declared)) return null
|
|
326
|
+
const length = Number(declared)
|
|
327
|
+
if (length === 0 || length > LS_REFS_MAX_BYTES) return null
|
|
328
|
+
return { kind: 'ls-refs', repo }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** What one `ls-refs` asked for. */
|
|
332
|
+
export interface LsRefsRequest {
|
|
333
|
+
symrefs: boolean
|
|
334
|
+
peel: boolean
|
|
335
|
+
unborn: boolean
|
|
336
|
+
/** `ref-prefix` arguments; empty means every ref. */
|
|
337
|
+
prefixes: string[]
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The first packet of an `ls-refs` request, as git's client writes it. */
|
|
341
|
+
const LS_REFS_COMMAND = 'command=ls-refs'
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Is this body an `ls-refs` at all? Cheap, and asked before anything is read
|
|
345
|
+
* from the store, so a `fetch` — the clone itself — costs the edge no read.
|
|
346
|
+
*/
|
|
347
|
+
export function isLsRefs(body: Uint8Array): boolean {
|
|
348
|
+
const pkts = readPkts(body)
|
|
349
|
+
const first = pkts?.[0]
|
|
350
|
+
return first?.kind === 'data' && chomp(ascii(first.payload) ?? '') === LS_REFS_COMMAND
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* One `ls-refs` request, read the way the container's git reads it — or `null`
|
|
355
|
+
* for anything it would read differently, refuse, or that this file does not
|
|
356
|
+
* render.
|
|
357
|
+
*
|
|
358
|
+
* The shape is fixed: the command, the capabilities the client sends with it,
|
|
359
|
+
* a delimiter, the arguments, a flush, and nothing after. A capability is
|
|
360
|
+
* accepted only if the container's git ADVERTISED it, because that git dies on
|
|
361
|
+
* one it did not (`unknown capability`), and only the three that change nothing
|
|
362
|
+
* about the answer: `agent`, `session-id`, and `object-format` naming the
|
|
363
|
+
* format advertised. A `server-option` falls through. So does any argument
|
|
364
|
+
* besides the four `ls-refs` defines.
|
|
365
|
+
*/
|
|
366
|
+
export function parseLsRefsRequest(
|
|
367
|
+
body: Uint8Array,
|
|
368
|
+
capabilities: Map<string, string | null>,
|
|
369
|
+
): LsRefsRequest | null {
|
|
370
|
+
const pkts = readPkts(body)
|
|
371
|
+
// The command, the delimiter and the flush at the least; and the flush last,
|
|
372
|
+
// with nothing after it, because a stateless request is exactly one command.
|
|
373
|
+
if (!pkts || pkts.length < 3 || pkts.pop()?.kind !== 'flush') return null
|
|
374
|
+
const delim = pkts.findIndex((p) => p.kind === 'delim')
|
|
375
|
+
if (delim === -1) return null
|
|
376
|
+
// Every other packet is a line of text with at most its trailing newline.
|
|
377
|
+
const text = (p: Pkt): string | null => {
|
|
378
|
+
if (p.kind !== 'data') return null
|
|
379
|
+
const line = ascii(p.payload)
|
|
380
|
+
if (line === null) return null
|
|
381
|
+
const chomped = chomp(line)
|
|
382
|
+
return chomped.includes('\n') ? null : chomped
|
|
383
|
+
}
|
|
384
|
+
const head = pkts.slice(0, delim).map(text)
|
|
385
|
+
const args = pkts.slice(delim + 1).map(text)
|
|
386
|
+
if (head.includes(null) || args.includes(null)) return null
|
|
387
|
+
if (head[0] !== LS_REFS_COMMAND) return null
|
|
388
|
+
|
|
389
|
+
for (const line of head.slice(1) as string[]) {
|
|
390
|
+
const eq = line.indexOf('=')
|
|
391
|
+
const key = eq === -1 ? line : line.slice(0, eq)
|
|
392
|
+
if (!capabilities.has(key)) return null
|
|
393
|
+
if (key === 'agent' || key === 'session-id') continue
|
|
394
|
+
if (key === 'object-format' && line.slice(eq + 1) === capabilities.get(key)) continue
|
|
395
|
+
return null
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const request: LsRefsRequest = { symrefs: false, peel: false, unborn: false, prefixes: [] }
|
|
399
|
+
for (const line of args as string[]) {
|
|
400
|
+
if (line === 'symrefs') request.symrefs = true
|
|
401
|
+
else if (line === 'peel') request.peel = true
|
|
402
|
+
else if (line === 'unborn') request.unborn = true
|
|
403
|
+
else if (line.startsWith('ref-prefix ')) request.prefixes.push(line.slice('ref-prefix '.length))
|
|
404
|
+
else return null
|
|
405
|
+
}
|
|
406
|
+
return request
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ── The answers ─────────────────────────────────────────────────────────────
|
|
410
|
+
|
|
411
|
+
/** A response the edge may send, before it is a `Response`. */
|
|
412
|
+
export interface EdgeAnswer {
|
|
413
|
+
status: number
|
|
414
|
+
headers: [string, string][]
|
|
415
|
+
body: string
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** A full ref name the edge can render as git would, sort as git would, and frame as one byte per character. */
|
|
419
|
+
const RENDERABLE_REF = /^refs\/[\x21-\x7e]+$/
|
|
420
|
+
const SHA1 = /^[0-9a-f]{40}$/
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Would the container serve this Index's refs through `git http-backend`?
|
|
424
|
+
*
|
|
425
|
+
* Three ways it would not, and each is the container's own decision to make:
|
|
426
|
+
*
|
|
427
|
+
* - **No Index** — a name nobody has pushed to. The container's empty-read
|
|
428
|
+
* path answers it (`src/empty-read.ts`), with an advertisement of its own.
|
|
429
|
+
* - **No refs** — the same path, for a repository that exists and holds none.
|
|
430
|
+
* - **A Reader List** — the Private gate (`src/http.ts`'s `refuseRead`) asks
|
|
431
|
+
* for a signature before it serves anything. ANY `readers` field, even `[]`
|
|
432
|
+
* and even on a deployment whose container would not gate it: whether to
|
|
433
|
+
* challenge is the container's question, and an edge that answered a name
|
|
434
|
+
* the container would have challenged has published the name's refs.
|
|
435
|
+
*/
|
|
436
|
+
function servedByBackend(index: WalIndex | null): index is WalIndex {
|
|
437
|
+
if (!index) return false
|
|
438
|
+
if (Object.keys(index.refs).length === 0) return false
|
|
439
|
+
if (index.claim?.readers !== undefined) return false
|
|
440
|
+
return true
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** The advertisement, verbatim — or `null` when the container would answer otherwise. */
|
|
444
|
+
export function answerAdvertisement(
|
|
445
|
+
facts: UploadPackFacts,
|
|
446
|
+
index: WalIndex | null,
|
|
447
|
+
): EdgeAnswer | null {
|
|
448
|
+
if (!servedByBackend(index)) return null
|
|
449
|
+
return { status: 200, headers: facts.advertisement.headers, body: facts.advertisement.body }
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* The `ls-refs` lines for these refs, as git renders them — or `null` for any
|
|
454
|
+
* set of refs this cannot render exactly.
|
|
455
|
+
*
|
|
456
|
+
* `HEAD` first, then every ref in byte order, filtered by `ref-prefix` (a ref
|
|
457
|
+
* is listed when its name starts with any one of them; `HEAD` is tested as the
|
|
458
|
+
* string `HEAD`). Each line is `<oid> <name>`, with ` symref-target:<ref>` on
|
|
459
|
+
* `HEAD` when `symrefs` was asked — the refs themselves are never symbolic, as
|
|
460
|
+
* the Cache writes them all into `packed-refs` (`src/reconcile.ts`).
|
|
461
|
+
*
|
|
462
|
+
* Three refusals, each because the right answer needs something the Index does
|
|
463
|
+
* not hold:
|
|
464
|
+
*
|
|
465
|
+
* - **No branch.** `HEAD` is then unborn, and what git says about an unborn
|
|
466
|
+
* `HEAD` depends on which branch `git init` left it on.
|
|
467
|
+
* - **`peel` with a listed ref outside `refs/heads/`.** Peeling needs to know
|
|
468
|
+
* whether a ref names a tag object, and the Index holds oids, not types.
|
|
469
|
+
* A branch is safe — git refuses to point `refs/heads/` at anything but a
|
|
470
|
+
* commit — and `HEAD` points at a branch. The polling `ls-remote` asks for
|
|
471
|
+
* `peel` on every request, so this is narrow on purpose: a repository with
|
|
472
|
+
* tags falls through, one with only branches does not.
|
|
473
|
+
* - **A ref name or oid outside what is rendered here** — anything not
|
|
474
|
+
* printable ASCII, which is where JavaScript's sort and git's byte order
|
|
475
|
+
* could part, and where one character stops being one framed byte.
|
|
476
|
+
*/
|
|
477
|
+
export function renderLsRefs(refs: Record<string, string>, request: LsRefsRequest): string | null {
|
|
478
|
+
const head = defaultBranch(refs)
|
|
479
|
+
if (head === null) return null
|
|
480
|
+
const names = Object.keys(refs)
|
|
481
|
+
for (const name of names) {
|
|
482
|
+
if (!RENDERABLE_REF.test(name) || !SHA1.test(refs[name]!)) return null
|
|
483
|
+
}
|
|
484
|
+
const listed = (name: string) =>
|
|
485
|
+
request.prefixes.length === 0 || request.prefixes.some((prefix) => name.startsWith(prefix))
|
|
486
|
+
|
|
487
|
+
// `sort` on the fresh array rather than `toSorted`, for the Workers lib (see
|
|
488
|
+
// `defaultBranch`). Every name is ASCII here, so UTF-16 order is byte order.
|
|
489
|
+
const shown = names.filter(listed).sort()
|
|
490
|
+
if (request.peel && shown.some((name) => !name.startsWith('refs/heads/'))) return null
|
|
491
|
+
|
|
492
|
+
const lines: string[] = []
|
|
493
|
+
if (listed('HEAD')) {
|
|
494
|
+
lines.push(`${refs[head]} HEAD${request.symrefs ? ` symref-target:${head}` : ''}\n`)
|
|
495
|
+
}
|
|
496
|
+
for (const name of shown) lines.push(`${refs[name]} ${name}\n`)
|
|
497
|
+
return `${lines.map(pkt).join('')}${FLUSH}`
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** The `ls-refs` answer for this Index — or `null` when the container would answer otherwise. */
|
|
501
|
+
export function answerLsRefs(
|
|
502
|
+
facts: UploadPackFacts,
|
|
503
|
+
index: WalIndex | null,
|
|
504
|
+
request: LsRefsRequest,
|
|
505
|
+
): EdgeAnswer | null {
|
|
506
|
+
if (!servedByBackend(index)) return null
|
|
507
|
+
const body = renderLsRefs(index.refs, request)
|
|
508
|
+
if (body === null) return null
|
|
509
|
+
return { status: 200, headers: facts.resultHeaders, body }
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// ── The one function with I/O ───────────────────────────────────────────────
|
|
513
|
+
|
|
514
|
+
/** What `refsAtEdge` decided. */
|
|
515
|
+
export type EdgeRefsOutcome =
|
|
516
|
+
/** Answered: send this, and the container was never asked. */
|
|
517
|
+
| { response: Response; route: EdgeRefsRoute; bytes: number }
|
|
518
|
+
/**
|
|
519
|
+
* Not answered: forward THIS request. It is the original unless its body was
|
|
520
|
+
* read to be inspected, in which case it is a new request carrying exactly
|
|
521
|
+
* the bytes that arrived — a body stream is read once, and the container
|
|
522
|
+
* must still receive what the client sent.
|
|
523
|
+
*/
|
|
524
|
+
| { response: null; request: Request }
|
|
525
|
+
|
|
526
|
+
export interface EdgeRefsDeps {
|
|
527
|
+
/** `caps.publicAccess`. A token-gated container answers 401 first, and the edge must not get ahead of it. */
|
|
528
|
+
publicAccess: boolean
|
|
529
|
+
store: ObjectStore | null
|
|
530
|
+
/** `uploadPackKeyFor(env)`. */
|
|
531
|
+
recordKey: string | null
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Answer one of the two polling requests at the edge, or hand it back.
|
|
536
|
+
*
|
|
537
|
+
* The order is the cost model: every check that needs no I/O runs first, a
|
|
538
|
+
* body is read only for a POST small enough to hold, and the store is asked
|
|
539
|
+
* only once the body has said `ls-refs` — so a `fetch`, which is the clone
|
|
540
|
+
* itself, is forwarded having cost the edge nothing but a copy of a few hundred
|
|
541
|
+
* bytes. The record and the Index are then read together, and any failure to
|
|
542
|
+
* read either is a fall-through rather than an error: the container is always
|
|
543
|
+
* there to answer.
|
|
544
|
+
*/
|
|
545
|
+
export async function refsAtEdge(request: Request, deps: EdgeRefsDeps): Promise<EdgeRefsOutcome> {
|
|
546
|
+
const pass = (forward: Request = request): EdgeRefsOutcome => ({
|
|
547
|
+
response: null,
|
|
548
|
+
request: forward,
|
|
549
|
+
})
|
|
550
|
+
if (!deps.publicAccess || !deps.store || !deps.recordKey) return pass()
|
|
551
|
+
const route = edgeRefsRoute(request)
|
|
552
|
+
if (!route) return pass()
|
|
553
|
+
|
|
554
|
+
let body: Uint8Array | null = null
|
|
555
|
+
let forward = request
|
|
556
|
+
if (route.kind === 'ls-refs') {
|
|
557
|
+
try {
|
|
558
|
+
body = new Uint8Array(await request.arrayBuffer())
|
|
559
|
+
} catch {
|
|
560
|
+
// The client went away mid-body. There is nothing left to forward — the
|
|
561
|
+
// stream is spent — and nobody left to answer, so say so plainly rather
|
|
562
|
+
// than throw out of the Worker with no telemetry row.
|
|
563
|
+
return {
|
|
564
|
+
response: new Response('walgit: request body unreadable\n', { status: 400 }),
|
|
565
|
+
route,
|
|
566
|
+
bytes: 0,
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// Rebuilt from parts rather than `new Request(request, { body })`: the
|
|
570
|
+
// original's body is spent, and whether a runtime accepts a spent request
|
|
571
|
+
// as the template is not a thing to find out in production.
|
|
572
|
+
forward = new Request(request.url, {
|
|
573
|
+
method: request.method,
|
|
574
|
+
headers: request.headers,
|
|
575
|
+
body: body.slice().buffer as ArrayBuffer,
|
|
576
|
+
})
|
|
577
|
+
const declared = Number(request.headers.get('content-length'))
|
|
578
|
+
if (body.byteLength !== declared || !isLsRefs(body)) return pass(forward)
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
let facts: UploadPackFacts | null
|
|
582
|
+
let index: WalIndex | null
|
|
583
|
+
try {
|
|
584
|
+
const [record, loaded] = await Promise.all([
|
|
585
|
+
deps.store.get(deps.recordKey),
|
|
586
|
+
loadIndex(deps.store, route.repo),
|
|
587
|
+
])
|
|
588
|
+
facts = record ? parseUploadPackRecord(record.body) : null
|
|
589
|
+
// `loadIndex` answers an absent Index with an empty one; the etag is what
|
|
590
|
+
// tells the two apart, and they are different answers here.
|
|
591
|
+
index = loaded.etag === null ? null : loaded.index
|
|
592
|
+
} catch {
|
|
593
|
+
return pass(forward)
|
|
594
|
+
}
|
|
595
|
+
if (!facts) return pass(forward)
|
|
596
|
+
|
|
597
|
+
let answer: EdgeAnswer | null
|
|
598
|
+
if (route.kind === 'advertise') {
|
|
599
|
+
answer = answerAdvertisement(facts, index)
|
|
600
|
+
} else {
|
|
601
|
+
const asked = parseLsRefsRequest(body!, facts.capabilities)
|
|
602
|
+
answer = asked ? answerLsRefs(facts, index, asked) : null
|
|
603
|
+
}
|
|
604
|
+
if (!answer) return pass(forward)
|
|
605
|
+
|
|
606
|
+
const bytes = new TextEncoder().encode(answer.body)
|
|
607
|
+
return {
|
|
608
|
+
response: new Response(bytes, { status: answer.status, headers: answer.headers }),
|
|
609
|
+
route,
|
|
610
|
+
bytes: bytes.byteLength,
|
|
611
|
+
}
|
|
612
|
+
}
|
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
* constant.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import type { Capabilities } from '
|
|
19
|
-
import { describeBytes, describeWindow } from '
|
|
20
|
-
import { EVENTS_PATH, PROVENANCE_PATH } from '
|
|
18
|
+
import type { Capabilities } from './capabilities'
|
|
19
|
+
import { describeBytes, describeWindow } from './policy'
|
|
20
|
+
import { EVENTS_PATH, PROVENANCE_PATH } from './protocol'
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* Rendered per request rather than baked at boot, because the host an agent
|
|
@@ -112,7 +112,11 @@ function facts(caps: Capabilities): string[] {
|
|
|
112
112
|
}
|
|
113
113
|
if (caps.retentionHours !== null) {
|
|
114
114
|
facts.push(
|
|
115
|
-
`A repository is deleted ${describeHours(caps.retentionHours)} after its LAST PUSH. Cloning does not extend it; pushing does
|
|
115
|
+
`A repository is deleted ${describeHours(caps.retentionHours)} after its LAST PUSH. Cloning does not extend it; pushing does.${
|
|
116
|
+
caps.claimedRetentionHours !== null
|
|
117
|
+
? ` A claimed one — a name with a Signer List — is kept ${describeHours(caps.claimedRetentionHours)} instead.`
|
|
118
|
+
: ''
|
|
119
|
+
} This is scratch space — copy the work elsewhere if it must outlive that window.`,
|
|
116
120
|
)
|
|
117
121
|
}
|
|
118
122
|
if (caps.maxPushBytes !== null) {
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* repos/<repo_id>/wal/<seq>-<ulid>.pack one push's objects
|
|
18
18
|
* repos/<repo_id>/wal/<seq>-<ulid>.idx its sibling index
|
|
19
19
|
* repos/<repo_id>/compaction.lease who is compacting, until when
|
|
20
|
+
* walgit/upload-pack-v2/<fingerprint>.json what the container's git advertises
|
|
20
21
|
*
|
|
21
22
|
* Enumerating repositories lives here too, and that is a move rather than a new
|
|
22
23
|
* function: `listRepoIds` was in `usage.ts`, the read-only reporting command,
|
|
@@ -51,6 +52,22 @@ export function leaseKey(repoId: string): string {
|
|
|
51
52
|
return `${repoPrefix(repoId)}compaction.lease`
|
|
52
53
|
}
|
|
53
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Where a container publishes the protocol-v2 advertisement its own git makes
|
|
57
|
+
* (`shared/edge-refs.ts`), one object per environment it booted with.
|
|
58
|
+
*
|
|
59
|
+
* Outside `repos/` on purpose, and that is the whole collision argument: every
|
|
60
|
+
* repository walk — `listRepoIds`, the expiry sweep, the usage report — starts
|
|
61
|
+
* from `REPOS_PREFIX`, so nothing here can be mistaken for a repository, and
|
|
62
|
+
* no repository id can name a key here.
|
|
63
|
+
*/
|
|
64
|
+
export const UPLOAD_PACK_PREFIX = 'walgit/upload-pack-v2/'
|
|
65
|
+
|
|
66
|
+
/** The advertisement a container booted with this environment fingerprint published. */
|
|
67
|
+
export function uploadPackKey(fingerprint: string): string {
|
|
68
|
+
return `${UPLOAD_PACK_PREFIX}${fingerprint}.json`
|
|
69
|
+
}
|
|
70
|
+
|
|
54
71
|
/** Zero-padded to 12 digits so lexicographic key order is numeric order. */
|
|
55
72
|
export function walKey(repoId: string, seq: number, ulid: string, ext: 'pack' | 'idx'): string {
|
|
56
73
|
return `${walPrefix(repoId)}${String(seq).padStart(12, '0')}-${ulid}.${ext}`
|