@zabaca/zbc 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/package.json +6 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/init.ts +1 -0
  5. package/src/engine/apply.ts +60 -21
  6. package/src/engine/destroy.ts +183 -14
  7. package/src/engine/discover.ts +1 -1
  8. package/src/engine/resolve.ts +56 -11
  9. package/src/utils/copy-template.ts +10 -0
  10. package/templates/apps/inbox/package.json +4 -2
  11. package/templates/apps/inbox/tsconfig.json +3 -1
  12. package/templates/apps/inbox/worker/api.ts +197 -0
  13. package/templates/apps/inbox/worker/commands.ts +299 -0
  14. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  15. package/templates/apps/inbox/worker/index.ts +15 -202
  16. package/templates/apps/inbox/worker/mcp.ts +49 -100
  17. package/templates/apps/walgit/CONTEXT.md +135 -0
  18. package/templates/apps/walgit/Dockerfile +40 -18
  19. package/templates/apps/walgit/README.md +518 -55
  20. package/templates/apps/walgit/e2e/README.md +100 -6
  21. package/templates/apps/walgit/e2e/harness.ts +262 -1
  22. package/templates/apps/walgit/e2e/live.ts +588 -0
  23. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  24. package/templates/apps/walgit/e2e/suite.ts +5 -5
  25. package/templates/apps/walgit/examples/watch.ts +209 -0
  26. package/templates/apps/walgit/package.json +12 -3
  27. package/templates/apps/walgit/registry.json +6 -11
  28. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  29. package/templates/apps/walgit/shared/container-env.ts +114 -0
  30. package/templates/apps/walgit/shared/credentials.ts +81 -0
  31. package/templates/apps/walgit/shared/events.ts +277 -0
  32. package/templates/apps/walgit/shared/landing.ts +1241 -0
  33. package/templates/apps/walgit/shared/llms.ts +463 -0
  34. package/templates/apps/walgit/shared/outbox.ts +266 -0
  35. package/templates/apps/walgit/shared/policy.ts +59 -0
  36. package/templates/apps/walgit/shared/protocol.ts +197 -0
  37. package/templates/apps/walgit/shared/provenance.ts +154 -0
  38. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  39. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  40. package/templates/apps/walgit/src/announce-main.ts +37 -0
  41. package/templates/apps/walgit/src/announce.ts +98 -0
  42. package/templates/apps/walgit/src/append-only.ts +112 -0
  43. package/templates/apps/walgit/src/cache.ts +172 -0
  44. package/templates/apps/walgit/src/cli.ts +493 -0
  45. package/templates/apps/walgit/src/compact.ts +25 -23
  46. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  47. package/templates/apps/walgit/src/expire.ts +248 -0
  48. package/templates/apps/walgit/src/gc.ts +8 -16
  49. package/templates/apps/walgit/src/git-backend.ts +29 -0
  50. package/templates/apps/walgit/src/git.ts +78 -0
  51. package/templates/apps/walgit/src/hook-main.ts +259 -17
  52. package/templates/apps/walgit/src/hooks.ts +4 -3
  53. package/templates/apps/walgit/src/http.ts +237 -45
  54. package/templates/apps/walgit/src/instructions.ts +240 -0
  55. package/templates/apps/walgit/src/keys.ts +126 -0
  56. package/templates/apps/walgit/src/limits.ts +158 -0
  57. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  58. package/templates/apps/walgit/src/materialize.ts +48 -40
  59. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  60. package/templates/apps/walgit/src/orphans.ts +2 -5
  61. package/templates/apps/walgit/src/pending.ts +201 -0
  62. package/templates/apps/walgit/src/push-cert.ts +254 -0
  63. package/templates/apps/walgit/src/push.ts +233 -46
  64. package/templates/apps/walgit/src/reconcile.ts +5 -8
  65. package/templates/apps/walgit/src/repo.ts +22 -77
  66. package/templates/apps/walgit/src/server.ts +148 -26
  67. package/templates/apps/walgit/src/signers.ts +577 -0
  68. package/templates/apps/walgit/src/store-env.ts +5 -4
  69. package/templates/apps/walgit/src/store.ts +47 -24
  70. package/templates/apps/walgit/src/usage.ts +404 -0
  71. package/templates/apps/walgit/src/verify.ts +171 -0
  72. package/templates/apps/walgit/src/wal-index.ts +189 -11
  73. package/templates/apps/walgit/tsconfig.json +8 -2
  74. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  75. package/templates/apps/walgit/worker/events-do.ts +259 -0
  76. package/templates/apps/walgit/worker/index.ts +572 -0
  77. package/templates/apps/walgit/wrangler.jsonc +95 -0
  78. package/templates/apps/warehouse/package.json +1 -1
  79. package/templates/infra/modules/cloudflare/index.ts +93 -67
  80. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  81. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  82. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  83. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  84. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  85. package/templates/infra/modules/cloudflare-token/index.ts +10 -30
  86. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  87. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  88. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  89. package/templates/infra/modules/fly/index.ts +158 -35
  90. package/templates/infra/modules/host-file/index.ts +6 -7
  91. package/templates/infra/modules/provision-core/index.ts +21 -15
  92. package/templates/infra/modules/r2/index.ts +38 -55
  93. package/templates/infra/modules/r2/registry.json +1 -1
  94. package/templates/infra/modules/remote-provision/index.ts +1 -3
  95. package/templates/infra/modules/turso/index.ts +45 -7
  96. package/templates/infra/modules/vm-provision/index.ts +10 -3
  97. package/templates/infra/package.json +1 -1
  98. package/templates/infra/src/context.ts +115 -0
  99. package/templates/infra/src/define-module.ts +8 -2
  100. package/templates/infra/src/index.ts +11 -1
  101. package/templates/infra/src/types.ts +72 -3
  102. package/src/commands/add-registry.test.ts +0 -92
  103. package/src/commands/secret.test.ts +0 -717
  104. package/src/commands/vendor-mode.test.ts +0 -183
  105. package/src/infra-types.ts +0 -38
  106. package/src/utils/subtree.test.ts +0 -127
  107. package/templates/apps/inbox/worker/send-op.ts +0 -174
  108. package/templates/apps/walgit/entrypoint.sh +0 -59
  109. package/templates/apps/walgit/fly.toml +0 -52
  110. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  111. package/templates/apps/walgit/sshd_config +0 -38
@@ -16,6 +16,8 @@
16
16
  import * as fs from 'node:fs'
17
17
  import * as nodePath from 'node:path'
18
18
 
19
+ import { acquireLock } from './mkdir-lock'
20
+
19
21
  /** A conditional precondition on a write. */
20
22
  export type PutCondition =
21
23
  /** Write only if the object's current ETag matches (compare-and-swap). */
@@ -49,6 +51,17 @@ export interface ObjectStore {
49
51
  delete(key: string): Promise<void>
50
52
  /** Keys under a prefix, lexicographically ascending. */
51
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[]>
52
65
  }
53
66
 
54
67
  // ── In-memory implementation ────────────────────────────────────────────────
@@ -209,6 +222,30 @@ export class S3Store implements ObjectStore {
209
222
  } while (token)
210
223
  return keys.sort()
211
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
+ }
212
249
  }
213
250
 
214
251
  // ── Filesystem implementation ───────────────────────────────────────────────
@@ -242,7 +279,9 @@ export class FileStore implements ObjectStore {
242
279
  async get(key: string): Promise<GetResult> {
243
280
  if (!fs.existsSync(this.path(key))) return null
244
281
  return {
245
- body: new Uint8Array(fs.readFileSync(this.path(key))),
282
+ // The `Buffer` is returned as it is: it already IS a `Uint8Array`, and
283
+ // wrapping it would copy every byte read back out of the store.
284
+ body: fs.readFileSync(this.path(key)),
246
285
  etag: fs.readFileSync(this.etagPath(key), 'utf8'),
247
286
  }
248
287
  }
@@ -282,33 +321,17 @@ export class FileStore implements ObjectStore {
282
321
  }
283
322
  }
284
323
 
324
+ /**
325
+ * A conditional write is over in milliseconds, so a lock still held after a
326
+ * second belongs to a process that died mid-write — and one of those would
327
+ * otherwise wedge every later push. See `mkdir-lock.ts` for why breaking it
328
+ * is safe.
329
+ */
285
330
  private async lock(key: string): Promise<() => void> {
286
331
  const dir = `${this.root}/.walgit-locks`
287
332
  fs.mkdirSync(dir, { recursive: true })
288
333
  const lockPath = `${dir}/${key.replace(/[^A-Za-z0-9]/g, '_')}.lock`
289
- for (let i = 0; ; i += 1) {
290
- try {
291
- fs.mkdirSync(lockPath)
292
- return () => {
293
- try {
294
- fs.rmdirSync(lockPath)
295
- } catch {
296
- /* already released */
297
- }
298
- }
299
- } catch {
300
- // A holder that died mid-write would otherwise wedge every later push,
301
- // so the wait is bounded and then broken.
302
- if (i > 200) {
303
- try {
304
- fs.rmdirSync(lockPath)
305
- } catch {
306
- /* someone else broke it first */
307
- }
308
- }
309
- await new Promise((r) => setTimeout(r, 5))
310
- }
311
- }
334
+ return acquireLock(lockPath, { breakAfter: 200 })
312
335
  }
313
336
 
314
337
  async delete(key: string): Promise<void> {
@@ -0,0 +1,404 @@
1
+ /**
2
+ * What is this service holding?
3
+ *
4
+ * The write-ahead log is already a usage ledger. Every entry carries a `size`
5
+ * and a `ts`, and `index.json` carries the whole entry list, so repository
6
+ * count, bytes stored, the largest repositories and push volume over time are
7
+ * all derivable from the store with no instrumentation, no counters to keep in
8
+ * sync and nothing that can drift from the thing it claims to measure. A metric
9
+ * emitted at push time would be a second record of the same fact, and the two
10
+ * would disagree the first time a push failed between them.
11
+ *
12
+ * Read-only, and it matters more here than anywhere else: this is the command
13
+ * an operator runs while worried about the bill or about abuse, which is
14
+ * exactly the moment a command that also repairs things is dangerous. Nothing
15
+ * in this file calls `put` or `delete` — `usage.test.ts` asserts that against a
16
+ * store that throws if either is reached.
17
+ *
18
+ * What it deliberately does NOT report is reads. The log records pushes; a
19
+ * clone leaves no trace in it at all, and an approximation invented here would
20
+ * read as a measurement. That gap is a separate ticket and belongs beside the
21
+ * request path, not here.
22
+ */
23
+
24
+ import { indexKey, listRepoIds } from './keys'
25
+ import type { ObjectStore } from './store'
26
+ import type { WalEntry, WalIndex } from './wal-index'
27
+
28
+ export interface RepoUsage {
29
+ repoId: string
30
+ /**
31
+ * Every entry `index.json` still names. This is what the bucket is billed
32
+ * for under this repository, superseded-but-not-yet-collected entries
33
+ * included — because it still holds them.
34
+ */
35
+ bytes: number
36
+ /**
37
+ * Entries above the compaction frontier: what a restore actually downloads.
38
+ * A large gap between this and `bytes` is a repository waiting on `walgit gc`,
39
+ * not a repository that is genuinely large.
40
+ */
41
+ liveBytes: number
42
+ entries: number
43
+ seq: number
44
+ refs: number
45
+ pushes: number
46
+ /** Bytes pushed, ever — growth, as distinct from what is currently stored. */
47
+ pushBytes: number
48
+ firstPush: string | null
49
+ lastPush: string | null
50
+ /** Pushes and bytes inside the requested window; zero when none was asked for. */
51
+ pushesInWindow: number
52
+ bytesInWindow: number
53
+ /**
54
+ * The repository is scheduled for deletion but still inside its grace period.
55
+ * Its bytes are counted, because the bucket still holds them — but an
56
+ * operator reading a total needs to know which part of it is already leaving.
57
+ */
58
+ deletionPending: boolean
59
+ }
60
+
61
+ /** One slice of the window, for push volume over time. */
62
+ export interface UsageBucket {
63
+ /** Inclusive ISO instant this slice starts at. */
64
+ start: string
65
+ pushes: number
66
+ bytes: number
67
+ }
68
+
69
+ /** A `repos/<id>/` prefix whose index could not be read. Named, never silent. */
70
+ export interface UnreadableRepo {
71
+ repoId: string
72
+ reason: string
73
+ }
74
+
75
+ export interface UsageWindow {
76
+ since: string
77
+ until: string
78
+ hours: number
79
+ /** Width of each bucket in `buckets`, in hours. */
80
+ bucketHours: number
81
+ }
82
+
83
+ export interface UsageReport {
84
+ generatedAt: string
85
+ window: UsageWindow | null
86
+ /** Repositories the store holds an index for. */
87
+ repos: number
88
+ bytes: number
89
+ /** Bytes belonging to repositories already scheduled for deletion. */
90
+ bytesPendingDeletion: number
91
+ liveBytes: number
92
+ entries: number
93
+ pushes: number
94
+ pushesInWindow: number
95
+ bytesInWindow: number
96
+ /** Sorted by `bytes` descending, truncated to the requested `top`. */
97
+ largest: RepoUsage[]
98
+ buckets: UsageBucket[]
99
+ unreadable: UnreadableRepo[]
100
+ }
101
+
102
+ export interface UsageOptions {
103
+ /** How far back the window reaches. Omit for lifetime totals and no buckets. */
104
+ sinceMs?: number
105
+ /** How many repositories to name. 0 means all of them. Default 10. */
106
+ top?: number
107
+ /** Injected so tests can fix the window. */
108
+ now?: () => Date
109
+ /** How many indexes to read at once. */
110
+ concurrency?: number
111
+ }
112
+
113
+ // ── Enumerating repositories ────────────────────────────────────────────────
114
+
115
+ /**
116
+ * The repository ids the store holds.
117
+ *
118
+ * `listPrefixes` is the cheap path — one delimited LIST names every repository
119
+ * without naming a single packfile. Stores that do not implement it (the
120
+ * in-memory and filesystem ones) fall back to deriving the ids from a full
121
+ * listing, which is fine at their scale and wrong at a bucket's.
122
+ */
123
+ // ── Folding one index ───────────────────────────────────────────────────────
124
+
125
+ function isInWindow(entry: WalEntry, since: number, until: number): boolean {
126
+ const at = Date.parse(entry.ts)
127
+ // An unparseable timestamp is counted in the lifetime totals (its bytes are
128
+ // real) but never in a window: guessing which slice it belongs to would put
129
+ // a fabricated bar on the chart.
130
+ return Number.isFinite(at) && at >= since && at <= until
131
+ }
132
+
133
+ /**
134
+ * Fold one repository's index into its usage row. Pure — no I/O.
135
+ *
136
+ * `onWindowedPush` is how the caller builds the time series without the fold
137
+ * having to keep every entry alive: each in-window push is offered once, and
138
+ * the report's buckets are the only thing that wants them.
139
+ */
140
+ export function usageOfIndex(
141
+ index: WalIndex,
142
+ window?: { since: number; until: number },
143
+ onWindowedPush?: (entry: WalEntry) => void,
144
+ ): RepoUsage {
145
+ const row: RepoUsage = {
146
+ repoId: index.repo_id,
147
+ bytes: 0,
148
+ liveBytes: 0,
149
+ entries: index.entries.length,
150
+ seq: index.seq,
151
+ refs: Object.keys(index.refs).length,
152
+ pushes: 0,
153
+ pushBytes: 0,
154
+ firstPush: null,
155
+ lastPush: null,
156
+ pushesInWindow: 0,
157
+ bytesInWindow: 0,
158
+ deletionPending: index.deletion !== undefined,
159
+ }
160
+
161
+ for (const entry of index.entries) {
162
+ row.bytes += entry.size
163
+ if (entry.seq > index.compaction_frontier) row.liveBytes += entry.size
164
+ // Compaction entries are storage, not traffic: counting a repack as a push
165
+ // would make a quiet repository look busy on the day it was compacted.
166
+ if (entry.kind !== 'push') continue
167
+ row.pushes += 1
168
+ row.pushBytes += entry.size
169
+ if (row.firstPush === null || entry.ts < row.firstPush) row.firstPush = entry.ts
170
+ if (row.lastPush === null || entry.ts > row.lastPush) row.lastPush = entry.ts
171
+ if (window && isInWindow(entry, window.since, window.until)) {
172
+ row.pushesInWindow += 1
173
+ row.bytesInWindow += entry.size
174
+ onWindowedPush?.(entry)
175
+ }
176
+ }
177
+ return row
178
+ }
179
+
180
+ // ── The report ──────────────────────────────────────────────────────────────
181
+
182
+ const HOUR_MS = 3_600_000
183
+
184
+ /**
185
+ * Bucket width, chosen from the window rather than configured: a day of pushes
186
+ * is legible by the hour and a quarter of them is not, and an operator should
187
+ * not have to pick.
188
+ */
189
+ function bucketHoursFor(windowHours: number): number {
190
+ if (windowHours <= 48) return 1
191
+ if (windowHours <= 24 * 14) return 24
192
+ return 24 * 7
193
+ }
194
+
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
+ export async function collectUsage(
211
+ store: ObjectStore,
212
+ options: UsageOptions = {},
213
+ ): Promise<UsageReport> {
214
+ const now = (options.now ?? (() => new Date()))()
215
+ const until = now.getTime()
216
+ const window = options.sinceMs === undefined ? null : { since: until - options.sinceMs, until }
217
+
218
+ // Buckets are laid out before anything is read, so the fold can drop each
219
+ // in-window push straight into its slice. Anchored at the window's END, so
220
+ // the last bucket is the hour the operator is standing in rather than an
221
+ // arbitrary one starting whenever the window happened to begin.
222
+ const bucketHours = window ? bucketHoursFor((options.sinceMs ?? 0) / HOUR_MS) : 0
223
+ const bucketMs = bucketHours * HOUR_MS
224
+ const buckets: UsageBucket[] = []
225
+ if (window) {
226
+ const count = Math.max(1, Math.ceil((window.until - window.since) / bucketMs))
227
+ for (let i = count; i >= 1; i -= 1) {
228
+ buckets.push({
229
+ start: new Date(window.until - i * bucketMs).toISOString(),
230
+ pushes: 0,
231
+ bytes: 0,
232
+ })
233
+ }
234
+ }
235
+ const firstBucketAt = buckets.length > 0 ? Date.parse(buckets[0]!.start) : 0
236
+ const record = (entry: WalEntry): void => {
237
+ const slot = Math.floor((Date.parse(entry.ts) - firstBucketAt) / bucketMs)
238
+ const bucket = buckets[Math.min(Math.max(slot, 0), buckets.length - 1)]
239
+ if (!bucket) return
240
+ bucket.pushes += 1
241
+ bucket.bytes += entry.size
242
+ }
243
+
244
+ const repoIds = await listRepoIds(store)
245
+ const read = await pooled(repoIds, options.concurrency ?? 8, async (repoId) => {
246
+ try {
247
+ const found = await store.get(indexKey(repoId))
248
+ if (!found) return { repoId, reason: 'no index.json' } as UnreadableRepo
249
+ const index = JSON.parse(new TextDecoder().decode(found.body)) as WalIndex
250
+ // The id in the key is the one the operator sees; an index that disagrees
251
+ // is a routing fault, and reporting it under either name would hide that.
252
+ if (index.repo_id !== repoId) {
253
+ return { repoId, reason: `index declares repo_id "${index.repo_id}"` } as UnreadableRepo
254
+ }
255
+ return usageOfIndex(index, window ?? undefined, window ? record : undefined)
256
+ } catch (error) {
257
+ return {
258
+ repoId,
259
+ reason: error instanceof Error ? error.message : String(error),
260
+ } as UnreadableRepo
261
+ }
262
+ })
263
+
264
+ const rows: RepoUsage[] = []
265
+ const unreadable: UnreadableRepo[] = []
266
+ for (const item of read) {
267
+ if ('reason' in item) unreadable.push(item)
268
+ else rows.push(item)
269
+ }
270
+
271
+ const report: UsageReport = {
272
+ generatedAt: now.toISOString(),
273
+ window: window
274
+ ? {
275
+ since: new Date(window.since).toISOString(),
276
+ until: new Date(window.until).toISOString(),
277
+ hours: options.sinceMs! / HOUR_MS,
278
+ bucketHours,
279
+ }
280
+ : null,
281
+ repos: rows.length,
282
+ bytes: rows.reduce((n, r) => n + r.bytes, 0),
283
+ bytesPendingDeletion: rows.reduce((n, r) => n + (r.deletionPending ? r.bytes : 0), 0),
284
+ liveBytes: rows.reduce((n, r) => n + r.liveBytes, 0),
285
+ entries: rows.reduce((n, r) => n + r.entries, 0),
286
+ pushes: rows.reduce((n, r) => n + r.pushes, 0),
287
+ pushesInWindow: rows.reduce((n, r) => n + r.pushesInWindow, 0),
288
+ bytesInWindow: rows.reduce((n, r) => n + r.bytesInWindow, 0),
289
+ largest: [...rows].sort(byBytesThenId),
290
+ buckets,
291
+ unreadable,
292
+ }
293
+ const top = options.top ?? 10
294
+ if (top > 0) report.largest = report.largest.slice(0, top)
295
+ return report
296
+ }
297
+
298
+ /** Bytes descending, id ascending — so equal-sized repos have a stable order. */
299
+ function byBytesThenId(a: RepoUsage, b: RepoUsage): number {
300
+ return b.bytes - a.bytes || a.repoId.localeCompare(b.repoId)
301
+ }
302
+
303
+ // ── Formatting ──────────────────────────────────────────────────────────────
304
+
305
+ const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] as const
306
+
307
+ /** Binary units, because that is what a bucket console reports. */
308
+ export function formatBytes(bytes: number): string {
309
+ let value = bytes
310
+ let unit = 0
311
+ while (value >= 1024 && unit < UNITS.length - 1) {
312
+ value /= 1024
313
+ unit += 1
314
+ }
315
+ return `${unit === 0 ? value : value.toFixed(value < 10 ? 1 : 0)} ${UNITS[unit]}`
316
+ }
317
+
318
+ /**
319
+ * `30m`, `24h`, `7d`, `2w` — and a bare number is hours.
320
+ *
321
+ * Deliberately not a date: an operator asking "what happened lately?" thinks in
322
+ * durations, and a window relative to now is the only one that stays correct
323
+ * between two runs of the command.
324
+ */
325
+ export function parseDuration(input: string): number {
326
+ const match = /^(\d+(?:\.\d+)?)\s*([mhdw]?)$/.exec(input.trim())
327
+ if (!match) throw new Error(`not a duration: ${JSON.stringify(input)} (try 24h, 7d, 30m)`)
328
+ const scale = { m: 60_000, h: HOUR_MS, d: 24 * HOUR_MS, w: 7 * 24 * HOUR_MS }
329
+ return Number(match[1]) * scale[(match[2] || 'h') as 'm' | 'h' | 'd' | 'w']
330
+ }
331
+
332
+ /** A bar scaled to the busiest bucket, so the shape is readable without a scale. */
333
+ function bar(value: number, max: number, width = 24): string {
334
+ if (max <= 0) return ''
335
+ return '#'.repeat(Math.max(value > 0 ? 1 : 0, Math.round((value / max) * width)))
336
+ }
337
+
338
+ export function formatUsage(report: UsageReport): string {
339
+ const lines: string[] = []
340
+ lines.push(
341
+ `${report.repos} ${report.repos === 1 ? 'repository' : 'repositories'}, ` +
342
+ `${formatBytes(report.bytes)} stored, ${report.entries} WAL entries, ` +
343
+ `${report.pushes} pushes`,
344
+ )
345
+ // Worth naming only when it is not the same number: the difference is
346
+ // storage being paid for that no restore reads.
347
+ if (report.liveBytes !== report.bytes) {
348
+ lines.push(
349
+ ` ${formatBytes(report.liveBytes)} live — ${formatBytes(report.bytes - report.liveBytes)} ` +
350
+ 'superseded, awaiting `walgit gc`',
351
+ )
352
+ }
353
+
354
+ if (report.bytesPendingDeletion > 0) {
355
+ lines.push(
356
+ ` ${formatBytes(report.bytesPendingDeletion)} belongs to repositories scheduled for deletion`,
357
+ )
358
+ }
359
+
360
+ if (report.largest.length > 0) {
361
+ lines.push('', 'Largest repositories')
362
+ const width = Math.max(...report.largest.map((r) => r.repoId.length))
363
+ for (const row of report.largest) {
364
+ lines.push(
365
+ ` ${row.repoId.padEnd(width)} ${formatBytes(row.bytes).padStart(9)} ` +
366
+ `${String(row.pushes).padStart(5)} ${row.pushes === 1 ? 'push ' : 'pushes'} ` +
367
+ `${row.refs} ${row.refs === 1 ? 'ref ' : 'refs'} ` +
368
+ `last push ${row.lastPush ?? 'never'}${row.deletionPending ? ' (deleting)' : ''}`,
369
+ )
370
+ }
371
+ }
372
+
373
+ if (report.window) {
374
+ const w = report.window
375
+ lines.push(
376
+ '',
377
+ `Pushes in the last ${w.hours}h: ${report.pushesInWindow} ` +
378
+ `(${formatBytes(report.bytesInWindow)}), by ${w.bucketHours}h`,
379
+ )
380
+ const max = Math.max(0, ...report.buckets.map((b) => b.pushes))
381
+ for (const bucket of report.buckets) {
382
+ lines.push(
383
+ ` ${bucket.start.slice(0, 16).replace('T', ' ')} ` +
384
+ `${String(bucket.pushes).padStart(4)} ${bar(bucket.pushes, max)}`.trimEnd(),
385
+ )
386
+ }
387
+ if (max === 0) lines.push(' (no pushes in this window)')
388
+ }
389
+
390
+ // Named, not counted: a prefix without a readable index is either an orphan
391
+ // left by a rejected first push or a routing fault, and both need the name.
392
+ if (report.unreadable.length > 0) {
393
+ lines.push('', 'Not counted')
394
+ for (const skipped of report.unreadable) {
395
+ lines.push(` ${skipped.repoId}: ${skipped.reason}`)
396
+ }
397
+ }
398
+
399
+ lines.push(
400
+ '',
401
+ 'Reads are not in the log and are not reported here — this counts pushes and storage only.',
402
+ )
403
+ return lines.join('\n')
404
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Does this disk agree with the log?
3
+ *
4
+ * Read-only, and that is the whole point. `sync.ts` answers the same question on
5
+ * every access and immediately repairs what it finds, which makes it useless for
6
+ * an operator asking "was this node serving the wrong thing?" — by the time the
7
+ * answer arrives the evidence is gone. This asks and does not touch.
8
+ *
9
+ * It reports four independent disagreements rather than one boolean, because
10
+ * they have different causes and different repairs:
11
+ *
12
+ * - **Diverged refs** — the disk and `index.json` name different oids for a
13
+ * ref, or one has a ref the other does not. Repaired by `reconcile`.
14
+ * - **Missing objects** — the log names an oid this repo does not have. The
15
+ * WAL has to be replayed; `reconcile` deliberately refuses to write such a
16
+ * ref, so a node in this state serves a stale ref rather than a broken one.
17
+ * - **Missing packs** — a WAL entry above `compaction_frontier` is not on
18
+ * disk. Usually the same fault as above, seen from the log's side; it can
19
+ * also stand alone, when the absent entry carried only objects some other
20
+ * entry also carries.
21
+ * - **A partial marker** — a materialize died partway. The refs may look
22
+ * perfect and the repo still be truncated, which is exactly why the marker
23
+ * exists and why it is checked here rather than inferred.
24
+ *
25
+ * Refs the CACHE has and the log does not are reported as divergence too. The
26
+ * log is the source of truth, so a local-only ref is not "extra" — it is a ref
27
+ * that will vanish on the next access, and an operator chasing "my branch
28
+ * disappeared" needs to see it named here.
29
+ */
30
+
31
+ import * as fs from 'node:fs'
32
+ import * as path from 'node:path'
33
+
34
+ import { absentEntries, isPartial } from './materialize'
35
+ import { localRefs, presentObjects } from './reconcile'
36
+ import type { ResolvedRepo } from './repo'
37
+ import type { ObjectStore } from './store'
38
+ import { loadIndex, type WalIndex } from './wal-index'
39
+
40
+ export interface RefDivergence {
41
+ ref: string
42
+ /** Oid on this disk, or `null` when the ref is only in the log. */
43
+ local: string | null
44
+ /** Oid in `index.json`, or `null` when the ref is only on this disk. */
45
+ log: string | null
46
+ }
47
+
48
+ export interface MissingPack {
49
+ seq: number
50
+ key: string
51
+ }
52
+
53
+ export interface VerifyReport {
54
+ repoId: string
55
+ dir: string
56
+ /** False when there is no bare repo here at all — a cold node, not a broken one. */
57
+ exists: boolean
58
+ /** A materialize died partway; the repo may be truncated however good the refs look. */
59
+ partial: boolean
60
+ seq: number
61
+ entries: number
62
+ compactionFrontier: number
63
+ diverged: RefDivergence[]
64
+ /** Refs the log names whose object this repo does not have. */
65
+ missingObjects: string[]
66
+ /** WAL entries above the frontier whose pack is absent from `objects/pack`. */
67
+ missingPacks: MissingPack[]
68
+ ok: boolean
69
+ }
70
+
71
+ /** True when the directory holds a git repository, without running git to find out. */
72
+ export function repoExists(dir: string): boolean {
73
+ return fs.existsSync(path.join(dir, 'HEAD'))
74
+ }
75
+
76
+ export async function verifyRepo(
77
+ store: ObjectStore,
78
+ repo: ResolvedRepo,
79
+ known?: WalIndex,
80
+ ): Promise<VerifyReport> {
81
+ const index = known ?? (await loadIndex(store, repo.repoId)).index
82
+ const base = {
83
+ repoId: repo.repoId,
84
+ dir: repo.dir,
85
+ seq: index.seq,
86
+ entries: index.entries.length,
87
+ compactionFrontier: index.compaction_frontier,
88
+ }
89
+
90
+ if (!repoExists(repo.dir)) {
91
+ // Not a failure of agreement — there is nothing here to disagree. An
92
+ // operator who wanted a repo here reads `exists: false` and materializes;
93
+ // one who is checking a node that never served this repo reads it and moves
94
+ // on. Reporting it as divergence would drown the real ones.
95
+ return {
96
+ ...base,
97
+ exists: false,
98
+ partial: false,
99
+ diverged: [],
100
+ missingObjects: [],
101
+ missingPacks: [],
102
+ ok: index.seq === 0,
103
+ }
104
+ }
105
+
106
+ const local = localRefs(repo.dir)
107
+ const desired = index.refs
108
+ const present = presentObjects(repo.dir, [...new Set(Object.values(desired))])
109
+
110
+ const diverged: RefDivergence[] = []
111
+ for (const ref of [...new Set([...Object.keys(local), ...Object.keys(desired)])].sort()) {
112
+ if (local[ref] !== desired[ref]) {
113
+ diverged.push({ ref, local: local[ref] ?? null, log: desired[ref] ?? null })
114
+ }
115
+ }
116
+
117
+ const missingObjects = Object.entries(desired)
118
+ .filter(([, oid]) => !present.has(oid))
119
+ .map(([ref]) => ref)
120
+ .sort()
121
+
122
+ // The same predicate materialize fetches by, not a second copy of it.
123
+ const missingPacks = absentEntries(repo.dir, index).map((entry) => ({
124
+ seq: entry.seq,
125
+ key: entry.key,
126
+ }))
127
+
128
+ const partial = isPartial(repo.dir)
129
+ return {
130
+ ...base,
131
+ exists: true,
132
+ partial,
133
+ diverged,
134
+ missingObjects,
135
+ missingPacks,
136
+ ok:
137
+ !partial && diverged.length === 0 && missingObjects.length === 0 && missingPacks.length === 0,
138
+ }
139
+ }
140
+
141
+ /** One operator-readable block. Every disagreement names the refs it is about. */
142
+ export function formatVerify(report: VerifyReport): string {
143
+ const lines: string[] = []
144
+ lines.push(
145
+ `${report.repoId}: seq ${report.seq}, ${report.entries} WAL ${
146
+ report.entries === 1 ? 'entry' : 'entries'
147
+ }, frontier ${report.compactionFrontier}`,
148
+ )
149
+ lines.push(` disk: ${report.dir}`)
150
+
151
+ if (!report.exists) {
152
+ lines.push(' no local repo — nothing cached here (materialize to build one)')
153
+ return lines.join('\n')
154
+ }
155
+ if (report.ok) {
156
+ lines.push(' OK — local state agrees with index.json')
157
+ return lines.join('\n')
158
+ }
159
+
160
+ if (report.partial) lines.push(' PARTIAL — a previous materialize did not finish')
161
+ for (const d of report.diverged) {
162
+ lines.push(` DIVERGED ${d.ref}: local ${d.local ?? '(absent)'} log ${d.log ?? '(absent)'}`)
163
+ }
164
+ for (const ref of report.missingObjects) {
165
+ lines.push(` MISSING OBJECT ${ref}: the log's oid is not in this repo`)
166
+ }
167
+ for (const pack of report.missingPacks) {
168
+ lines.push(` MISSING PACK seq ${pack.seq}: ${pack.key}`)
169
+ }
170
+ return lines.join('\n')
171
+ }