@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
@@ -27,19 +27,19 @@
27
27
  * grace period later.
28
28
  */
29
29
 
30
- import { spawnSync } from 'node:child_process'
31
30
  import * as fs from 'node:fs'
32
31
  import * as path from 'node:path'
33
32
 
34
- import { materialize, packBasename } from './materialize'
35
- import { sha256 } from './push'
33
+ import { gitOrThrow } from './git'
34
+ import { leaseKey, walKey } from './keys'
35
+ import { materialize, packBasename, packDirOf } from './materialize'
36
36
  import type { ResolvedRepo } from './repo'
37
37
  import type { ObjectStore } from './store'
38
38
  import { ulid } from './ulid'
39
39
  import {
40
40
  loadIndex,
41
+ sha256,
41
42
  updateIndex,
42
- walKey,
43
43
  type Tombstone,
44
44
  type WalEntry,
45
45
  type WalIndex,
@@ -89,10 +89,6 @@ export function isCompactionDue(index: WalIndex, threshold = configuredThreshold
89
89
 
90
90
  // ── The lease ───────────────────────────────────────────────────────────────
91
91
 
92
- export function leaseKey(repoId: string): string {
93
- return `repos/${repoId}/compaction.lease`
94
- }
95
-
96
92
  interface Lease {
97
93
  holder: string
98
94
  acquired: string
@@ -111,7 +107,7 @@ export type LeaseResult =
111
107
  /**
112
108
  * Take the per-repository compaction lease.
113
109
  *
114
- * The lease EXPIRES because the holder is a process on a machine Fly may stop
110
+ * The lease EXPIRES because the holder is a process in a container Cloudflare may stop
115
111
  * at any moment: a lease that only a graceful release could clear would wedge
116
112
  * compaction for a repository permanently, and the failure would present as
117
113
  * restores quietly getting slower forever. Stealing an expired lease is a
@@ -223,7 +219,7 @@ export async function compact(
223
219
  return { status: 'not-due', pending: pendingEntries(index).length }
224
220
  }
225
221
 
226
- const holder = opts.holder ?? `${process.env.FLY_MACHINE_ID ?? 'local'}:${process.pid}`
222
+ const holder = opts.holder ?? `${process.env.HOSTNAME ?? 'local'}:${process.pid}`
227
223
  const lease = await acquireLease(store, repo.repoId, {
228
224
  holder,
229
225
  now: now(),
@@ -239,10 +235,18 @@ export async function compact(
239
235
  // is why the snapshot is taken here and not re-read after.
240
236
  const supersedesThrough = index.seq
241
237
 
242
- const packDir = path.join(repo.dir, 'objects', 'pack')
243
- run('git', ['--git-dir', repo.dir, 'repack', '-adfq'])
244
-
245
- const packs = fs.readdirSync(packDir).filter((f) => f.endsWith('.pack'))
238
+ const packDir = packDirOf(repo.dir)
239
+ gitOrThrow(['--git-dir', repo.dir, 'repack', '-adfq'])
240
+
241
+ const onDisk = fs.readdirSync(packDir)
242
+ // A cruft pack is not a second copy of the repository — it is git's
243
+ // holding pen for UNREACHABLE objects, marked by a sibling `.mtimes`, and
244
+ // `git repack -adf` never writes one (it drops unreachable objects
245
+ // instead). One can still be lying here from a `git gc` that ran before
246
+ // this repo learned to refuse them, and counting it as a kept-back pack
247
+ // would make compaction refuse this repository forever.
248
+ const isCruft = (pack: string) => onDisk.includes(`${pack.replace(/\.pack$/, '')}.mtimes`)
249
+ const packs = onDisk.filter((f) => f.endsWith('.pack') && !isCruft(f))
246
250
  if (packs.length === 0) return { status: 'empty' }
247
251
  // `-a -d` collapses to exactly one pack. More than one means something on
248
252
  // this disk kept a pack back (a `.keep`), and uploading only part of the
@@ -256,9 +260,14 @@ export async function compact(
256
260
  const produced = packs[0]!
257
261
 
258
262
  const packPath = path.join(packDir, produced)
259
- const packBody = new Uint8Array(fs.readFileSync(packPath))
263
+ // The `Buffer` goes to the store as it is. A Node `Buffer` already IS a
264
+ // `Uint8Array`, so wrapping it in `new Uint8Array(…)` would change nothing
265
+ // about the value and allocate a second full copy of the repository — up to
266
+ // `WALGIT_MAX_REPO_BYTES` of it, which is the largest single allocation
267
+ // walgit makes and what sized the container.
268
+ const packBody = fs.readFileSync(packPath)
260
269
  const idxPath = packPath.replace(/\.pack$/, '.idx')
261
- const idxBody = fs.existsSync(idxPath) ? new Uint8Array(fs.readFileSync(idxPath)) : null
270
+ const idxBody = fs.existsSync(idxPath) ? fs.readFileSync(idxPath) : null
262
271
 
263
272
  const id = ulid(now().getTime())
264
273
  const key = walKey(repo.repoId, supersedesThrough + 1, id, 'pack')
@@ -352,10 +361,3 @@ function adoptLocally(packDir: string, produced: string, basename: string): void
352
361
  fs.rmSync(path.join(packDir, file), { force: true })
353
362
  }
354
363
  }
355
-
356
- function run(cmd: string, args: string[]): void {
357
- const res = spawnSync(cmd, args, { stdio: ['ignore', 'ignore', 'pipe'] })
358
- if (res.status !== 0) {
359
- throw new Error(`${cmd} ${args.join(' ')} failed: ${res.stderr?.toString().trim()}`)
360
- }
361
- }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Deleting a whole repository — the only thing in walgit that destroys data on
3
+ * purpose.
4
+ *
5
+ * Everything else that removes anything (`gc.ts`) removes only what is
6
+ * provably unreferenced. This removes what IS referenced, which is why it
7
+ * inherits that file's discipline rather than inventing a faster one:
8
+ *
9
+ * - **Deferred, not immediate.** The first call tombstones the repository by
10
+ * writing a `deletion` marker into `index.json`; nothing is removed until a
11
+ * later call finds that marker's `collect_after` in the past. A clone that
12
+ * read the index a moment before the request is still downloading the packs
13
+ * it names, and cutting it off fails it with a missing object — the silent
14
+ * failure mode docs/adr/0007 ranks as risk #2.
15
+ * - **Record first, objects second.** Collection deletes `index.json` before
16
+ * it deletes anything the index names. A crash between the two leaves
17
+ * unreferenced objects under the WAL prefix — which is exactly what
18
+ * `findOrphans` discovers and `collectGarbage` reclaims. The reverse order
19
+ * would leave an index naming objects that are gone, which is a broken
20
+ * repository rather than a recoverable one.
21
+ * - **Dry run by default.** This is the operator surface for destruction, so
22
+ * the safe direction is to print.
23
+ *
24
+ * It takes a repo id and nothing else. Deciding WHICH repositories should go —
25
+ * expiry — is a separate concern and a separate caller.
26
+ */
27
+
28
+ import * as fs from 'node:fs'
29
+
30
+ import type { ObjectStore } from './store'
31
+ import { indexKey, repoPrefix } from './keys'
32
+ import { loadIndex, updateIndex, type WalIndex } from './wal-index'
33
+
34
+ /**
35
+ * How long a repository sits tombstoned before its objects may be deleted.
36
+ *
37
+ * Its own knob rather than the collector's: compaction's grace covers the
38
+ * slowest restore of a live repository, while this covers a clone of a
39
+ * repository someone has decided to remove. The timescales are unrelated, and
40
+ * tying them together would mean tuning one to fix the other.
41
+ */
42
+ export const DEFAULT_DELETE_GRACE_MS = 60 * 60 * 1000
43
+
44
+ export function configuredDeleteGraceMs(env = process.env): number {
45
+ const raw = Number(env.WALGIT_DELETE_GRACE_MS)
46
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_DELETE_GRACE_MS
47
+ }
48
+
49
+ export type DeleteStatus =
50
+ /** Nothing under this repo's prefix and no index: there was nothing to do. */
51
+ | 'absent'
52
+ /** The marker was written (or would be); the grace period starts now. */
53
+ | 'tombstoned'
54
+ /** Already marked, still inside the grace period. Nothing was removed. */
55
+ | 'retained'
56
+ /** The grace period elapsed; the index and every object under it are gone. */
57
+ | 'collected'
58
+
59
+ export interface RetainedObject {
60
+ key: string
61
+ /** Why this object is still here — the question an operator arrives with. */
62
+ reason: string
63
+ }
64
+
65
+ export interface DeleteResult {
66
+ repoId: string
67
+ status: DeleteStatus
68
+ /** Keys deleted, or — under a dry run — the keys that would be. */
69
+ deleted: string[]
70
+ /** Keys deliberately kept, each with the reason it was kept. */
71
+ retained: RetainedObject[]
72
+ /** When the objects become collectable. Absent for `absent`. */
73
+ collectAfter?: string
74
+ /** The cached bare repo removed from disk, when one was named and existed. */
75
+ cacheRemoved?: string
76
+ dryRun: boolean
77
+ }
78
+
79
+ export interface DeleteOptions {
80
+ now?: () => Date
81
+ graceMs?: number
82
+ /**
83
+ * Nothing is removed and no marker is written unless this is false. Dry run
84
+ * is the default so `--yes` is a word the operator has to type.
85
+ */
86
+ dryRun?: boolean
87
+ /** The bare repo on disk to remove once the log has let go of it. */
88
+ dir?: string
89
+ }
90
+
91
+ /**
92
+ * Schedule a repository for deletion, or — once its grace period has elapsed —
93
+ * carry that deletion out.
94
+ *
95
+ * Idempotent in both halves: asking twice inside the grace period does not
96
+ * move `collect_after`, and asking twice after collection reports `absent`.
97
+ */
98
+ export async function deleteRepo(
99
+ store: ObjectStore,
100
+ repoId: string,
101
+ opts: DeleteOptions = {},
102
+ ): Promise<DeleteResult> {
103
+ const now = (opts.now ?? (() => new Date()))()
104
+ const graceMs = opts.graceMs ?? configuredDeleteGraceMs()
105
+ const dryRun = opts.dryRun !== false
106
+
107
+ const [{ index, etag }, keys] = await Promise.all([
108
+ loadIndex(store, repoId),
109
+ store.list(repoPrefix(repoId)),
110
+ ])
111
+
112
+ // No index and nothing under the prefix: there is no repository here. This
113
+ // is a no-op rather than an error because the caller that will drive this —
114
+ // expiry — races with an operator doing the same thing by hand.
115
+ if (etag === null && keys.length === 0) {
116
+ return { repoId, status: 'absent', deleted: [], retained: [], dryRun }
117
+ }
118
+
119
+ // Objects without an index are already orphans by `orphans.ts`'s definition,
120
+ // and reclaiming those is the collector's job, not this one's. Writing a
121
+ // marker here would resurrect an `index.json` for a repository that has
122
+ // none — the opposite of what was asked for.
123
+ if (etag === null) {
124
+ return {
125
+ repoId,
126
+ status: 'absent',
127
+ deleted: [],
128
+ retained: keys.map((key) => ({
129
+ key,
130
+ reason: 'no index.json — already an orphan, reclaimed by `walgit gc`',
131
+ })),
132
+ dryRun,
133
+ }
134
+ }
135
+
136
+ const existing = index.deletion
137
+ if (!existing) {
138
+ const collectAfter = new Date(now.getTime() + graceMs).toISOString()
139
+ if (!dryRun) {
140
+ const committed = await updateIndex(
141
+ store,
142
+ repoId,
143
+ (current): WalIndex => ({
144
+ ...current,
145
+ // Re-read inside the mutation: a delete that raced another one must
146
+ // keep the FIRST request's deadline, never restart the clock.
147
+ deletion: current.deletion ?? {
148
+ requested_at: now.toISOString(),
149
+ collect_after: collectAfter,
150
+ },
151
+ }),
152
+ )
153
+ if (!committed.ok) {
154
+ throw new Error(
155
+ `walgit: delete for ${repoId} could not update the index; nothing was changed`,
156
+ )
157
+ }
158
+ return {
159
+ repoId,
160
+ status: 'tombstoned',
161
+ deleted: [],
162
+ retained: keys.map((key) => ({
163
+ key,
164
+ reason: `scheduled for deletion after ${committed.index.deletion?.collect_after}`,
165
+ })),
166
+ collectAfter: committed.index.deletion?.collect_after,
167
+ dryRun,
168
+ }
169
+ }
170
+ return {
171
+ repoId,
172
+ status: 'tombstoned',
173
+ deleted: [],
174
+ retained: keys.map((key) => ({
175
+ key,
176
+ reason: `would be scheduled for deletion after ${collectAfter}`,
177
+ })),
178
+ collectAfter,
179
+ dryRun,
180
+ }
181
+ }
182
+
183
+ if (Date.parse(existing.collect_after) > now.getTime()) {
184
+ return {
185
+ repoId,
186
+ status: 'retained',
187
+ deleted: [],
188
+ retained: keys.map((key) => ({
189
+ key,
190
+ reason: `inside the deletion grace period until ${existing.collect_after}`,
191
+ })),
192
+ collectAfter: existing.collect_after,
193
+ dryRun,
194
+ }
195
+ }
196
+
197
+ if (dryRun) {
198
+ return {
199
+ repoId,
200
+ status: 'collected',
201
+ deleted: keys,
202
+ retained: [],
203
+ collectAfter: existing.collect_after,
204
+ dryRun,
205
+ }
206
+ }
207
+
208
+ // The record goes first. From here on the objects are unreferenced, so a
209
+ // crash at any point below leaves orphans the collector reclaims — never an
210
+ // index naming an object that is gone.
211
+ await store.delete(indexKey(repoId))
212
+ const deleted = [indexKey(repoId)]
213
+ for (const key of keys) {
214
+ if (key === indexKey(repoId)) continue
215
+ await store.delete(key)
216
+ deleted.push(key)
217
+ }
218
+
219
+ // The disk is a cache and the log has just stopped describing it, so this is
220
+ // last and its failure is not fatal to the deletion: a cache left behind is
221
+ // reclaimable, whereas a half-deleted log is not.
222
+ let cacheRemoved: string | undefined
223
+ if (opts.dir && fs.existsSync(opts.dir)) {
224
+ fs.rmSync(opts.dir, { recursive: true, force: true })
225
+ cacheRemoved = opts.dir
226
+ }
227
+
228
+ return {
229
+ repoId,
230
+ status: 'collected',
231
+ deleted,
232
+ retained: [],
233
+ collectAfter: existing.collect_after,
234
+ cacheRemoved,
235
+ dryRun,
236
+ }
237
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Expiry — collecting repositories nobody has pushed to for a while.
3
+ *
4
+ * On the free tier this is the ONLY removal path, and it is what lets the
5
+ * service promise append-only refs without unbounded storage: nothing can ever
6
+ * be destroyed inside the window, and everything leaves at the end of it.
7
+ *
8
+ * Idle means the time of the LAST PUSH, never the last access:
9
+ *
10
+ * - It is free. The most recent WAL entry's `ts` is already in `index.json`,
11
+ * so the signal costs no write and no instrumentation.
12
+ * - It cannot be gamed. Recording a last-access would mean a write on every
13
+ * clone, through an endpoint deliberately left unauthenticated — a daily
14
+ * `git clone` from a cron job could then pin any repository alive forever.
15
+ * - It is the promise `GET /` already makes, from the same environment
16
+ * variable this file reads: "deleted N hours after its LAST PUSH. Cloning
17
+ * does not extend it; pushing does."
18
+ *
19
+ * The predicate below is the dangerous part of walgit, because its failure is
20
+ * silent: over-retaining costs storage, and under-retaining deletes somebody's
21
+ * work with no error anywhere. So every branch it cannot prove resolves toward
22
+ * RETAIN — an index with no entries is not "infinitely old", and a timestamp
23
+ * that will not parse is not "long ago". Deciding is all this file does; the
24
+ * removal itself is `delete-repo.ts`, and what runs this on a timer belongs to
25
+ * the deployment, not here.
26
+ */
27
+
28
+ import { deleteRepo, type DeleteResult } from './delete-repo'
29
+ import type { ObjectStore } from './store'
30
+ import { listRepoIds } from './keys'
31
+ import { loadIndex, type WalIndex } from './wal-index'
32
+
33
+ /**
34
+ * Expiry is off unless a window is configured. Absent means "this instance
35
+ * keeps repositories forever", which is also what makes `GET /` stay silent
36
+ * about a retention window it does not enforce — the same variable drives both.
37
+ */
38
+ export function configuredExpiryMs(env = process.env): number | null {
39
+ const hours = Number(env.WALGIT_RETENTION_HOURS)
40
+ if (!Number.isFinite(hours) || hours <= 0) return null
41
+ return hours * 60 * 60 * 1000
42
+ }
43
+
44
+ export type ExpiryVerdict = 'collect' | 'retain'
45
+
46
+ export interface ExpiryDecision {
47
+ verdict: ExpiryVerdict
48
+ /** Why. On a retention this is the question an operator arrives with. */
49
+ reason: string
50
+ /** The signal, when there was a usable one. */
51
+ lastPushAt?: string
52
+ idleMs?: number
53
+ }
54
+
55
+ /**
56
+ * The most recent WAL entry's timestamp, or null when the index carries none
57
+ * that parses.
58
+ *
59
+ * Every entry counts, not only `kind: 'push'`. A compaction is only ever
60
+ * produced BY a push crossing the entry threshold, so it can never be newer
61
+ * than the push that caused it in any way that matters — and after `gc` has
62
+ * removed superseded entries, a compaction entry may be the only record left of
63
+ * when the repository was last written to. Filtering it out would date a busy
64
+ * repository by an entry that no longer exists, which is the under-retaining
65
+ * direction.
66
+ */
67
+ export function lastWriteAt(index: WalIndex): string | null {
68
+ let newest: { ts: string; at: number } | null = null
69
+ for (const entry of index.entries ?? []) {
70
+ const at = Date.parse(entry.ts)
71
+ // An unparseable timestamp is skipped rather than treated as epoch zero:
72
+ // zero would read as ancient and take the repository with it.
73
+ if (!Number.isFinite(at)) continue
74
+ if (!newest || at > newest.at) newest = { ts: entry.ts, at }
75
+ }
76
+ return newest?.ts ?? null
77
+ }
78
+
79
+ export interface DecideOptions {
80
+ now: Date
81
+ /** Null means expiry is not configured, so nothing is ever collected. */
82
+ windowMs: number | null
83
+ }
84
+
85
+ /**
86
+ * Decide one repository's fate. Pure — no store, no clock, no environment — so
87
+ * the edge cases that matter can be tested directly rather than through a
88
+ * sweep that would hide them.
89
+ */
90
+ export function decideExpiry(index: WalIndex | null, opts: DecideOptions): ExpiryDecision {
91
+ const { now, windowMs } = opts
92
+
93
+ if (windowMs === null) {
94
+ return { verdict: 'retain', reason: 'expiry is not configured (WALGIT_RETENTION_HOURS unset)' }
95
+ }
96
+
97
+ // No index at all. Objects may still sit under the prefix, but they are
98
+ // orphans by `orphans.ts`'s definition and reclaiming those is `gc`'s job;
99
+ // resurrecting an index.json here to tombstone it would be worse.
100
+ if (!index) {
101
+ return { verdict: 'retain', reason: 'no index.json — nothing here for expiry to date' }
102
+ }
103
+
104
+ if (index.deletion) {
105
+ // Already tombstoned, by an operator or by an earlier sweep. The decision
106
+ // has been made; all that is left is whether its grace period has run out.
107
+ // Handing it back to `deleteRepo` once it has is what finishes the job —
108
+ // reporting "already scheduled" forever would leave every expired
109
+ // repository tombstoned and none of them collected.
110
+ const due = Date.parse(index.deletion.collect_after)
111
+ if (Number.isFinite(due) && due <= now.getTime()) {
112
+ return {
113
+ verdict: 'collect',
114
+ reason: `deletion grace period elapsed at ${index.deletion.collect_after}`,
115
+ }
116
+ }
117
+ return {
118
+ verdict: 'retain',
119
+ reason: `already scheduled for deletion after ${index.deletion.collect_after}`,
120
+ }
121
+ }
122
+
123
+ const lastPushAt = lastWriteAt(index)
124
+ if (lastPushAt === null) {
125
+ // An index with no entries, or with none whose `ts` parses. It is either
126
+ // brand new (created by a push whose pack is landing right now) or damaged.
127
+ // Both are reasons to leave it alone.
128
+ return {
129
+ verdict: 'retain',
130
+ reason: 'no entry carries a parseable timestamp — nothing to date the repository by',
131
+ }
132
+ }
133
+
134
+ const idleMs = now.getTime() - Date.parse(lastPushAt)
135
+
136
+ // A timestamp in the future is clock skew or a corrupted index, never
137
+ // staleness. Reading it as "idle for a negative time" happens to be safe, but
138
+ // saying so out loud is what makes the skew visible to whoever has to fix it.
139
+ if (idleMs < 0) {
140
+ return {
141
+ verdict: 'retain',
142
+ reason: `last push ${lastPushAt} is in the future — clock skew, refusing to judge`,
143
+ lastPushAt,
144
+ idleMs,
145
+ }
146
+ }
147
+
148
+ if (idleMs < windowMs) {
149
+ return {
150
+ verdict: 'retain',
151
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, inside the ${describe(windowMs)} window`,
152
+ lastPushAt,
153
+ idleMs,
154
+ }
155
+ }
156
+
157
+ return {
158
+ verdict: 'collect',
159
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${describe(windowMs)} window`,
160
+ lastPushAt,
161
+ idleMs,
162
+ }
163
+ }
164
+
165
+ function describe(ms: number): string {
166
+ const hours = ms / 3_600_000
167
+ if (hours >= 1) return `${Math.round(hours * 10) / 10}h`
168
+ return `${Math.round(ms / 60_000)}m`
169
+ }
170
+
171
+ /** One repository's outcome, as the sweep reports it. */
172
+ export interface ExpiryOutcome {
173
+ repoId: string
174
+ decision: ExpiryDecision
175
+ /** Present only for a collected repository: what `deleteRepo` did. */
176
+ deletion?: DeleteResult
177
+ }
178
+
179
+ export interface ExpireResult {
180
+ /** Repositories the sweep acted on — tombstoned, or collected outright. */
181
+ collected: ExpiryOutcome[]
182
+ /** Repositories deliberately kept, each carrying the reason it was kept. */
183
+ retained: ExpiryOutcome[]
184
+ windowMs: number | null
185
+ dryRun: boolean
186
+ }
187
+
188
+ export interface ExpireOptions {
189
+ now?: () => Date
190
+ /** Null (the default when unconfigured) sweeps nothing. */
191
+ windowMs?: number | null
192
+ dryRun?: boolean
193
+ /** Only consider these repositories, instead of every one in the store. */
194
+ repoIds?: readonly string[]
195
+ /** Where cached bare repos live, so a collection can drop the disk copy too. */
196
+ reposDir?: string
197
+ /** How long a collected repository sits tombstoned. `deleteRepo`'s default otherwise. */
198
+ graceMs?: number
199
+ }
200
+
201
+ /**
202
+ * Sweep the store and collect what has gone idle.
203
+ *
204
+ * Dry run by default, like `gc` and `delete`: this is the operator surface for
205
+ * destruction, and looking before anything goes should never require care.
206
+ * Collection is delegated to `deleteRepo`, so an expired repository gets the
207
+ * same deferred, tombstone-first treatment as one deleted by hand — the clone
208
+ * that read the index a second ago still finishes.
209
+ */
210
+ export async function expireRepos(
211
+ store: ObjectStore,
212
+ opts: ExpireOptions = {},
213
+ ): Promise<ExpireResult> {
214
+ const now = opts.now ?? (() => new Date())
215
+ const windowMs = opts.windowMs ?? null
216
+ const dryRun = opts.dryRun !== false
217
+
218
+ const result: ExpireResult = { collected: [], retained: [], windowMs, dryRun }
219
+
220
+ // Unconfigured stops before the LIST, not after it: an instance that does not
221
+ // expire should not be walking its bucket on a timer either.
222
+ if (windowMs === null) return result
223
+
224
+ // `usage.ts` already knows how to enumerate repositories cheaply — one
225
+ // delimited LIST rather than a walk of every packfile. A repository it names
226
+ // that has no `index.json` is retained by the predicate, not deleted.
227
+ const repoIds = opts.repoIds ?? (await listRepoIds(store))
228
+ for (const repoId of repoIds) {
229
+ const loaded = await loadIndex(store, repoId)
230
+ const index = loaded.etag === null ? null : loaded.index
231
+ const decision = decideExpiry(index, { now: now(), windowMs })
232
+
233
+ if (decision.verdict === 'retain') {
234
+ result.retained.push({ repoId, decision })
235
+ continue
236
+ }
237
+
238
+ const deletion = await deleteRepo(store, repoId, {
239
+ now,
240
+ dryRun,
241
+ graceMs: opts.graceMs,
242
+ dir: opts.reposDir ? `${opts.reposDir}/${repoId}.git` : undefined,
243
+ })
244
+ result.collected.push({ repoId, decision, deletion })
245
+ }
246
+
247
+ return result
248
+ }
@@ -21,9 +21,9 @@
21
21
  */
22
22
 
23
23
  import { configuredGraceMs } from './compact'
24
+ import { siblingIdx, walKeyUploadedAt } from './keys'
24
25
  import { findOrphans } from './orphans'
25
26
  import type { ObjectStore } from './store'
26
- import { ulidTime } from './ulid'
27
27
  import { loadIndex, updateIndex, type WalIndex } from './wal-index'
28
28
 
29
29
  export interface GcResult {
@@ -44,24 +44,16 @@ export interface GcOptions {
44
44
  dryRun?: boolean
45
45
  }
46
46
 
47
- /** The `.idx` uploaded beside a pack. Deleted with it, never separately. */
48
- function siblingIdx(key: string): string {
49
- return key.replace(/\.pack$/, '.idx')
50
- }
51
-
52
47
  /**
53
- * The upload time encoded in a WAL key's ULID, or null when the key does not
54
- * carry one. Null is the "leave it alone" answer, not the "it is ancient" one.
48
+ * How old a WAL object is, from the ULID `keys.ts` put in its key.
49
+ *
50
+ * Null is the "leave it alone" answer, not the "it is ancient" one: a key this
51
+ * process cannot date is a key it will not collect. The parse itself is
52
+ * `keys.ts`'s — this file owns the policy, not the format.
55
53
  */
56
54
  export function keyAgeMs(key: string, now: number): number | null {
57
- const stem =
58
- key
59
- .split('/')
60
- .pop()
61
- ?.replace(/\.(pack|idx)$/, '') ?? ''
62
- const id = stem.includes('-') ? stem.slice(stem.indexOf('-') + 1) : ''
63
- const time = id ? ulidTime(id) : null
64
- return time === null ? null : now - time
55
+ const uploadedAt = walKeyUploadedAt(key)
56
+ return uploadedAt === null ? null : now - uploadedAt
65
57
  }
66
58
 
67
59
  /**
@@ -55,6 +55,15 @@ export async function runGitHttpBackend(req: BackendRequest): Promise<Response>
55
55
  stderr: 'pipe',
56
56
  })
57
57
 
58
+ // git's own diagnostics, and every hook's. Drained rather than dropped for
59
+ // two reasons that are really one: a 64 KiB pipe nobody reads eventually
60
+ // blocks the child mid-push, and a refusal reached at `reference-transaction`
61
+ // has nowhere else to go. Only `pre-receive` output rides the sideband to the
62
+ // client — a `prepared` hook that exits non-zero makes git die with "ref
63
+ // updates aborted by hook", and its stderr is the CGI's, not the connection's.
64
+ // So this is the one place a publish-time refusal is readable at all.
65
+ void drainToStderr(child.stderr)
66
+
58
67
  const { headers, rest } = await readCgiHeaders(child.stdout)
59
68
  const status = Number(headers.get('status')?.slice(0, 3) ?? 200)
60
69
  headers.delete('status')
@@ -62,6 +71,26 @@ export async function runGitHttpBackend(req: BackendRequest): Promise<Response>
62
71
  return new Response(concatStream(rest, child.stdout), { status, headers })
63
72
  }
64
73
 
74
+ /**
75
+ * Copy the child's stderr to ours, and swallow every failure doing it.
76
+ *
77
+ * Deliberately not awaited: the response streams, and a push is a long request
78
+ * whose diagnostics arrive throughout it. A failure here is a child that is
79
+ * already gone, which leaves nothing to log and must never touch the push.
80
+ */
81
+ async function drainToStderr(stream: ReadableStream<Uint8Array>): Promise<void> {
82
+ const reader = stream.getReader()
83
+ try {
84
+ for (;;) {
85
+ const { done, value } = await reader.read()
86
+ if (done) return
87
+ process.stderr.write(value)
88
+ }
89
+ } catch {
90
+ return
91
+ }
92
+ }
93
+
65
94
  /** Read up to the CGI header terminator, returning the leftover first chunk. */
66
95
  async function readCgiHeaders(
67
96
  stdout: ReadableStream<Uint8Array>,