@zabaca/zbc 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/templates/apps/walgit/CONTEXT.md +37 -0
  3. package/templates/apps/walgit/README.md +193 -4
  4. package/templates/apps/walgit/e2e/harness.ts +2 -2
  5. package/templates/apps/walgit/e2e/scenarios.ts +302 -2
  6. package/templates/apps/walgit/package.json +5 -1
  7. package/templates/apps/walgit/registry.json +1 -1
  8. package/templates/apps/walgit/shared/browse.ts +733 -0
  9. package/templates/apps/walgit/shared/capabilities.ts +17 -0
  10. package/templates/apps/walgit/shared/container-env.ts +9 -0
  11. package/templates/apps/walgit/shared/landing.ts +8 -27
  12. package/templates/apps/walgit/shared/llms.ts +41 -0
  13. package/templates/apps/walgit/shared/mcp.ts +286 -0
  14. package/templates/apps/walgit/shared/policy.ts +21 -0
  15. package/templates/apps/walgit/shared/pooled.ts +31 -0
  16. package/templates/apps/walgit/shared/protocol.ts +140 -0
  17. package/templates/apps/walgit/shared/repo-list.ts +478 -0
  18. package/templates/apps/walgit/shared/store.ts +307 -0
  19. package/templates/apps/walgit/shared/telemetry.ts +79 -6
  20. package/templates/apps/walgit/shared/wal-index.ts +249 -0
  21. package/templates/apps/walgit/shared/web.ts +46 -0
  22. package/templates/apps/walgit/src/announce-main.ts +1 -1
  23. package/templates/apps/walgit/src/announce.ts +1 -1
  24. package/templates/apps/walgit/src/append-only.ts +5 -8
  25. package/templates/apps/walgit/src/browse.ts +230 -0
  26. package/templates/apps/walgit/src/cache.ts +4 -4
  27. package/templates/apps/walgit/src/compact.ts +6 -12
  28. package/templates/apps/walgit/src/delete-repo.ts +4 -3
  29. package/templates/apps/walgit/src/expire.ts +3 -3
  30. package/templates/apps/walgit/src/gc.ts +4 -3
  31. package/templates/apps/walgit/src/git.ts +127 -10
  32. package/templates/apps/walgit/src/hook-main.ts +1 -1
  33. package/templates/apps/walgit/src/http.ts +386 -3
  34. package/templates/apps/walgit/src/limits.ts +1 -1
  35. package/templates/apps/walgit/src/materialize.bench.ts +4 -10
  36. package/templates/apps/walgit/src/materialize.ts +11 -4
  37. package/templates/apps/walgit/src/orphans.ts +3 -3
  38. package/templates/apps/walgit/src/pending.ts +1 -1
  39. package/templates/apps/walgit/src/private.ts +1 -1
  40. package/templates/apps/walgit/src/proposals.ts +3 -3
  41. package/templates/apps/walgit/src/push-cert.ts +10 -1
  42. package/templates/apps/walgit/src/push.ts +11 -9
  43. package/templates/apps/walgit/src/reconcile.ts +4 -3
  44. package/templates/apps/walgit/src/server.ts +29 -2
  45. package/templates/apps/walgit/src/signers.ts +9 -3
  46. package/templates/apps/walgit/src/store-env.ts +8 -21
  47. package/templates/apps/walgit/src/store.ts +12 -241
  48. package/templates/apps/walgit/src/sync.ts +2 -2
  49. package/templates/apps/walgit/src/usage.ts +4 -18
  50. package/templates/apps/walgit/src/verify.ts +2 -2
  51. package/templates/apps/walgit/src/wal-index.ts +20 -239
  52. package/templates/apps/walgit/worker/index.ts +278 -1
  53. package/templates/apps/walgit/worker/mcp.ts +281 -0
  54. /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
  55. /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
@@ -38,12 +38,13 @@ import * as path from 'node:path'
38
38
 
39
39
  import { ensureBareRepo } from './cache'
40
40
  import { git } from './git'
41
- import { siblingIdx } from './keys'
41
+ import { siblingIdx } from '../shared/keys'
42
42
  import { acquireLock, type LockRelease } from './mkdir-lock'
43
43
  import { reconcile, type ReconcileResult } from './reconcile'
44
44
  import type { ResolvedRepo } from './repo'
45
- import type { ObjectStore } from './store'
46
- import { loadIndex, sha256, type WalEntry, type WalIndex } from './wal-index'
45
+ import type { ObjectStore } from '../shared/store'
46
+ import { loadIndex, type WalEntry, type WalIndex } from '../shared/wal-index'
47
+ import { sha256 } from './wal-index'
47
48
 
48
49
  /**
49
50
  * Removed only when a materialize completes. Its presence means a previous
@@ -233,7 +234,13 @@ async function placeEntry(store: ObjectStore, packDir: string, entry: WalEntry):
233
234
  } else {
234
235
  // Only when the log predates uploading the index, or the sibling was lost.
235
236
  // It is the expensive path the `.idx` upload exists to avoid, so it says so.
236
- const built = git(['index-pack', `${base}.pack`])
237
+ // `index-pack` is one of the few git commands that parses its own
238
+ // arguments rather than going through parse-options: it accepts neither
239
+ // `--end-of-options` nor `--`, so the pack path goes in the argument
240
+ // vector directly. It is safe there because it is not user input — it is
241
+ // an absolute path this function just built under the repository's own
242
+ // pack directory.
243
+ const built = git([`index-pack`, `${base}.pack`])
237
244
  if (built.status !== 0) {
238
245
  throw new Error(`walgit: could not index ${entry.key}: ${built.stderr.trim()}`)
239
246
  }
@@ -19,9 +19,9 @@
19
19
  * garbage.
20
20
  */
21
21
 
22
- import { siblingIdx, walPrefix } from './keys'
23
- import type { ObjectStore } from './store'
24
- import { loadIndex } from './wal-index'
22
+ import { siblingIdx, walPrefix } from '../shared/keys'
23
+ import type { ObjectStore } from '../shared/store'
24
+ import { loadIndex } from '../shared/wal-index'
25
25
 
26
26
  export interface Orphan {
27
27
  key: string
@@ -17,7 +17,7 @@ import * as fs from 'node:fs'
17
17
  import * as path from 'node:path'
18
18
 
19
19
  import type { PushSigner } from './signers'
20
- import type { Claim, Provenance, WalEntry } from './wal-index'
20
+ import type { Claim, Provenance, WalEntry } from '../shared/wal-index'
21
21
 
22
22
  /**
23
23
  * What `pre-receive` hands to `reference-transaction`.
@@ -19,7 +19,7 @@ import { createHmac } from 'node:crypto'
19
19
 
20
20
  import { flagEnabled, seedValue } from '../shared/policy'
21
21
  import { CHALLENGE_PATH, READ_CHALLENGE_NAMESPACE } from '../shared/protocol'
22
- import type { Claim } from './wal-index'
22
+ import type { Claim } from '../shared/wal-index'
23
23
 
24
24
  /**
25
25
  * The variables this module reads, named so a literal fixture is checked: a
@@ -39,7 +39,7 @@
39
39
  import { flagEnabled } from '../shared/policy'
40
40
  import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
41
41
  import { git } from './git'
42
- import type { Provenance, RefChange } from './wal-index'
42
+ import type { Provenance, RefChange } from '../shared/wal-index'
43
43
 
44
44
  /** The env flag an instance sets to take Proposals. */
45
45
  export function proposalsEnabled(env: Record<string, string | undefined> = process.env): boolean {
@@ -140,7 +140,7 @@ export interface ProposalSource {
140
140
  /** The real object reader: the pushed objects are in the hook's object path. */
141
141
  export function gitObjectType(gitDir: string): (oid: string) => string | null {
142
142
  return (oid) => {
143
- const res = git(['--git-dir', gitDir, 'cat-file', '-t', oid])
143
+ const res = git(['cat-file', '-t'], { gitDir, operands: [oid], inheritObjects: true })
144
144
  if (res.status !== 0) return null
145
145
  const type = res.stdout.trim()
146
146
  return type === '' ? null : type
@@ -308,7 +308,7 @@ export type Ancestry = (tip: string, ancestorOf: string) => boolean
308
308
  */
309
309
  export function gitAncestry(gitDir: string): Ancestry {
310
310
  return (tip, ancestorOf) =>
311
- git(['--git-dir', gitDir, 'merge-base', '--is-ancestor', tip, ancestorOf]).status === 0
311
+ git(['merge-base', '--is-ancestor'], { gitDir, operands: [tip, ancestorOf] }).status === 0
312
312
  }
313
313
 
314
314
  /**
@@ -123,9 +123,18 @@ export type BlobReader = (oid: string) => string | null
123
123
  * no special handling, and returns `null` rather than throwing once the
124
124
  * quarantine is gone (which is what makes calling this from a later hook a
125
125
  * no-op rather than a crash).
126
+ *
127
+ * The repository and the quarantine are both named rather than inherited: the
128
+ * wrapper hands git no ambient `GIT_*` (see `git.ts`), so `$GIT_DIR` — which
129
+ * git sets for the hook, and which is the repository this certificate belongs
130
+ * to — is read here and passed on.
126
131
  */
127
132
  function catBlob(oid: string): string | null {
128
- const res = git(['cat-file', 'blob', oid])
133
+ const res = git(['cat-file', 'blob'], {
134
+ gitDir: process.env.GIT_DIR ?? '.',
135
+ operands: [oid],
136
+ inheritObjects: true,
137
+ })
129
138
  return res.status === 0 ? res.stdout : null
130
139
  }
131
140
 
@@ -21,7 +21,7 @@ import * as fs from 'node:fs'
21
21
  import * as path from 'node:path'
22
22
 
23
23
  import { ZERO_OID } from '../shared/protocol'
24
- import { walKey } from './keys'
24
+ import { walKey } from '../shared/keys'
25
25
  import { writePending, type PendingPush } from './pending'
26
26
  import { certSigner } from './push-cert'
27
27
  import {
@@ -31,22 +31,24 @@ import {
31
31
  type ProposalGate,
32
32
  type PushSigner,
33
33
  } from './signers'
34
- import type { ObjectStore } from './store'
35
- import { ulid } from './ulid'
34
+ import type { ObjectStore } from '../shared/store'
35
+ import { ulid } from '../shared/ulid'
36
36
  import {
37
- applyClaim,
38
- applyProvenance,
39
- applyRefChanges,
40
- commitIndex,
41
37
  loadIndex,
42
- nextIndex,
43
- sha256,
44
38
  type Claim,
45
39
  type Provenance,
46
40
  type PushRecord,
47
41
  type RefChange,
48
42
  type WalEntry,
49
43
  type WalIndex,
44
+ } from '../shared/wal-index'
45
+ import {
46
+ applyClaim,
47
+ applyProvenance,
48
+ applyRefChanges,
49
+ commitIndex,
50
+ nextIndex,
51
+ sha256,
50
52
  } from './wal-index'
51
53
 
52
54
  /**
@@ -19,7 +19,7 @@ import * as fs from 'node:fs'
19
19
  import * as path from 'node:path'
20
20
 
21
21
  import { git } from './git'
22
- import type { WalIndex } from './wal-index'
22
+ import type { WalIndex } from '../shared/wal-index'
23
23
 
24
24
  export interface ReconcileResult {
25
25
  changed: boolean
@@ -37,7 +37,7 @@ export interface ReconcileResult {
37
37
  }
38
38
 
39
39
  export function localRefs(gitDir: string): Record<string, string> {
40
- const res = git(['--git-dir', gitDir, 'for-each-ref', '--format=%(objectname) %(refname)'])
40
+ const res = git(['for-each-ref', '--format=%(objectname) %(refname)'], { gitDir })
41
41
  if (res.status !== 0) throw new Error(`for-each-ref failed: ${res.stderr.trim()}`)
42
42
  const refs: Record<string, string> = {}
43
43
  for (const line of res.stdout.split('\n')) {
@@ -50,7 +50,8 @@ export function localRefs(gitDir: string): Record<string, string> {
50
50
  /** Which of these oids the local object store actually has. One process. */
51
51
  export function presentObjects(gitDir: string, oids: readonly string[]): Set<string> {
52
52
  if (oids.length === 0) return new Set()
53
- const res = git(['--git-dir', gitDir, 'cat-file', '--batch-check'], {
53
+ const res = git(['cat-file', '--batch-check'], {
54
+ gitDir,
54
55
  input: `${oids.join('\n')}\n`,
55
56
  })
56
57
  const present = new Set<string>()
@@ -13,6 +13,7 @@
13
13
 
14
14
  import { capabilitiesFrom } from '../shared/capabilities'
15
15
  import { parseTokens } from '../shared/credentials'
16
+ import { listCommits, listTree, readBlob, statBlob } from './browse'
16
17
  import { ensureBareRepo } from './cache'
17
18
  import { configuredExpiryMs, expireRepos } from './expire'
18
19
  import { createHttpHandler } from './http'
@@ -21,10 +22,11 @@ import { gitAncestry, isProposalRef, listProposals } from './proposals'
21
22
  import { resolveRepo } from './repo'
22
23
  import { sshReadVerifier } from './ssh-signature'
23
24
  import { runGitHttpBackend } from './git-backend'
24
- import type { ObjectStore } from './store'
25
+ import type { ObjectStore } from '../shared/store'
25
26
  import { storeFromEnv } from './store-env'
26
27
  import { syncRepo } from './sync'
27
- import { loadIndex } from './wal-index'
28
+ import { lastPushOf } from '../shared/repo-list'
29
+ import { loadIndex } from '../shared/wal-index'
28
30
 
29
31
  const reposDir = process.env.WALGIT_REPOS_DIR ?? '/srv/walgit/repos'
30
32
  const port = Number(process.env.PORT ?? 8080)
@@ -241,6 +243,31 @@ try {
241
243
  return listProposals(index.refs, index.provenance ?? {}, gitAncestry(repo.dir))
242
244
  }
243
245
  : undefined,
246
+ // What a browse of one repository reads (`shared/browse.ts`): the refs and
247
+ // the last push from the INDEX, because that is the source of truth and a
248
+ // node's disk is a cache, and one level of a tree from the CACHE, because
249
+ // the Index holds no objects. `null` from the Index reader is the name
250
+ // nobody has pushed to — `loadIndex` reports that as a missing etag, which
251
+ // is the one distinction an empty ref map cannot make and the one this
252
+ // endpoint must not get wrong: a browse must not bring a name into
253
+ // existence.
254
+ //
255
+ // Absent without a store for the reason `readProvenance` is: there is
256
+ // nothing authoritative behind the endpoint, and it should not exist.
257
+ // Whether the deployment OFFERS the web view at all is the handler's check,
258
+ // against the capability this same process advertises.
259
+ browse: store
260
+ ? {
261
+ readIndex: async (repoId) => {
262
+ const { index, etag } = await loadIndex(store, repoId)
263
+ return etag === null ? null : { refs: index.refs, lastPush: lastPushOf(index) }
264
+ },
265
+ listTree: (repo, rev, path) => listTree(repo.dir, rev, path),
266
+ statBlob: (repo, rev, path) => statBlob(repo.dir, rev, path),
267
+ readBlob: (repo, rev, path) => readBlob(repo.dir, rev, path),
268
+ listCommits: (repo, rev, before, limit) => listCommits(repo.dir, rev, before, limit),
269
+ }
270
+ : undefined,
244
271
  // Read gating, and only where all three halves exist (docs/adr/0013): the
245
272
  // seed with the Signer List flag beside it, and a store to read the Reader
246
273
  // List out of. Without a store the Index cannot be read at all, and a gate
@@ -53,7 +53,7 @@ import { git } from './git'
53
53
  import { readAllowed } from './private'
54
54
  import { PROPOSALS_PREFIX, SIGNERS_TARGET, isProposalRef } from './proposals'
55
55
  import { certificatePresented, signedPushEnabled, type PushCertEnv } from './push-cert'
56
- import type { RefChange } from './wal-index'
56
+ import type { RefChange } from '../shared/wal-index'
57
57
 
58
58
  /**
59
59
  * The env flag an instance sets to give its repositories Signer Lists.
@@ -204,7 +204,9 @@ export const MAX_KEY_LIST_BYTES = 64 * 1024
204
204
  */
205
205
  export function gitListSource(gitDir: string): ListSource {
206
206
  return (oid, file) => {
207
- const checked = git(['--git-dir', gitDir, 'cat-file', '--batch-check'], {
207
+ const checked = git(['cat-file', '--batch-check'], {
208
+ gitDir,
209
+ inheritObjects: true,
208
210
  input: `${oid}\n${oid}:${file}\n`,
209
211
  })
210
212
  const [tip, found] = checked.stdout.split('\n')
@@ -250,7 +252,11 @@ export function gitListSource(gitDir: string): ListSource {
250
252
  }
251
253
  }
252
254
 
253
- const blob = git(['--git-dir', gitDir, 'cat-file', 'blob', `${oid}:${file}`])
255
+ const blob = git(['cat-file', 'blob'], {
256
+ gitDir,
257
+ inheritObjects: true,
258
+ operands: [`${oid}:${file}`],
259
+ })
254
260
  // It was there a moment ago and a git object is immutable, so this is a
255
261
  // read that failed rather than a file that is absent — and saying "add a
256
262
  // `signers` file" to someone who just pushed one is worse than saying
@@ -14,32 +14,19 @@
14
14
 
15
15
  import { AwsClient } from 'aws4fetch'
16
16
 
17
- import { FileStore, S3Store, type ObjectStore } from './store'
17
+ import { s3StoreFrom, type ObjectStore } from '../shared/store'
18
+ import { FileStore } from './store'
18
19
 
19
20
  export type Env = Record<string, string | undefined>
20
21
 
21
22
  export function storeFromEnv(env: Env = process.env): ObjectStore | null {
23
+ // The one branch only this half can serve: a local directory instead of a
24
+ // bucket, for development and tests.
22
25
  if (env.WALGIT_STORE_DIR) return new FileStore(env.WALGIT_STORE_DIR)
23
-
24
- const endpoint = env.WALGIT_S3_ENDPOINT
25
- const bucket = env.WALGIT_S3_BUCKET
26
- const accessKeyId = env.WALGIT_S3_ACCESS_KEY_ID
27
- const secretAccessKey = env.WALGIT_S3_SECRET_ACCESS_KEY
28
- if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) return null
29
-
30
- const client = new AwsClient({
31
- accessKeyId,
32
- secretAccessKey,
33
- service: 's3',
34
- // R2 ignores the region but the SigV4 signature does not: an absent region
35
- // signs differently and every request 403s with nothing useful in the body.
36
- region: env.WALGIT_S3_REGION ?? 'auto',
37
- })
38
- return new S3Store({
39
- endpoint: endpoint.replace(/\/$/, ''),
40
- bucket,
41
- fetch: (input, init) => client.fetch(input, init),
42
- })
26
+ // Everything else is the shared reading (`shared/store.ts`), which the edge
27
+ // makes too — including the region rule, which is the part that used to be
28
+ // commented identically in both copies.
29
+ return s3StoreFrom(env, (credentials) => new AwsClient(credentials))
43
30
  }
44
31
 
45
32
  /** The store, or a thrown explanation. For paths that must not proceed without one. */
@@ -1,253 +1,24 @@
1
1
  /**
2
- * The object-store seam.
2
+ * `FileStore` — an `ObjectStore` backed by a local directory.
3
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
- * The interface is deliberately narrow — five operations, exactly what the WAL
10
- * needs. In particular it exposes CONDITIONAL writes as a first-class result
11
- * rather than an exception, because losing a compare-and-swap is a normal
12
- * outcome on the push path, not an error: two pushes raced and one has to be
13
- * told to try again.
4
+ * The interface and the two portable implementations (`MemoryStore`,
5
+ * `S3Store`) are in `shared/store.ts`, which both halves of walgit compile.
6
+ * This one cannot go with them and should not: it is `node:fs` and an
7
+ * `mkdir`-based lock, which is the container's disk (docs/adr/0010).
14
8
  */
15
9
 
16
10
  import * as fs from 'node:fs'
17
11
  import * as nodePath from 'node:path'
18
12
 
13
+ import type {
14
+ ConditionalGetResult,
15
+ GetResult,
16
+ ObjectStore,
17
+ PutCondition,
18
+ PutResult,
19
+ } from '../shared/store'
19
20
  import { acquireLock } from './mkdir-lock'
20
21
 
21
- /** A conditional precondition on a write. */
22
- export type PutCondition =
23
- /** Write only if the object's current ETag matches (compare-and-swap). */
24
- | { ifMatch: string }
25
- /** Write only if the object does not exist yet. */
26
- | { ifAbsent: true }
27
-
28
- export type PutResult =
29
- | { ok: true; etag: string }
30
- /** The precondition failed: someone else wrote first. Not an error. */
31
- | { ok: false; reason: 'precondition-failed' }
32
-
33
- export type GetResult = { body: Uint8Array; etag: string } | null
34
-
35
- /** Result of a conditional read — the cheap "am I current?" check. */
36
- export type ConditionalGetResult =
37
- | { status: 'not-modified' }
38
- | { status: 'ok'; body: Uint8Array; etag: string }
39
- | { status: 'absent' }
40
-
41
- export interface ObjectStore {
42
- get(key: string): Promise<GetResult>
43
- /**
44
- * Read only if the caller's ETag is stale. A `not-modified` answer is a
45
- * metadata-only round trip, which is what makes "is my cached repo current?"
46
- * cheap enough to do on every request.
47
- */
48
- getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult>
49
- /** Unconditional when `condition` is omitted. */
50
- put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult>
51
- delete(key: string): Promise<void>
52
- /** Keys under a prefix, lexicographically ascending. */
53
- list(prefix: string): Promise<string[]>
54
- /**
55
- * Immediate child prefixes under `prefix`, delimited by `/`.
56
- *
57
- * Optional because it is an optimisation, not a capability: a store without
58
- * it is enumerated by `list` and derivation (see `listRepoIds`). It exists
59
- * because "which repositories exist?" is one question the bucket can answer
60
- * in a handful of round trips, and answering it by listing every packfile in
61
- * the log would make a read-only report the most expensive command walgit
62
- * has.
63
- */
64
- listPrefixes?(prefix: string): Promise<string[]>
65
- }
66
-
67
- // ── In-memory implementation ────────────────────────────────────────────────
68
-
69
- /**
70
- * For tests. Faithful about the one property that matters: a conditional put
71
- * evaluates its precondition and swaps atomically with respect to other
72
- * in-flight puts.
73
- *
74
- * `yieldBeforeWrite` exists because JavaScript would otherwise make this test
75
- * nothing. Without a suspension point between reading the current ETag and
76
- * writing, every put runs to completion uninterrupted and a broken CAS
77
- * implementation would still pass. The hook forces the interleaving that a real
78
- * network round trip would produce.
79
- */
80
- export class MemoryStore implements ObjectStore {
81
- private objects = new Map<string, { body: Uint8Array; etag: string }>()
82
- private counter = 0
83
-
84
- constructor(private readonly yieldBeforeWrite: () => Promise<void> = async () => {}) {}
85
-
86
- private nextEtag(): string {
87
- this.counter += 1
88
- return `"mem-${this.counter}"`
89
- }
90
-
91
- async get(key: string): Promise<GetResult> {
92
- const found = this.objects.get(key)
93
- return found ? { body: found.body, etag: found.etag } : null
94
- }
95
-
96
- async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
97
- const found = this.objects.get(key)
98
- if (!found) return { status: 'absent' }
99
- if (found.etag === etag) return { status: 'not-modified' }
100
- return { status: 'ok', body: found.body, etag: found.etag }
101
- }
102
-
103
- async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
104
- // Read the precondition's subject, then suspend — this is the window a
105
- // real store has, and the window a wrong implementation loses data in.
106
- const before = this.objects.get(key)
107
- await this.yieldBeforeWrite()
108
-
109
- // Re-read after the suspension: the check and the swap must both see the
110
- // same state, which is the whole contract being modelled.
111
- const current = this.objects.get(key)
112
- if (condition) {
113
- if ('ifAbsent' in condition && current) return { ok: false, reason: 'precondition-failed' }
114
- if ('ifMatch' in condition && current?.etag !== condition.ifMatch) {
115
- return { ok: false, reason: 'precondition-failed' }
116
- }
117
- // A racing writer that landed during the suspension invalidates a
118
- // precondition that was true when we started.
119
- if (current?.etag !== before?.etag) return { ok: false, reason: 'precondition-failed' }
120
- }
121
-
122
- const etag = this.nextEtag()
123
- this.objects.set(key, { body, etag })
124
- return { ok: true, etag }
125
- }
126
-
127
- async delete(key: string): Promise<void> {
128
- this.objects.delete(key)
129
- }
130
-
131
- async list(prefix: string): Promise<string[]> {
132
- return [...this.objects.keys()].filter((k) => k.startsWith(prefix)).sort()
133
- }
134
- }
135
-
136
- // ── S3-compatible implementation (R2, S3, MinIO, Tigris) ────────────────────
137
-
138
- export interface S3StoreOptions {
139
- /** e.g. `https://<account>.r2.cloudflarestorage.com` */
140
- endpoint: string
141
- bucket: string
142
- /** Signs each request. `aws4fetch`'s `AwsClient.fetch` satisfies this. */
143
- fetch: (input: string, init?: RequestInit) => Promise<Response>
144
- }
145
-
146
- /**
147
- * Conditional writes were verified against R2 on 2026-08-20 — 16 concurrent
148
- * writers against one ETag produced exactly one 200 and fifteen 412s, with no
149
- * torn writes. See docs/research/walgit-m0-spike/.
150
- *
151
- * Portability caveat worth carrying: Tigris honours the same headers but only
152
- * evaluates them safely on Multi-region or Single-region buckets. Its Global
153
- * and Dual-region types are strong same-region and eventual cross-region, and a
154
- * sub-second replication window is exactly wide enough to lose a push race and
155
- * never reproduce it.
156
- */
157
- export class S3Store implements ObjectStore {
158
- constructor(private readonly opts: S3StoreOptions) {}
159
-
160
- private url(key: string): string {
161
- return `${this.opts.endpoint}/${this.opts.bucket}/${key}`
162
- }
163
-
164
- async get(key: string): Promise<GetResult> {
165
- const res = await this.opts.fetch(this.url(key))
166
- if (res.status === 404) return null
167
- if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
168
- return { body: new Uint8Array(await res.arrayBuffer()), etag: res.headers.get('etag') ?? '' }
169
- }
170
-
171
- async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
172
- const res = await this.opts.fetch(this.url(key), { headers: { 'If-None-Match': etag } })
173
- if (res.status === 304) return { status: 'not-modified' }
174
- if (res.status === 404) return { status: 'absent' }
175
- if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
176
- return {
177
- status: 'ok',
178
- body: new Uint8Array(await res.arrayBuffer()),
179
- etag: res.headers.get('etag') ?? '',
180
- }
181
- }
182
-
183
- async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
184
- const headers: Record<string, string> = {}
185
- if (condition && 'ifMatch' in condition) headers['If-Match'] = condition.ifMatch
186
- if (condition && 'ifAbsent' in condition) headers['If-None-Match'] = '*'
187
-
188
- // `Uint8Array` is a valid BodyInit at runtime; the cast is only to bridge
189
- // TS 5.7's `Uint8Array<ArrayBufferLike>` against lib.dom's narrower
190
- // `BodyInit`, which does not accept the generic form.
191
- const res = await this.opts.fetch(this.url(key), {
192
- method: 'PUT',
193
- body: body as unknown as BodyInit,
194
- headers,
195
- })
196
- // 412 is the documented precondition failure. 409 is included because
197
- // S3-compatible stores have historically used it for the same condition
198
- // under concurrent load; treating it as an error would surface a normal
199
- // race as an outage.
200
- if (res.status === 412 || res.status === 409)
201
- return { ok: false, reason: 'precondition-failed' }
202
- if (!res.ok) throw new Error(`PUT ${key}: HTTP ${res.status}`)
203
- return { ok: true, etag: res.headers.get('etag') ?? '' }
204
- }
205
-
206
- async delete(key: string): Promise<void> {
207
- const res = await this.opts.fetch(this.url(key), { method: 'DELETE' })
208
- if (!res.ok && res.status !== 404) throw new Error(`DELETE ${key}: HTTP ${res.status}`)
209
- }
210
-
211
- async list(prefix: string): Promise<string[]> {
212
- const keys: string[] = []
213
- let token: string | undefined
214
- do {
215
- const params = new URLSearchParams({ 'list-type': '2', prefix })
216
- if (token) params.set('continuation-token', token)
217
- const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
218
- if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
219
- const xml = await res.text()
220
- for (const m of xml.matchAll(/<Key>([^<]+)<\/Key>/g)) keys.push(m[1]!)
221
- token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
222
- } while (token)
223
- return keys.sort()
224
- }
225
-
226
- /**
227
- * `delimiter=/` makes the store roll every key sharing a child prefix into a
228
- * single `CommonPrefixes` entry, so a bucket holding a million WAL objects
229
- * still answers "which repositories are there?" in one page per thousand
230
- * repositories.
231
- */
232
- async listPrefixes(prefix: string): Promise<string[]> {
233
- const prefixes: string[] = []
234
- let token: string | undefined
235
- do {
236
- const params = new URLSearchParams({ 'list-type': '2', prefix, delimiter: '/' })
237
- if (token) params.set('continuation-token', token)
238
- const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
239
- if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
240
- const xml = await res.text()
241
- for (const block of xml.matchAll(/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g)) {
242
- const found = /<Prefix>([^<]+)<\/Prefix>/.exec(block[1]!)
243
- if (found) prefixes.push(found[1]!)
244
- }
245
- token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
246
- } while (token)
247
- return prefixes.sort()
248
- }
249
- }
250
-
251
22
  // ── Filesystem implementation ───────────────────────────────────────────────
252
23
 
253
24
  /**
@@ -21,11 +21,11 @@
21
21
  * request rather than behind a flag.
22
22
  */
23
23
 
24
- import type { ObjectStore } from './store'
24
+ import type { ObjectStore } from '../shared/store'
25
25
  import type { ResolvedRepo } from './repo'
26
26
  import { isPartial, materialize, type MaterializeStats } from './materialize'
27
27
  import { reconcile, type ReconcileResult } from './reconcile'
28
- import { loadIndex } from './wal-index'
28
+ import { loadIndex } from '../shared/wal-index'
29
29
 
30
30
  export type SyncResult = ReconcileResult & {
31
31
  /** Present only when the WAL was actually replayed onto this disk. */
@@ -21,9 +21,10 @@
21
21
  * request path, not here.
22
22
  */
23
23
 
24
- import { indexKey, listRepoIds } from './keys'
25
- import type { ObjectStore } from './store'
26
- import type { WalEntry, WalIndex } from './wal-index'
24
+ import { indexKey, listRepoIds } from '../shared/keys'
25
+ import { pooled } from '../shared/pooled'
26
+ import type { ObjectStore } from '../shared/store'
27
+ import type { WalEntry, WalIndex } from '../shared/wal-index'
27
28
 
28
29
  export interface RepoUsage {
29
30
  repoId: string
@@ -192,21 +193,6 @@ function bucketHoursFor(windowHours: number): number {
192
193
  return 24 * 7
193
194
  }
194
195
 
195
- /** Run `task` over `items` with a bounded number in flight. */
196
- async function pooled<T, R>(
197
- items: readonly T[],
198
- limit: number,
199
- task: (item: T) => Promise<R>,
200
- ): Promise<R[]> {
201
- const results: R[] = Array.from({ length: items.length })
202
- let next = 0
203
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
204
- for (let i = next++; i < items.length; i = next++) results[i] = await task(items[i]!)
205
- })
206
- await Promise.all(workers)
207
- return results
208
- }
209
-
210
196
  export async function collectUsage(
211
197
  store: ObjectStore,
212
198
  options: UsageOptions = {},
@@ -34,8 +34,8 @@ import * as path from 'node:path'
34
34
  import { absentEntries, isPartial } from './materialize'
35
35
  import { localRefs, presentObjects } from './reconcile'
36
36
  import type { ResolvedRepo } from './repo'
37
- import type { ObjectStore } from './store'
38
- import { loadIndex, type WalIndex } from './wal-index'
37
+ import type { ObjectStore } from '../shared/store'
38
+ import { loadIndex, type WalIndex } from '../shared/wal-index'
39
39
 
40
40
  export interface RefDivergence {
41
41
  ref: string