@zabaca/zbc 0.21.0 → 0.22.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 +6 -1
- package/templates/apps/walgit/CONTEXT.md +25 -0
- package/templates/apps/walgit/README.md +152 -4
- package/templates/apps/walgit/e2e/harness.ts +2 -2
- package/templates/apps/walgit/e2e/scenarios.ts +302 -2
- package/templates/apps/walgit/shared/browse.ts +733 -0
- package/templates/apps/walgit/shared/capabilities.ts +17 -0
- package/templates/apps/walgit/shared/container-env.ts +9 -0
- package/templates/apps/walgit/shared/landing.ts +8 -27
- package/templates/apps/walgit/shared/llms.ts +25 -0
- package/templates/apps/walgit/shared/policy.ts +21 -0
- package/templates/apps/walgit/shared/pooled.ts +31 -0
- package/templates/apps/walgit/shared/protocol.ts +120 -0
- package/templates/apps/walgit/shared/repo-list.ts +478 -0
- package/templates/apps/walgit/shared/store.ts +307 -0
- package/templates/apps/walgit/shared/telemetry.ts +68 -6
- package/templates/apps/walgit/shared/wal-index.ts +249 -0
- package/templates/apps/walgit/shared/web.ts +46 -0
- package/templates/apps/walgit/src/announce-main.ts +1 -1
- package/templates/apps/walgit/src/announce.ts +1 -1
- package/templates/apps/walgit/src/append-only.ts +5 -8
- package/templates/apps/walgit/src/browse.ts +230 -0
- package/templates/apps/walgit/src/cache.ts +4 -4
- package/templates/apps/walgit/src/compact.ts +6 -12
- package/templates/apps/walgit/src/delete-repo.ts +4 -3
- package/templates/apps/walgit/src/expire.ts +3 -3
- package/templates/apps/walgit/src/gc.ts +4 -3
- package/templates/apps/walgit/src/git.ts +127 -10
- package/templates/apps/walgit/src/hook-main.ts +1 -1
- package/templates/apps/walgit/src/http.ts +386 -3
- package/templates/apps/walgit/src/limits.ts +1 -1
- package/templates/apps/walgit/src/materialize.bench.ts +4 -10
- package/templates/apps/walgit/src/materialize.ts +11 -4
- package/templates/apps/walgit/src/orphans.ts +3 -3
- package/templates/apps/walgit/src/pending.ts +1 -1
- package/templates/apps/walgit/src/private.ts +1 -1
- package/templates/apps/walgit/src/proposals.ts +3 -3
- package/templates/apps/walgit/src/push-cert.ts +10 -1
- package/templates/apps/walgit/src/push.ts +11 -9
- package/templates/apps/walgit/src/reconcile.ts +4 -3
- package/templates/apps/walgit/src/server.ts +29 -2
- package/templates/apps/walgit/src/signers.ts +9 -3
- package/templates/apps/walgit/src/store-env.ts +8 -21
- package/templates/apps/walgit/src/store.ts +12 -241
- package/templates/apps/walgit/src/sync.ts +2 -2
- package/templates/apps/walgit/src/usage.ts +4 -18
- package/templates/apps/walgit/src/verify.ts +2 -2
- package/templates/apps/walgit/src/wal-index.ts +20 -239
- package/templates/apps/walgit/worker/index.ts +232 -1
- package/templates/infra/modules/cloudflare-zone/index.ts +83 -9
- /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
- /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The object-store seam.
|
|
3
|
+
*
|
|
4
|
+
* Everything walgit persists goes through this interface, because the store is
|
|
5
|
+
* the source of truth and swapping it must not be a rewrite: R2 in production,
|
|
6
|
+
* an in-memory implementation in tests, S3/MinIO/Tigris for portability. See
|
|
7
|
+
* this repository's docs/adr/0007-walgit-object-storage-holds-the-log.md.
|
|
8
|
+
*
|
|
9
|
+
* It lives in the Shared Kernel because the bucket is not the container's
|
|
10
|
+
* private resource: the edge reads the same objects, and a second client would
|
|
11
|
+
* be a second set of rules about what a conditional write means (docs/adr/0010).
|
|
12
|
+
* `FileStore` is the one implementation that stays in `src/store.ts` — it is
|
|
13
|
+
* the local disk, which only the container has.
|
|
14
|
+
*
|
|
15
|
+
* The interface is deliberately narrow — five operations, exactly what the WAL
|
|
16
|
+
* needs. In particular it exposes CONDITIONAL writes as a first-class result
|
|
17
|
+
* rather than an exception, because losing a compare-and-swap is a normal
|
|
18
|
+
* outcome on the push path, not an error: two pushes raced and one has to be
|
|
19
|
+
* told to try again.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** A conditional precondition on a write. */
|
|
23
|
+
export type PutCondition =
|
|
24
|
+
/** Write only if the object's current ETag matches (compare-and-swap). */
|
|
25
|
+
| { ifMatch: string }
|
|
26
|
+
/** Write only if the object does not exist yet. */
|
|
27
|
+
| { ifAbsent: true }
|
|
28
|
+
|
|
29
|
+
export type PutResult =
|
|
30
|
+
| { ok: true; etag: string }
|
|
31
|
+
/** The precondition failed: someone else wrote first. Not an error. */
|
|
32
|
+
| { ok: false; reason: 'precondition-failed' }
|
|
33
|
+
|
|
34
|
+
export type GetResult = { body: Uint8Array; etag: string } | null
|
|
35
|
+
|
|
36
|
+
/** Result of a conditional read — the cheap "am I current?" check. */
|
|
37
|
+
export type ConditionalGetResult =
|
|
38
|
+
| { status: 'not-modified' }
|
|
39
|
+
| { status: 'ok'; body: Uint8Array; etag: string }
|
|
40
|
+
| { status: 'absent' }
|
|
41
|
+
|
|
42
|
+
export interface ObjectStore {
|
|
43
|
+
get(key: string): Promise<GetResult>
|
|
44
|
+
/**
|
|
45
|
+
* Read only if the caller's ETag is stale. A `not-modified` answer is a
|
|
46
|
+
* metadata-only round trip, which is what makes "is my cached repo current?"
|
|
47
|
+
* cheap enough to do on every request.
|
|
48
|
+
*/
|
|
49
|
+
getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult>
|
|
50
|
+
/** Unconditional when `condition` is omitted. */
|
|
51
|
+
put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult>
|
|
52
|
+
delete(key: string): Promise<void>
|
|
53
|
+
/** Keys under a prefix, lexicographically ascending. */
|
|
54
|
+
list(prefix: string): Promise<string[]>
|
|
55
|
+
/**
|
|
56
|
+
* Immediate child prefixes under `prefix`, delimited by `/`.
|
|
57
|
+
*
|
|
58
|
+
* Optional because it is an optimisation, not a capability: a store without
|
|
59
|
+
* it is enumerated by `list` and derivation (see `listRepoIds`). It exists
|
|
60
|
+
* because "which repositories exist?" is one question the bucket can answer
|
|
61
|
+
* in a handful of round trips, and answering it by listing every packfile in
|
|
62
|
+
* the log would make a read-only report the most expensive command walgit
|
|
63
|
+
* has.
|
|
64
|
+
*/
|
|
65
|
+
listPrefixes?(prefix: string): Promise<string[]>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ── In-memory implementation ────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* For tests. Faithful about the one property that matters: a conditional put
|
|
72
|
+
* evaluates its precondition and swaps atomically with respect to other
|
|
73
|
+
* in-flight puts.
|
|
74
|
+
*
|
|
75
|
+
* `yieldBeforeWrite` exists because JavaScript would otherwise make this test
|
|
76
|
+
* nothing. Without a suspension point between reading the current ETag and
|
|
77
|
+
* writing, every put runs to completion uninterrupted and a broken CAS
|
|
78
|
+
* implementation would still pass. The hook forces the interleaving that a real
|
|
79
|
+
* network round trip would produce.
|
|
80
|
+
*/
|
|
81
|
+
export class MemoryStore implements ObjectStore {
|
|
82
|
+
private objects = new Map<string, { body: Uint8Array; etag: string }>()
|
|
83
|
+
private counter = 0
|
|
84
|
+
|
|
85
|
+
constructor(private readonly yieldBeforeWrite: () => Promise<void> = async () => {}) {}
|
|
86
|
+
|
|
87
|
+
private nextEtag(): string {
|
|
88
|
+
this.counter += 1
|
|
89
|
+
return `"mem-${this.counter}"`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async get(key: string): Promise<GetResult> {
|
|
93
|
+
const found = this.objects.get(key)
|
|
94
|
+
return found ? { body: found.body, etag: found.etag } : null
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
|
|
98
|
+
const found = this.objects.get(key)
|
|
99
|
+
if (!found) return { status: 'absent' }
|
|
100
|
+
if (found.etag === etag) return { status: 'not-modified' }
|
|
101
|
+
return { status: 'ok', body: found.body, etag: found.etag }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
|
|
105
|
+
// Read the precondition's subject, then suspend — this is the window a
|
|
106
|
+
// real store has, and the window a wrong implementation loses data in.
|
|
107
|
+
const before = this.objects.get(key)
|
|
108
|
+
await this.yieldBeforeWrite()
|
|
109
|
+
|
|
110
|
+
// Re-read after the suspension: the check and the swap must both see the
|
|
111
|
+
// same state, which is the whole contract being modelled.
|
|
112
|
+
const current = this.objects.get(key)
|
|
113
|
+
if (condition) {
|
|
114
|
+
if ('ifAbsent' in condition && current) return { ok: false, reason: 'precondition-failed' }
|
|
115
|
+
if ('ifMatch' in condition && current?.etag !== condition.ifMatch) {
|
|
116
|
+
return { ok: false, reason: 'precondition-failed' }
|
|
117
|
+
}
|
|
118
|
+
// A racing writer that landed during the suspension invalidates a
|
|
119
|
+
// precondition that was true when we started.
|
|
120
|
+
if (current?.etag !== before?.etag) return { ok: false, reason: 'precondition-failed' }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const etag = this.nextEtag()
|
|
124
|
+
this.objects.set(key, { body, etag })
|
|
125
|
+
return { ok: true, etag }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async delete(key: string): Promise<void> {
|
|
129
|
+
this.objects.delete(key)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async list(prefix: string): Promise<string[]> {
|
|
133
|
+
return [...this.objects.keys()].filter((k) => k.startsWith(prefix)).sort()
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── S3-compatible implementation (R2, S3, MinIO, Tigris) ────────────────────
|
|
138
|
+
|
|
139
|
+
export interface S3StoreOptions {
|
|
140
|
+
/** e.g. `https://<account>.r2.cloudflarestorage.com` */
|
|
141
|
+
endpoint: string
|
|
142
|
+
bucket: string
|
|
143
|
+
/** Signs each request. `aws4fetch`'s `AwsClient.fetch` satisfies this. */
|
|
144
|
+
fetch: (input: string, init?: RequestInit) => Promise<Response>
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Conditional writes were verified against R2 on 2026-08-20 — 16 concurrent
|
|
149
|
+
* writers against one ETag produced exactly one 200 and fifteen 412s, with no
|
|
150
|
+
* torn writes. See docs/research/walgit-m0-spike/.
|
|
151
|
+
*
|
|
152
|
+
* Portability caveat worth carrying: Tigris honours the same headers but only
|
|
153
|
+
* evaluates them safely on Multi-region or Single-region buckets. Its Global
|
|
154
|
+
* and Dual-region types are strong same-region and eventual cross-region, and a
|
|
155
|
+
* sub-second replication window is exactly wide enough to lose a push race and
|
|
156
|
+
* never reproduce it.
|
|
157
|
+
*/
|
|
158
|
+
export class S3Store implements ObjectStore {
|
|
159
|
+
constructor(private readonly opts: S3StoreOptions) {}
|
|
160
|
+
|
|
161
|
+
private url(key: string): string {
|
|
162
|
+
return `${this.opts.endpoint}/${this.opts.bucket}/${key}`
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async get(key: string): Promise<GetResult> {
|
|
166
|
+
const res = await this.opts.fetch(this.url(key))
|
|
167
|
+
if (res.status === 404) return null
|
|
168
|
+
if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
|
|
169
|
+
return { body: new Uint8Array(await res.arrayBuffer()), etag: res.headers.get('etag') ?? '' }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
|
|
173
|
+
const res = await this.opts.fetch(this.url(key), { headers: { 'If-None-Match': etag } })
|
|
174
|
+
if (res.status === 304) return { status: 'not-modified' }
|
|
175
|
+
if (res.status === 404) return { status: 'absent' }
|
|
176
|
+
if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
|
|
177
|
+
return {
|
|
178
|
+
status: 'ok',
|
|
179
|
+
body: new Uint8Array(await res.arrayBuffer()),
|
|
180
|
+
etag: res.headers.get('etag') ?? '',
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
|
|
185
|
+
const headers: Record<string, string> = {}
|
|
186
|
+
if (condition && 'ifMatch' in condition) headers['If-Match'] = condition.ifMatch
|
|
187
|
+
if (condition && 'ifAbsent' in condition) headers['If-None-Match'] = '*'
|
|
188
|
+
|
|
189
|
+
// `Uint8Array` is a valid BodyInit at runtime; the cast is only to bridge
|
|
190
|
+
// TS 5.7's `Uint8Array<ArrayBufferLike>` against lib.dom's narrower
|
|
191
|
+
// `BodyInit`, which does not accept the generic form.
|
|
192
|
+
const res = await this.opts.fetch(this.url(key), {
|
|
193
|
+
method: 'PUT',
|
|
194
|
+
body: body as unknown as BodyInit,
|
|
195
|
+
headers,
|
|
196
|
+
})
|
|
197
|
+
// 412 is the documented precondition failure. 409 is included because
|
|
198
|
+
// S3-compatible stores have historically used it for the same condition
|
|
199
|
+
// under concurrent load; treating it as an error would surface a normal
|
|
200
|
+
// race as an outage.
|
|
201
|
+
if (res.status === 412 || res.status === 409)
|
|
202
|
+
return { ok: false, reason: 'precondition-failed' }
|
|
203
|
+
if (!res.ok) throw new Error(`PUT ${key}: HTTP ${res.status}`)
|
|
204
|
+
return { ok: true, etag: res.headers.get('etag') ?? '' }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async delete(key: string): Promise<void> {
|
|
208
|
+
const res = await this.opts.fetch(this.url(key), { method: 'DELETE' })
|
|
209
|
+
if (!res.ok && res.status !== 404) throw new Error(`DELETE ${key}: HTTP ${res.status}`)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async list(prefix: string): Promise<string[]> {
|
|
213
|
+
const keys: string[] = []
|
|
214
|
+
let token: string | undefined
|
|
215
|
+
do {
|
|
216
|
+
const params = new URLSearchParams({ 'list-type': '2', prefix })
|
|
217
|
+
if (token) params.set('continuation-token', token)
|
|
218
|
+
const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
|
|
219
|
+
if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
|
|
220
|
+
const xml = await res.text()
|
|
221
|
+
for (const m of xml.matchAll(/<Key>([^<]+)<\/Key>/g)) keys.push(m[1]!)
|
|
222
|
+
token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
|
|
223
|
+
} while (token)
|
|
224
|
+
return keys.sort()
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* `delimiter=/` makes the store roll every key sharing a child prefix into a
|
|
229
|
+
* single `CommonPrefixes` entry, so a bucket holding a million WAL objects
|
|
230
|
+
* still answers "which repositories are there?" in one page per thousand
|
|
231
|
+
* repositories.
|
|
232
|
+
*/
|
|
233
|
+
async listPrefixes(prefix: string): Promise<string[]> {
|
|
234
|
+
const prefixes: string[] = []
|
|
235
|
+
let token: string | undefined
|
|
236
|
+
do {
|
|
237
|
+
const params = new URLSearchParams({ 'list-type': '2', prefix, delimiter: '/' })
|
|
238
|
+
if (token) params.set('continuation-token', token)
|
|
239
|
+
const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
|
|
240
|
+
if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
|
|
241
|
+
const xml = await res.text()
|
|
242
|
+
for (const block of xml.matchAll(/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g)) {
|
|
243
|
+
const found = /<Prefix>([^<]+)<\/Prefix>/.exec(block[1]!)
|
|
244
|
+
if (found) prefixes.push(found[1]!)
|
|
245
|
+
}
|
|
246
|
+
token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
|
|
247
|
+
} while (token)
|
|
248
|
+
return prefixes.sort()
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The S3 half of "build the store from the environment".
|
|
254
|
+
*
|
|
255
|
+
* Both halves need it and neither may own it: the container reads it out of
|
|
256
|
+
* `process.env` (`src/store-env.ts`, which also has the `WALGIT_STORE_DIR`
|
|
257
|
+
* disk branch only it can serve), and the Worker reads it off a binding object
|
|
258
|
+
* to answer the web view at the edge (`worker/index.ts`). It was written twice,
|
|
259
|
+
* including the one comment that is genuinely hard-won — R2 ignores the region
|
|
260
|
+
* but SigV4 does not, and an absent one signs differently and 403s with nothing
|
|
261
|
+
* useful in the body (docs/adr/0010).
|
|
262
|
+
*
|
|
263
|
+
* `null` means "not configured", which the two halves read differently on
|
|
264
|
+
* purpose: the push path treats it as fatal (there is nowhere to persist to, so
|
|
265
|
+
* nothing may be acknowledged) while a read path treats it as "there is no log
|
|
266
|
+
* to read".
|
|
267
|
+
*
|
|
268
|
+
* The signer is injected rather than imported so this module keeps importing no
|
|
269
|
+
* runtime — `aws4fetch`'s `AwsClient` is fetch-based and works in both halves,
|
|
270
|
+
* but the dependency belongs to the caller that has one.
|
|
271
|
+
*/
|
|
272
|
+
export function s3StoreFrom(
|
|
273
|
+
env: {
|
|
274
|
+
WALGIT_S3_ENDPOINT?: string | undefined
|
|
275
|
+
WALGIT_S3_BUCKET?: string | undefined
|
|
276
|
+
WALGIT_S3_ACCESS_KEY_ID?: string | undefined
|
|
277
|
+
WALGIT_S3_SECRET_ACCESS_KEY?: string | undefined
|
|
278
|
+
WALGIT_S3_REGION?: string | undefined
|
|
279
|
+
},
|
|
280
|
+
/** Builds a request signer for these credentials — `new AwsClient({…})`. */
|
|
281
|
+
signer: (credentials: {
|
|
282
|
+
accessKeyId: string
|
|
283
|
+
secretAccessKey: string
|
|
284
|
+
service: 's3'
|
|
285
|
+
region: string
|
|
286
|
+
}) => { fetch: (input: string, init?: RequestInit) => Promise<Response> },
|
|
287
|
+
): ObjectStore | null {
|
|
288
|
+
const endpoint = env.WALGIT_S3_ENDPOINT
|
|
289
|
+
const bucket = env.WALGIT_S3_BUCKET
|
|
290
|
+
const accessKeyId = env.WALGIT_S3_ACCESS_KEY_ID
|
|
291
|
+
const secretAccessKey = env.WALGIT_S3_SECRET_ACCESS_KEY
|
|
292
|
+
if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) return null
|
|
293
|
+
|
|
294
|
+
const client = signer({
|
|
295
|
+
accessKeyId,
|
|
296
|
+
secretAccessKey,
|
|
297
|
+
service: 's3',
|
|
298
|
+
// R2 ignores the region but the SigV4 signature does not: an absent region
|
|
299
|
+
// signs differently and every request 403s with nothing useful in the body.
|
|
300
|
+
region: env.WALGIT_S3_REGION ?? 'auto',
|
|
301
|
+
})
|
|
302
|
+
return new S3Store({
|
|
303
|
+
endpoint: endpoint.replace(/\/$/, ''),
|
|
304
|
+
bucket,
|
|
305
|
+
fetch: (input, init) => client.fetch(input, init),
|
|
306
|
+
})
|
|
307
|
+
}
|
|
@@ -29,9 +29,11 @@ import {
|
|
|
29
29
|
PROVENANCE_PATH,
|
|
30
30
|
REJECT_HEADER,
|
|
31
31
|
REPO_ID,
|
|
32
|
+
REPOS_PATH,
|
|
32
33
|
SERVED_HEADER,
|
|
33
34
|
SMART_HTTP,
|
|
34
35
|
normalizeReject,
|
|
36
|
+
wantsBrowse,
|
|
35
37
|
type RejectKind,
|
|
36
38
|
} from './protocol'
|
|
37
39
|
|
|
@@ -66,6 +68,23 @@ export type RequestKind =
|
|
|
66
68
|
// bucket and these are requests walgit now answers — and because the count
|
|
67
69
|
// is the measure of what the route absorbed.
|
|
68
70
|
| 'favicon'
|
|
71
|
+
// The repository list (`shared/repo-list.ts`), answered at the edge off the
|
|
72
|
+
// log. Its own kind for the reason `mcp` and `provenance` are — `other` is
|
|
73
|
+
// the unroutable bucket and this is a request walgit answers — and counted
|
|
74
|
+
// separately from `landing` because the two measure different things: the
|
|
75
|
+
// page is what a stranger reads, the list is what somebody who has decided
|
|
76
|
+
// to look around reads. It is recorded even on a deployment with the
|
|
77
|
+
// capability off, where the path falls through to a container that does not
|
|
78
|
+
// route it: the row is then a 404, which is the honest reading and a useful
|
|
79
|
+
// one (it is demand for a switch nobody has flipped).
|
|
80
|
+
| 'list'
|
|
81
|
+
// One of the two repository pages (`shared/browse.ts`). Its own kind for the
|
|
82
|
+
// reason `list` is — `other` is the unroutable bucket and this is a request
|
|
83
|
+
// walgit answers — and, unlike the list, it NAMES a repository, because it is
|
|
84
|
+
// about exactly one. It is recorded even on a deployment with the capability
|
|
85
|
+
// off, where the path falls through to a container that does not route it:
|
|
86
|
+
// the row is then a 404, which is the honest reading and a useful one.
|
|
87
|
+
| 'browse'
|
|
69
88
|
| 'health'
|
|
70
89
|
// Someone asking who pushed (docs/adr/0011). Its own kind rather than
|
|
71
90
|
// `other`, because `other` is the unroutable bucket and a provenance read is
|
|
@@ -154,6 +173,8 @@ export function classifyRequest(method: string, pathname: string, search: string
|
|
|
154
173
|
// No repository: the name a tool acts on travels in the JSON-RPC body, and
|
|
155
174
|
// the body is not something this function reads (see `RequestKind`).
|
|
156
175
|
if (pathname === MCP_PATH) return { kind: 'mcp', repo: '' }
|
|
176
|
+
// No repository: the list is about all of them.
|
|
177
|
+
if (pathname === REPOS_PATH) return { kind: 'list', repo: '' }
|
|
157
178
|
if (pathname === '/' && (method === 'GET' || method === 'HEAD')) {
|
|
158
179
|
return { kind: 'instructions', repo: '' }
|
|
159
180
|
}
|
|
@@ -170,7 +191,25 @@ export function classifyRequest(method: string, pathname: string, search: string
|
|
|
170
191
|
}
|
|
171
192
|
|
|
172
193
|
const route = SMART_HTTP.exec(pathname)
|
|
173
|
-
if (!route)
|
|
194
|
+
if (!route) {
|
|
195
|
+
// `/<name>` and `/<name>/tree/…` — read through the same `wantsBrowse` the
|
|
196
|
+
// edge routes on (`shared/protocol.ts`), so a path one claimed and the
|
|
197
|
+
// other did not cannot become a metric describing traffic that never
|
|
198
|
+
// happened. Below `SMART_HTTP` because a clone URL is not a browse URL and
|
|
199
|
+
// the git grammar is the one that must win.
|
|
200
|
+
//
|
|
201
|
+
// A path whose SHAPE already has a name keeps it. `/wp-login.php` and
|
|
202
|
+
// `/.env` are repository-shaped — a repository may be called `wp-login.php`
|
|
203
|
+
// — but they are the scanner baseline those buckets exist to measure, and
|
|
204
|
+
// counting them as people reading a repository page would put the noise
|
|
205
|
+
// into the one number a launch is read by. The edge still routes them: a
|
|
206
|
+
// browse of a name the log has no Index for is a 404 either way.
|
|
207
|
+
const bucket = otherBucket(pathname)
|
|
208
|
+
const browse =
|
|
209
|
+
bucket === 'bare-name' || bucket === 'else' ? wantsBrowse(method, pathname) : null
|
|
210
|
+
if (browse) return { kind: 'browse', repo: browse.repo }
|
|
211
|
+
return { kind: 'other', repo: '', bucket }
|
|
212
|
+
}
|
|
174
213
|
const repo = route[1]!
|
|
175
214
|
|
|
176
215
|
if (route[2] === 'git-upload-pack') return { kind: 'clone', repo }
|
|
@@ -201,14 +240,37 @@ export function classifyOutcome(
|
|
|
201
240
|
status: number,
|
|
202
241
|
headers: { get(name: string): string | null },
|
|
203
242
|
): { outcome: Outcome; reject: RejectKind | '' } {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
243
|
+
return outcomeOf({
|
|
244
|
+
status,
|
|
245
|
+
declared: headers.get(REJECT_HEADER),
|
|
246
|
+
served: headers.get(SERVED_HEADER) !== null,
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* The same judgement, from the two facts rather than from a `Headers`.
|
|
252
|
+
*
|
|
253
|
+
* Some callers have already read the stamps into values — the browse page
|
|
254
|
+
* carries them back from the container as `{ served, reject }`
|
|
255
|
+
* (`shared/browse.ts`), because `shared/` has no `Headers` to hand around. They
|
|
256
|
+
* ask this directly rather than building a stand-in object for the reader
|
|
257
|
+
* above to take apart again.
|
|
258
|
+
*/
|
|
259
|
+
export function outcomeOf(answer: {
|
|
260
|
+
status: number
|
|
261
|
+
/** `REJECT_HEADER`'s value, or `null`/`''` where the layer named no kind. */
|
|
262
|
+
declared: string | null
|
|
263
|
+
/** The container stamped it (`SERVED_HEADER`). */
|
|
264
|
+
served: boolean
|
|
265
|
+
}): { outcome: Outcome; reject: RejectKind | '' } {
|
|
266
|
+
if (answer.declared) return { outcome: 'reject', reject: normalizeReject(answer.declared) }
|
|
267
|
+
if (answer.status < 400) return { outcome: 'ok', reject: '' }
|
|
268
|
+
if (!answer.served) return { outcome: 'reject', reject: 'edge' }
|
|
269
|
+
return { outcome: 'reject', reject: fromStatus(answer.status) }
|
|
209
270
|
}
|
|
210
271
|
|
|
211
272
|
function fromStatus(status: number): RejectKind {
|
|
273
|
+
if (status === 400) return 'invalid'
|
|
212
274
|
if (status === 401 || status === 403) return 'unauthorized'
|
|
213
275
|
if (status === 404) return 'not-found'
|
|
214
276
|
if (status === 409) return 'collision'
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `index.json` — the source of truth for one repository, and how to READ it.
|
|
3
|
+
*
|
|
4
|
+
* It carries the full ref state, so there is no database beside it. A push is
|
|
5
|
+
* published by writing a new version of this object under a compare-and-swap;
|
|
6
|
+
* until that write lands, the packfile already uploaded to the WAL is present
|
|
7
|
+
* but unpublished, and nothing can see it.
|
|
8
|
+
*
|
|
9
|
+
* The Index’s types and its reader live in the Shared Kernel because reading
|
|
10
|
+
* the log is not a container privilege: the edge answers questions off
|
|
11
|
+
* `index.json` too, and the answer must be the same object model on both sides
|
|
12
|
+
* (docs/adr/0010). Writing it is not here — `src/wal-index.ts` owns the
|
|
13
|
+
* compare-and-swap, the `apply*` helpers and `sha256`, all of which belong to
|
|
14
|
+
* the process that holds the disk.
|
|
15
|
+
*
|
|
16
|
+
* See this repository’s docs/adr/0007-walgit-object-storage-holds-the-log.md.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { indexKey } from './keys'
|
|
20
|
+
import type { ObjectStore } from './store'
|
|
21
|
+
|
|
22
|
+
export type WalEntryKind = 'push' | 'compaction'
|
|
23
|
+
|
|
24
|
+
export interface WalEntry {
|
|
25
|
+
seq: number
|
|
26
|
+
/** Object key of the packfile, e.g. `wal/000000000042-01J….pack`. */
|
|
27
|
+
key: string
|
|
28
|
+
kind: WalEntryKind
|
|
29
|
+
size: number
|
|
30
|
+
sha256: string
|
|
31
|
+
ts: string
|
|
32
|
+
/** Compaction only: entries at or below this seq are no longer needed. */
|
|
33
|
+
supersedes_through?: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A superseded WAL object, scheduled for deletion but not yet deleted.
|
|
38
|
+
*
|
|
39
|
+
* The delay is the whole point. A compaction's compare-and-swap advances the
|
|
40
|
+
* frontier instantly, but a restore that read `index.json` a moment earlier is
|
|
41
|
+
* still downloading the entries that CAS just superseded — and deleting them
|
|
42
|
+
* out from under it fails the restore with a missing object, which is ranked
|
|
43
|
+
* risk #2 in docs/adr/0007 precisely because nothing shouts. So the CAS records
|
|
44
|
+
* an intent to delete, and collection happens later, out of band.
|
|
45
|
+
*/
|
|
46
|
+
export interface Tombstone {
|
|
47
|
+
/** The object key. Its sibling `.idx` is collected with it. */
|
|
48
|
+
key: string
|
|
49
|
+
/** The compaction entry whose pack now contains these objects. */
|
|
50
|
+
superseded_by: number
|
|
51
|
+
/** ISO instant before which this key must not be deleted. */
|
|
52
|
+
collect_after: string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A repository scheduled for deletion.
|
|
57
|
+
*
|
|
58
|
+
* Deletion is deferred for the same reason a tombstone is: a clone that read
|
|
59
|
+
* this index a moment ago is still downloading the packs it names, and pulling
|
|
60
|
+
* them out from under it fails the clone with a missing object. The marker is
|
|
61
|
+
* written under compare-and-swap like everything else, so an operator asking
|
|
62
|
+
* twice does not shorten the wait — the first request's `collect_after` stands.
|
|
63
|
+
*/
|
|
64
|
+
export interface RepoDeletion {
|
|
65
|
+
/** ISO instant the operator asked for the repository to go. */
|
|
66
|
+
requested_at: string
|
|
67
|
+
/** ISO instant before which nothing under the repo prefix may be deleted. */
|
|
68
|
+
collect_after: string
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface WalIndex {
|
|
72
|
+
version: 1
|
|
73
|
+
repo_id: string
|
|
74
|
+
/** Highest WAL entry applied. Monotonic. */
|
|
75
|
+
seq: number
|
|
76
|
+
entries: WalEntry[]
|
|
77
|
+
/** Full ref state after applying every entry. `refs/heads/main` → oid. */
|
|
78
|
+
refs: Record<string, string>
|
|
79
|
+
/** Entries below this are not needed to restore. */
|
|
80
|
+
compaction_frontier: number
|
|
81
|
+
/**
|
|
82
|
+
* Superseded keys awaiting collection. Optional because an index written
|
|
83
|
+
* before compaction existed does not have the field; absent reads as empty.
|
|
84
|
+
*/
|
|
85
|
+
tombstones?: Tombstone[]
|
|
86
|
+
/**
|
|
87
|
+
* Set when this repository has been scheduled for deletion. Its presence is
|
|
88
|
+
* what makes the second run of `walgit delete` a collection rather than a
|
|
89
|
+
* second request.
|
|
90
|
+
*/
|
|
91
|
+
deletion?: RepoDeletion
|
|
92
|
+
/**
|
|
93
|
+
* Push provenance: ref → who signed the push that moved it to the sha `refs`
|
|
94
|
+
* currently holds, and when (docs/adr/0011).
|
|
95
|
+
*
|
|
96
|
+
* A second map beside `refs` rather than a widening of it, for three reasons
|
|
97
|
+
* that each rule out the alternatives. It is not hung off a `WalEntry`: a
|
|
98
|
+
* ref-only push appends none, so provenance would be blind to a whole class
|
|
99
|
+
* of push. It is not kept on the certificate blob: that lives on the Cache,
|
|
100
|
+
* which is wiped on restart. And it is not a richer value inside `refs`,
|
|
101
|
+
* because every existing reader of the Index — reconcile, materialize, the
|
|
102
|
+
* event handshake — would then have to change to keep reading a sha.
|
|
103
|
+
*
|
|
104
|
+
* Latest-state per ref, like everything else here: there is no provenance
|
|
105
|
+
* history, because the audit trail of *content* is the commit graph and a
|
|
106
|
+
* second ledger would be a second thing to keep true.
|
|
107
|
+
*
|
|
108
|
+
* Optional and absent when empty, so an unsigned deployment's index.json is
|
|
109
|
+
* byte-for-byte what it was before this field existed.
|
|
110
|
+
*/
|
|
111
|
+
provenance?: Record<string, Provenance>
|
|
112
|
+
/**
|
|
113
|
+
* The repository's Signer List, as the push that last moved `refs/walgit/signers`
|
|
114
|
+
* resolved it (docs/adr/0012). Absent means unclaimed, which is every
|
|
115
|
+
* repository until someone writes one.
|
|
116
|
+
*
|
|
117
|
+
* Repo-level rather than per-ref, unlike `provenance` above it: the list
|
|
118
|
+
* governs the name, not a branch.
|
|
119
|
+
*
|
|
120
|
+
* The ref is authoritative and this is a derived copy, which is safe rather
|
|
121
|
+
* than a second source of truth — it is written by the same compare-and-swap
|
|
122
|
+
* that publishes the ref move, derived from bytes in that same push, and a
|
|
123
|
+
* restore replays the ref and this field together because both live here. The
|
|
124
|
+
* copy exists because the refusal that will read it runs in `pre-receive`,
|
|
125
|
+
* which already loads the Index; resolving from the Cache instead would make
|
|
126
|
+
* ownership depend on the Cache being materialized, and the Cache is
|
|
127
|
+
* disposable by definition (ADR-0007).
|
|
128
|
+
*
|
|
129
|
+
* It cannot be derived from `provenance`, which is latest-state per ref and
|
|
130
|
+
* overwritten by every push — by the time it mattered it would name the most
|
|
131
|
+
* recent Signer rather than the founding one.
|
|
132
|
+
*/
|
|
133
|
+
claim?: Claim
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Who moved a ref, and when it landed. */
|
|
137
|
+
export interface Provenance {
|
|
138
|
+
/**
|
|
139
|
+
* The SSH key fingerprint that signed the push, as `ssh-keygen` spells it:
|
|
140
|
+
* `SHA256:` and 43 characters of base64. A key, never a user or an account —
|
|
141
|
+
* neither exists here, and naming it either would imply a registry walgit
|
|
142
|
+
* deliberately does not have.
|
|
143
|
+
*/
|
|
144
|
+
signer: string
|
|
145
|
+
/** ISO instant the push was received. */
|
|
146
|
+
ts: string
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The keys a repository's Signer List names, and when that list landed. */
|
|
150
|
+
export interface Claim {
|
|
151
|
+
/**
|
|
152
|
+
* Fingerprints, in the order the file names them and with duplicates already
|
|
153
|
+
* collapsed — the list as `parseKeyList` read it, never the raw file. What
|
|
154
|
+
* is stored is the resolved answer, so a reader never re-parses and cannot
|
|
155
|
+
* reach a different one.
|
|
156
|
+
*/
|
|
157
|
+
signers: string[]
|
|
158
|
+
/**
|
|
159
|
+
* The keys the repository lets READ it — its Reader List (docs/adr/0013) —
|
|
160
|
+
* as `parseKeyList` read the `readers` file beside `signers` in the same
|
|
161
|
+
* commit. Absent when that file is absent, which is every repository until
|
|
162
|
+
* someone writes one: presence is the switch, so there is no `private`
|
|
163
|
+
* marker and no third state.
|
|
164
|
+
*
|
|
165
|
+
* `[]` is a value rather than an absence, and the difference is the whole
|
|
166
|
+
* capability: an empty Reader List is valid and means the Signer List reads
|
|
167
|
+
* this repository and nobody else, while no field at all means anyone does.
|
|
168
|
+
*
|
|
169
|
+
* Maintained only while the Private seed is set, exactly as the Claim around
|
|
170
|
+
* it is maintained only under the Signer List flag — the ref is what is
|
|
171
|
+
* authoritative and this is a derived copy (see `applyClaim`).
|
|
172
|
+
*/
|
|
173
|
+
readers?: string[]
|
|
174
|
+
/** ISO instant the push that wrote this list was received. */
|
|
175
|
+
ts: string
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* What one push records about who made it — applied by the same compare-and-swap
|
|
180
|
+
* that publishes the push, which is why they travel together rather than as two
|
|
181
|
+
* nullable tail arguments nobody can keep straight at a call site.
|
|
182
|
+
*/
|
|
183
|
+
export interface PushRecord {
|
|
184
|
+
/** The Signer of this push, or `null` for an anonymous one. */
|
|
185
|
+
provenance: Provenance | null
|
|
186
|
+
/** The Signer List this push writes, or `null` when it writes none. */
|
|
187
|
+
claim: Claim | null
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A ref change as `reference-transaction` reports it on stdin. */
|
|
191
|
+
export interface RefChange {
|
|
192
|
+
ref: string
|
|
193
|
+
oldOid: string
|
|
194
|
+
newOid: string
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function emptyIndex(repoId: string): WalIndex {
|
|
198
|
+
return {
|
|
199
|
+
version: 1,
|
|
200
|
+
repo_id: repoId,
|
|
201
|
+
seq: 0,
|
|
202
|
+
entries: [],
|
|
203
|
+
refs: {},
|
|
204
|
+
compaction_frontier: 0,
|
|
205
|
+
tombstones: [],
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ── Reading ─────────────────────────────────────────────────────────────────
|
|
210
|
+
|
|
211
|
+
export interface LoadedIndex {
|
|
212
|
+
index: WalIndex
|
|
213
|
+
/** ETag to guard the next write with. `null` when the object does not exist. */
|
|
214
|
+
etag: string | null
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export async function loadIndex(store: ObjectStore, repoId: string): Promise<LoadedIndex> {
|
|
218
|
+
const found = await store.get(indexKey(repoId))
|
|
219
|
+
if (!found) return { index: emptyIndex(repoId), etag: null }
|
|
220
|
+
return { index: parseIndex(found.body, repoId), etag: found.etag }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Cheap currency check for the read path: `not-modified` costs one metadata
|
|
225
|
+
* round trip, which is what lets a node serve from its local cache without
|
|
226
|
+
* trusting it blindly.
|
|
227
|
+
*/
|
|
228
|
+
export async function loadIndexIfChanged(
|
|
229
|
+
store: ObjectStore,
|
|
230
|
+
repoId: string,
|
|
231
|
+
knownEtag: string,
|
|
232
|
+
): Promise<LoadedIndex | 'current'> {
|
|
233
|
+
const res = await store.getIfNoneMatch(indexKey(repoId), knownEtag)
|
|
234
|
+
if (res.status === 'not-modified') return 'current'
|
|
235
|
+
if (res.status === 'absent') return { index: emptyIndex(repoId), etag: null }
|
|
236
|
+
return { index: parseIndex(res.body, repoId), etag: res.etag }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function parseIndex(body: Uint8Array, repoId: string): WalIndex {
|
|
240
|
+
const parsed = JSON.parse(new TextDecoder().decode(body)) as WalIndex
|
|
241
|
+
// Guard the two invariants a corrupted or misrouted object would break. A
|
|
242
|
+
// wrong repo_id means the key routing is wrong, which silently serving would
|
|
243
|
+
// turn into cross-repository data loss.
|
|
244
|
+
if (parsed.version !== 1) throw new Error(`index.json: unsupported version ${parsed.version}`)
|
|
245
|
+
if (parsed.repo_id !== repoId) {
|
|
246
|
+
throw new Error(`index.json at ${repoId} declares repo_id "${parsed.repo_id}"`)
|
|
247
|
+
}
|
|
248
|
+
return parsed
|
|
249
|
+
}
|