@zabaca/zbc 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +1 -1
  2. package/templates/CLAUDE.md +5 -0
  3. package/templates/apps/walgit/CONTEXT.md +5 -1
  4. package/templates/apps/walgit/README.md +159 -24
  5. package/templates/apps/walgit/package.json +2 -2
  6. package/templates/apps/walgit/registry.json +1 -1
  7. package/templates/apps/walgit/shared/browse.ts +18 -4
  8. package/templates/apps/walgit/shared/capabilities.ts +28 -3
  9. package/templates/apps/walgit/shared/container-env.ts +41 -2
  10. package/templates/apps/walgit/shared/container-lifecycle.ts +239 -0
  11. package/templates/apps/walgit/shared/container-snapshot.ts +219 -0
  12. package/templates/apps/walgit/shared/edge-refs.ts +612 -0
  13. package/templates/apps/walgit/{src → shared}/instructions.ts +8 -4
  14. package/templates/apps/walgit/shared/keys.ts +17 -0
  15. package/templates/apps/walgit/shared/landing.ts +10 -3
  16. package/templates/apps/walgit/shared/llms.ts +14 -5
  17. package/templates/apps/walgit/shared/policy.ts +1 -1
  18. package/templates/apps/walgit/shared/protocol.ts +35 -0
  19. package/templates/apps/walgit/shared/sleep-after.ts +44 -0
  20. package/templates/apps/walgit/shared/wal-index.ts +22 -1
  21. package/templates/apps/walgit/src/boot-residue.ts +58 -0
  22. package/templates/apps/walgit/src/cache.ts +9 -0
  23. package/templates/apps/walgit/src/cli.ts +39 -4
  24. package/templates/apps/walgit/src/delete-repo.ts +58 -9
  25. package/templates/apps/walgit/src/edge-refs.ts +148 -0
  26. package/templates/apps/walgit/src/expire.ts +75 -7
  27. package/templates/apps/walgit/src/hook-main.ts +2 -0
  28. package/templates/apps/walgit/src/http.ts +17 -4
  29. package/templates/apps/walgit/src/materialize.ts +34 -15
  30. package/templates/apps/walgit/src/push.ts +34 -8
  31. package/templates/apps/walgit/src/reconcile.ts +6 -1
  32. package/templates/apps/walgit/src/server.ts +69 -8
  33. package/templates/apps/walgit/src/sync.ts +10 -2
  34. package/templates/apps/walgit/worker/container-binding.ts +104 -0
  35. package/templates/apps/walgit/worker/durable-container.ts +786 -0
  36. package/templates/apps/walgit/worker/events-do.ts +16 -12
  37. package/templates/apps/walgit/worker/index.ts +235 -17
  38. package/templates/apps/walgit/worker/mcp.ts +9 -4
  39. package/templates/apps/walgit/wrangler.jsonc +44 -33
  40. package/templates/claude/settings.json +8 -0
  41. package/templates/infra/modules/cloudflare/index.ts +9 -0
  42. package/templates/infra/modules/d1/index.ts +30 -4
  43. package/templates/infra/modules/d1/registry.json +1 -1
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  import { deleteRepo, type DeleteResult } from './delete-repo'
29
+ import { capabilitiesFrom } from '../shared/capabilities'
29
30
  import type { ObjectStore } from '../shared/store'
30
31
  import { listRepoIds } from '../shared/keys'
31
32
  import { loadIndex, type WalIndex } from '../shared/wal-index'
@@ -41,6 +42,19 @@ export function configuredExpiryMs(env = process.env): number | null {
41
42
  return hours * 60 * 60 * 1000
42
43
  }
43
44
 
45
+ /**
46
+ * A claimed repository's window, or `null` when a claim buys no extra time.
47
+ *
48
+ * Read through `capabilitiesFrom` rather than straight off the variable, because
49
+ * the rules for when it applies — names can be claimed, expiry is on, and it is
50
+ * longer than the base window — are the ones `GET /` states it under, and a
51
+ * second reading here is how the page and the sweeper would come to disagree.
52
+ */
53
+ export function configuredClaimedExpiryMs(env = process.env): number | null {
54
+ const hours = capabilitiesFrom(env).claimedRetentionHours
55
+ return hours === null ? null : hours * 60 * 60 * 1000
56
+ }
57
+
44
58
  export type ExpiryVerdict = 'collect' | 'retain'
45
59
 
46
60
  export interface ExpiryDecision {
@@ -80,6 +94,19 @@ export interface DecideOptions {
80
94
  now: Date
81
95
  /** Null means expiry is not configured, so nothing is ever collected. */
82
96
  windowMs: number | null
97
+ /**
98
+ * The window for a repository with a Signer List (`index.claim`), when a claim
99
+ * earns a longer one. Null or absent: every repository gets `windowMs`.
100
+ */
101
+ claimedWindowMs?: number | null
102
+ /**
103
+ * Finish deletions only: collect what is already tombstoned and past its
104
+ * grace, and tombstone nothing new. The second of the deployment's two daily
105
+ * sweeps runs this way (`wrangler.jsonc`), so that a repository tombstoned by
106
+ * the first is collected a grace period later rather than a day later — and
107
+ * so that nothing it tombstones itself sits waiting a day for the next one.
108
+ */
109
+ collectOnly?: boolean
83
110
  }
84
111
 
85
112
  /**
@@ -88,9 +115,14 @@ export interface DecideOptions {
88
115
  * sweep that would hide them.
89
116
  */
90
117
  export function decideExpiry(index: WalIndex | null, opts: DecideOptions): ExpiryDecision {
91
- const { now, windowMs } = opts
118
+ const { now, collectOnly = false } = opts
119
+ // Which window this repository is judged by. Decided before anything else so
120
+ // that every reason below names the window that was actually applied.
121
+ const claimed = opts.claimedWindowMs != null && index?.claim !== undefined
122
+ const windowMs = claimed ? (opts.claimedWindowMs ?? null) : opts.windowMs
123
+ const which = claimed ? 'claimed ' : ''
92
124
 
93
- if (windowMs === null) {
125
+ if (opts.windowMs === null || windowMs === null) {
94
126
  return { verdict: 'retain', reason: 'expiry is not configured (WALGIT_RETENTION_HOURS unset)' }
95
127
  }
96
128
 
@@ -148,7 +180,16 @@ export function decideExpiry(index: WalIndex | null, opts: DecideOptions): Expir
148
180
  if (idleMs < windowMs) {
149
181
  return {
150
182
  verdict: 'retain',
151
- reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, inside the ${describe(windowMs)} window`,
183
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, inside the ${which}${describe(windowMs)} window`,
184
+ lastPushAt,
185
+ idleMs,
186
+ }
187
+ }
188
+
189
+ if (collectOnly) {
190
+ return {
191
+ verdict: 'retain',
192
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${which}${describe(windowMs)} window — left for the next full sweep to tombstone`,
152
193
  lastPushAt,
153
194
  idleMs,
154
195
  }
@@ -156,7 +197,7 @@ export function decideExpiry(index: WalIndex | null, opts: DecideOptions): Expir
156
197
 
157
198
  return {
158
199
  verdict: 'collect',
159
- reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${describe(windowMs)} window`,
200
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${which}${describe(windowMs)} window`,
160
201
  lastPushAt,
161
202
  idleMs,
162
203
  }
@@ -172,7 +213,7 @@ function describe(ms: number): string {
172
213
  export interface ExpiryOutcome {
173
214
  repoId: string
174
215
  decision: ExpiryDecision
175
- /** Present only for a collected repository: what `deleteRepo` did. */
216
+ /** What `deleteRepo` did — present when it was asked, so also on a superseded one. */
176
217
  deletion?: DeleteResult
177
218
  }
178
219
 
@@ -182,6 +223,8 @@ export interface ExpireResult {
182
223
  /** Repositories deliberately kept, each carrying the reason it was kept. */
183
224
  retained: ExpiryOutcome[]
184
225
  windowMs: number | null
226
+ claimedWindowMs: number | null
227
+ collectOnly: boolean
185
228
  dryRun: boolean
186
229
  }
187
230
 
@@ -189,6 +232,10 @@ export interface ExpireOptions {
189
232
  now?: () => Date
190
233
  /** Null (the default when unconfigured) sweeps nothing. */
191
234
  windowMs?: number | null
235
+ /** A claimed repository's window — see `DecideOptions.claimedWindowMs`. */
236
+ claimedWindowMs?: number | null
237
+ /** Collect tombstoned repositories only — see `DecideOptions.collectOnly`. */
238
+ collectOnly?: boolean
192
239
  dryRun?: boolean
193
240
  /** Only consider these repositories, instead of every one in the store. */
194
241
  repoIds?: readonly string[]
@@ -213,9 +260,18 @@ export async function expireRepos(
213
260
  ): Promise<ExpireResult> {
214
261
  const now = opts.now ?? (() => new Date())
215
262
  const windowMs = opts.windowMs ?? null
263
+ const claimedWindowMs = opts.claimedWindowMs ?? null
264
+ const collectOnly = opts.collectOnly ?? false
216
265
  const dryRun = opts.dryRun !== false
217
266
 
218
- const result: ExpireResult = { collected: [], retained: [], windowMs, dryRun }
267
+ const result: ExpireResult = {
268
+ collected: [],
269
+ retained: [],
270
+ windowMs,
271
+ claimedWindowMs,
272
+ collectOnly,
273
+ dryRun,
274
+ }
219
275
 
220
276
  // Unconfigured stops before the LIST, not after it: an instance that does not
221
277
  // expire should not be walking its bucket on a timer either.
@@ -228,7 +284,7 @@ export async function expireRepos(
228
284
  for (const repoId of repoIds) {
229
285
  const loaded = await loadIndex(store, repoId)
230
286
  const index = loaded.etag === null ? null : loaded.index
231
- const decision = decideExpiry(index, { now: now(), windowMs })
287
+ const decision = decideExpiry(index, { now: now(), windowMs, claimedWindowMs, collectOnly })
232
288
 
233
289
  if (decision.verdict === 'retain') {
234
290
  result.retained.push({ repoId, decision })
@@ -238,9 +294,21 @@ export async function expireRepos(
238
294
  const deletion = await deleteRepo(store, repoId, {
239
295
  now,
240
296
  dryRun,
297
+ by: 'expiry',
298
+ // Re-judged on the Index the mark would land on, so a push between this
299
+ // read and that write keeps the repository rather than marking it.
300
+ stillDue: (current) =>
301
+ decideExpiry(current, { now: now(), windowMs, claimedWindowMs, collectOnly }).verdict ===
302
+ 'collect',
241
303
  graceMs: opts.graceMs,
242
304
  dir: opts.reposDir ? `${opts.reposDir}/${repoId}.git` : undefined,
243
305
  })
306
+ // A push between the decision and the write: kept, and reported as kept.
307
+ if (deletion.status === 'superseded') {
308
+ const reason = deletion.retained[0]?.reason ?? 'the repository moved under the sweep'
309
+ result.retained.push({ repoId, decision: { verdict: 'retain', reason }, deletion })
310
+ continue
311
+ }
244
312
  result.collected.push({ repoId, decision, deletion })
245
313
  }
246
314
 
@@ -418,6 +418,8 @@ function publishRefusal(result: Extract<PublishResult, { ok: false }>): string {
418
418
  return result.message
419
419
  case 'contended':
420
420
  return 'walgit: the write-ahead log stayed contended — retry the push'
421
+ case 'deleting':
422
+ return 'walgit: this repository is being deleted — push to a new name'
421
423
  }
422
424
  }
423
425
 
@@ -42,7 +42,7 @@ import {
42
42
  type ContainerRejectKind,
43
43
  } from '../shared/protocol'
44
44
  import { emptyReadResponse } from './empty-read'
45
- import { renderInstructions } from './instructions'
45
+ import { renderInstructions } from '../shared/instructions'
46
46
  import { acceptedNonces, readAllowed, readChallengeNonce, renderReadChallenge } from './private'
47
47
  import type { ProposalListing } from './proposals'
48
48
  import { countsNewRepos, createSourceLimiter, rateLimitsEnforced, rateLimitsOf } from './rate-limit'
@@ -67,6 +67,9 @@ export type BackendRequest = {
67
67
  env?: Record<string, string>
68
68
  }
69
69
 
70
+ /** How one expiry sweep runs — see `decideExpiry`'s `collectOnly`. */
71
+ export type SweepOptions = { collectOnly: boolean }
72
+
70
73
  export type HttpHandlerDeps = {
71
74
  reposDir: string
72
75
  /** Accepted credentials. A request must present one of these. */
@@ -110,7 +113,7 @@ export type HttpHandlerDeps = {
110
113
  * is exactly when there are idle repositories to collect. The deployment's
111
114
  * Cron Trigger wakes it instead (`worker/index.ts`).
112
115
  */
113
- sweep?: () => Promise<unknown>
116
+ sweep?: (opts: SweepOptions) => Promise<unknown>
114
117
  /**
115
118
  * The Index's ref state for one repository — what a ref-event subscriber's
116
119
  * handshake is answered with (`worker/events-do.ts`).
@@ -287,6 +290,8 @@ export type BrowseReads = {
287
290
  export type BrowseIndex = {
288
291
  refs: Record<string, string>
289
292
  lastPush: string | null
293
+ /** The repository has a Signer List, so a claimed window may apply. */
294
+ claimed?: boolean
290
295
  }
291
296
 
292
297
  /** Verify a `walgit-read` signature over a message; name the key, or `null`. */
@@ -577,7 +582,13 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
577
582
  .toSorted()
578
583
  .map((name) => ({ name, oid: index.refs[name]! }))
579
584
  const head = defaultBranch(index.refs)
580
- const common = { repo: resolved.repoId, defaultBranch: head, refs, lastPush: index.lastPush }
585
+ const common = {
586
+ repo: resolved.repoId,
587
+ defaultBranch: head,
588
+ refs,
589
+ lastPush: index.lastPush,
590
+ claimed: index.claimed === true,
591
+ }
581
592
 
582
593
  const op = url.searchParams.get('op')
583
594
  if (op === 'refs') return json(common)
@@ -739,7 +750,9 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
739
750
  if (url.pathname === EXPIRE_PATH) {
740
751
  if (!deps.sweep || request.method !== 'POST') return NOT_FOUND()
741
752
  if (request.headers.get(INTERNAL_HEADER) !== '1') return NOT_FOUND()
742
- const report = await deps.sweep()
753
+ // `?collect=only` is the second daily sweep (`worker/index.ts`): finish
754
+ // the deletions the first one started, tombstone nothing new.
755
+ const report = await deps.sweep({ collectOnly: url.searchParams.get('collect') === 'only' })
743
756
  return new Response(`${JSON.stringify(report)}\n`, {
744
757
  headers: { 'content-type': 'application/json; charset=utf-8' },
745
758
  })
@@ -36,6 +36,7 @@
36
36
  import * as fs from 'node:fs'
37
37
  import * as path from 'node:path'
38
38
 
39
+ import { defaultBranch } from '../shared/browse'
39
40
  import { ensureBareRepo } from './cache'
40
41
  import { git } from './git'
41
42
  import { siblingIdx } from '../shared/keys'
@@ -176,7 +177,7 @@ export async function materialize(
176
177
 
177
178
  const refsStart = performance.now()
178
179
  const reconciled = reconcile(repo.dir, index)
179
- ensureHead(repo.dir, index)
180
+ ensureHead(repo.dir, index.refs)
180
181
  const refsMs = performance.now() - refsStart
181
182
 
182
183
  fs.rmSync(markerPath(repo.dir), { force: true })
@@ -255,26 +256,36 @@ function writeAtomic(target: string, body: Uint8Array): void {
255
256
  }
256
257
 
257
258
  /**
258
- * Point HEAD at a branch that exists.
259
+ * Point HEAD at the Index's Default Branch (`defaultBranch`, `shared/browse.ts`).
259
260
  *
260
261
  * A bare repo is initialised with HEAD on `main`; a repo whose log only carries
261
262
  * `master` would then clone successfully into an empty working tree, which
262
263
  * reads as data loss. The log's ref state is the only thing that knows.
264
+ *
265
+ * A function of the Index and nothing else, which is a property and not a
266
+ * simplification. It used to keep whatever HEAD already named while that branch
267
+ * existed, so the answer depended on the disk's history: a name first pushed as
268
+ * `feature` and later given `main` reported `feature` on a container that had
269
+ * watched it happen and `main` on one that had just Materialized it. Now every
270
+ * Cache says what the Index says — and so does the edge, which answers
271
+ * `ls-refs` off the Index without a Cache at all (`shared/edge-refs.ts`) and
272
+ * calls the same function for the same answer. Exported so `sync.ts` can
273
+ * assert it on every access, which is what makes a first push of a branch
274
+ * other than `main` visible as HEAD without waiting for a restart.
275
+ *
276
+ * A repository with no branch is left alone: HEAD is unborn there either way.
263
277
  */
264
- function ensureHead(gitDir: string, index: WalIndex): void {
265
- const branches = Object.keys(index.refs).filter((ref) => ref.startsWith('refs/heads/'))
266
- if (branches.length === 0) return
278
+ export function ensureHead(gitDir: string, refs: Record<string, string>): void {
279
+ const head = defaultBranch(refs)
280
+ if (head === null) return
267
281
 
268
282
  const headFile = path.join(gitDir, 'HEAD')
269
- const current = fs.existsSync(headFile) ? fs.readFileSync(headFile, 'utf8').trim() : ''
270
- const target = /^ref: (.+)$/.exec(current)?.[1]
271
- if (target && branches.includes(target)) return
272
-
273
- const preferred =
274
- branches.find((ref) => ref === 'refs/heads/main') ??
275
- branches.find((ref) => ref === 'refs/heads/master') ??
276
- branches.sort()[0]!
277
- fs.writeFileSync(headFile, `ref: ${preferred}\n`)
283
+ const wanted = `ref: ${head}\n`
284
+ const current = fs.existsSync(headFile) ? fs.readFileSync(headFile, 'utf8') : ''
285
+ if (current === wanted) return
286
+ // Renamed into place, because a `git upload-pack` reading HEAD while it is
287
+ // being written would otherwise see an empty file and report no HEAD at all.
288
+ writeAtomic(headFile, new TextEncoder().encode(wanted))
278
289
  }
279
290
 
280
291
  /**
@@ -293,7 +304,15 @@ function ensureHead(gitDir: string, index: WalIndex): void {
293
304
  * is genuinely absent.
294
305
  */
295
306
  function acquire(gitDir: string): Promise<LockRelease> {
296
- return acquireLock(path.join(gitDir, LOCK), { breakAfter: 1200 })
307
+ return acquireLock(lockPath(gitDir), { breakAfter: 1200 })
308
+ }
309
+
310
+ /**
311
+ * Where that lock lives. Exported for the one other reader: the boot-time
312
+ * sweep (src/boot-residue.ts), which removes a lock no process can hold yet.
313
+ */
314
+ export function lockPath(gitDir: string): string {
315
+ return path.join(gitDir, LOCK)
297
316
  }
298
317
 
299
318
  /**
@@ -254,6 +254,8 @@ export type PublishResult =
254
254
  * has to read like one.
255
255
  */
256
256
  | { ok: false; reason: 'not-allowed'; kind: GateRefusal; message: string }
257
+ /** The repository is being deleted right now (`RepoDeletion.collecting_at`). */
258
+ | { ok: false; reason: 'deleting' }
257
259
 
258
260
  export interface PublishOptions {
259
261
  /** How many compare-and-swap attempts before giving up. */
@@ -318,6 +320,23 @@ function claimIsThisPush(index: WalIndex, pending: PendingPush): boolean {
318
320
  )
319
321
  }
320
322
 
323
+ /**
324
+ * A push lifts an expiry mark: expiry marked the repository because nobody had
325
+ * pushed to it, and somebody just did. Left in place, the mark's grace would run
326
+ * out and the collection would delete the push this compare-and-swap is about to
327
+ * acknowledge. An operator's mark (no `by`) stays — that was a decision about
328
+ * the repository, not a reading of its idleness.
329
+ *
330
+ * A ref-only push lifts it too, though it appends no WAL entry and so does not
331
+ * move the date expiry reads: the next full sweep marks the repository again.
332
+ * That is a day's notice rather than a silent loss.
333
+ */
334
+ export function liftExpiry(next: WalIndex): WalIndex {
335
+ if (next.deletion?.by !== 'expiry') return next
336
+ const { deletion: _lifted, ...rest } = next
337
+ return rest
338
+ }
339
+
321
340
  /**
322
341
  * Publish the pending entry with the push's ref changes, under CAS.
323
342
  *
@@ -345,6 +364,11 @@ export async function publishPush(
345
364
  for (let i = 0; i < attempts; i += 1) {
346
365
  const { index, etag } = await loadIndex(store, repoId)
347
366
 
367
+ // Refused, not published: past this field the collection is removing the
368
+ // repository and will not look at the Index again, so anything published
369
+ // now would be acknowledged and then deleted.
370
+ if (index.deletion?.collecting_at) return { ok: false, reason: 'deleting' }
371
+
348
372
  for (const change of changes) {
349
373
  const actual = index.refs[change.ref] ?? ZERO_OID
350
374
  if (actual !== change.oldOid) {
@@ -417,14 +441,16 @@ export async function publishPush(
417
441
  provenance: pending.provenance ?? null,
418
442
  claim: pending.claim ?? null,
419
443
  }
420
- const next = pending.entry
421
- ? nextIndex(index, pending.entry, changes, record)
422
- : {
423
- ...index,
424
- refs: applyRefChanges(index.refs, changes),
425
- provenance: applyProvenance(index.provenance, changes, record.provenance),
426
- claim: applyClaim(index.claim, changes, record.claim),
427
- }
444
+ const next = liftExpiry(
445
+ pending.entry
446
+ ? nextIndex(index, pending.entry, changes, record)
447
+ : {
448
+ ...index,
449
+ refs: applyRefChanges(index.refs, changes),
450
+ provenance: applyProvenance(index.provenance, changes, record.provenance),
451
+ claim: applyClaim(index.claim, changes, record.claim),
452
+ },
453
+ )
428
454
 
429
455
  const result = await commitIndex(store, next, etag)
430
456
  if (result.ok) return { ok: true, index: next }
@@ -98,7 +98,12 @@ export function reconcile(gitDir: string, index: WalIndex): ReconcileResult {
98
98
  * for exactly the refs that were wrong.
99
99
  */
100
100
  function writePackedRefs(gitDir: string, refs: Record<string, string>): void {
101
- const lines = ['# pack-refs with: peeled fully-peeled sorted ']
101
+ // `sorted` and nothing else. `peeled`/`fully-peeled` promise that every
102
+ // annotated tag carries its `^<oid>` line, and these lines come from the
103
+ // Index, which holds no object types — so git trusted the promise and
104
+ // advertised annotated tags with no peeled value. Without the traits git
105
+ // peels them itself from the objects.
106
+ const lines = ['# pack-refs with: sorted ']
102
107
  for (const ref of Object.keys(refs).sort()) lines.push(`${refs[ref]} ${ref}`)
103
108
 
104
109
  const target = path.join(gitDir, 'packed-refs')
@@ -11,12 +11,17 @@
11
11
  * straight to this port.
12
12
  */
13
13
 
14
+ import * as fs from 'node:fs'
15
+
14
16
  import { capabilitiesFrom } from '../shared/capabilities'
17
+ import { BOOT_MARKER } from '../shared/container-snapshot'
15
18
  import { parseTokens } from '../shared/credentials'
16
19
  import { listCommits, listTree, readBlob, statBlob } from './browse'
20
+ import { clearBootResidue } from './boot-residue'
17
21
  import { ensureBareRepo } from './cache'
18
- import { configuredExpiryMs, expireRepos } from './expire'
19
- import { createHttpHandler } from './http'
22
+ import { publishUploadPackAtBoot } from './edge-refs'
23
+ import { configuredClaimedExpiryMs, configuredExpiryMs, expireRepos } from './expire'
24
+ import { createHttpHandler, type SweepOptions } from './http'
20
25
  import { privateReposConfigError, privateReposEnabled, privateReposSeed } from './private'
21
26
  import { gitAncestry, isProposalRef, listProposals } from './proposals'
22
27
  import { resolveRepo } from './repo'
@@ -127,6 +132,7 @@ if (privateSeed && !store) {
127
132
  * retention promise from — so the page and the sweeper can never disagree.
128
133
  */
129
134
  const expiryMs = configuredExpiryMs()
135
+ const claimedExpiryMs = configuredClaimedExpiryMs()
130
136
 
131
137
  /**
132
138
  * What this process actually booted with, printed once.
@@ -149,6 +155,7 @@ const expiryMs = configuredExpiryMs()
149
155
  console.log(
150
156
  `walgit boot: public=${isPublic} appendOnly=${caps.appendOnly} ` +
151
157
  `retentionHours=${caps.retentionHours ?? 'off'} ` +
158
+ `claimedRetentionHours=${caps.claimedRetentionHours ?? 'off'} ` +
152
159
  `maxPush=${caps.maxPushBytes ?? 'unset'} maxRepo=${caps.maxRepoBytes ?? 'unset'} ` +
153
160
  `private=${caps.namesCanBePrivate} ` +
154
161
  `perSource=${
@@ -168,15 +175,24 @@ console.log(
168
175
  * too, but this line is the one that survives in the container's own log when
169
176
  * the question is what the sweeper actually did.
170
177
  */
171
- async function runSweep(logStore: ObjectStore, windowMs: number) {
172
- const result = await expireRepos(logStore, { windowMs, dryRun: false, reposDir })
178
+ async function runSweep(logStore: ObjectStore, windowMs: number, opts: SweepOptions) {
179
+ const result = await expireRepos(logStore, {
180
+ windowMs,
181
+ claimedWindowMs: claimedExpiryMs,
182
+ collectOnly: opts.collectOnly,
183
+ dryRun: false,
184
+ reposDir,
185
+ })
173
186
  console.log(
174
- `walgit expire: collected ${result.collected.length}, retained ${result.retained.length}`,
187
+ `walgit expire${opts.collectOnly ? ' (collect only)' : ''}: ` +
188
+ `collected ${result.collected.length}, retained ${result.retained.length}`,
175
189
  )
176
190
  return {
177
191
  collected: result.collected.map((o) => ({ repoId: o.repoId, reason: o.decision.reason })),
178
192
  retained: result.retained.length,
179
193
  windowMs: result.windowMs,
194
+ claimedWindowMs: result.claimedWindowMs,
195
+ collectOnly: result.collectOnly,
180
196
  }
181
197
  }
182
198
 
@@ -195,7 +211,7 @@ try {
195
211
  // endpoint should not exist for it — `expireRepos` would return an empty
196
212
  // report either way, but a deployment that cannot collect anything should
197
213
  // not answer as though it might.
198
- sweep: store && expiryMs !== null ? () => runSweep(store, expiryMs) : undefined,
214
+ sweep: store && expiryMs !== null ? (opts) => runSweep(store, expiryMs, opts) : undefined,
199
215
  // Answered from the Index, so a ref-event handshake states what is
200
216
  // published rather than what this node's disk happens to hold. Absent
201
217
  // without a store, in which case there is nothing authoritative to read
@@ -260,7 +276,13 @@ try {
260
276
  ? {
261
277
  readIndex: async (repoId) => {
262
278
  const { index, etag } = await loadIndex(store, repoId)
263
- return etag === null ? null : { refs: index.refs, lastPush: lastPushOf(index) }
279
+ return etag === null
280
+ ? null
281
+ : {
282
+ refs: index.refs,
283
+ lastPush: lastPushOf(index),
284
+ claimed: index.claim !== undefined,
285
+ }
264
286
  },
265
287
  listTree: (repo, rev, path) => listTree(repo.dir, rev, path),
266
288
  statBlob: (repo, rev, path) => statBlob(repo.dir, rev, path),
@@ -296,5 +318,44 @@ try {
296
318
  process.exit(1)
297
319
  }
298
320
 
299
- Bun.serve({ port, idleTimeout: 0, fetch: handler })
321
+ // Before the port opens, because the port opening is what the Durable Object
322
+ // takes to mean "ready": a disk restored from a snapshot can carry a dead
323
+ // push's hand-off record and a materialize lock, and no request may see either
324
+ // (src/boot-residue.ts). Logged only when it found something, which on a disk
325
+ // that was not restored is never.
326
+ const residue = clearBootResidue(reposDir)
327
+ // After the residue goes, so clearing it does not read as a change: the stop
328
+ // compares the cache against this marker to decide whether a new snapshot is
329
+ // worth taking (`needsNewSnapshot`, shared/container-snapshot.ts).
330
+ try {
331
+ fs.writeFileSync(BOOT_MARKER, reposDir)
332
+ } catch (err) {
333
+ console.warn(`walgit: could not write ${BOOT_MARKER}: ${(err as Error).message}`)
334
+ }
335
+ if (residue.cleared.length > 0) {
336
+ console.log(
337
+ `walgit: cleared ${residue.cleared.length} stale lock/hand-off path(s) across ${residue.repos} cached repo(s)`,
338
+ )
339
+ }
340
+
341
+ const server = Bun.serve({ port, idleTimeout: 0, fetch: handler })
342
+
343
+ // What this image's git advertises, published for the edge to answer ref
344
+ // checks with while this container sleeps (`src/edge-refs.ts`). After the
345
+ // listener is up and never awaited: the request that woke this container is
346
+ // served the ordinary way either way, and so is every one until this lands.
347
+ if (store) void publishUploadPackAtBoot(store)
348
+
349
+ // The container's idle stop is a SIGTERM (`stopContainer` in
350
+ // worker/durable-container.ts), and this process is PID 1, which the kernel
351
+ // exempts from every signal it has no handler for. Without this the stop was
352
+ // ignored, the container ran around the clock, and the Durable Object in front
353
+ // of it stayed awake polling it. Stop accepting, let the requests in flight
354
+ // finish, then exit — nothing durable is lost by going, since a push is
355
+ // acknowledged only once the log holds it. The Durable Object kills the
356
+ // container outright if this has not happened within its grace period.
357
+ process.on('SIGTERM', () => {
358
+ console.log('walgit: SIGTERM, draining and exiting')
359
+ void server.stop().finally(() => process.exit(0))
360
+ })
300
361
  console.log(`walgit smart-HTTP listening on :${port} (repos: ${reposDir})`)
@@ -23,7 +23,7 @@
23
23
 
24
24
  import type { ObjectStore } from '../shared/store'
25
25
  import type { ResolvedRepo } from './repo'
26
- import { isPartial, materialize, type MaterializeStats } from './materialize'
26
+ import { ensureHead, isPartial, materialize, type MaterializeStats } from './materialize'
27
27
  import { reconcile, type ReconcileResult } from './reconcile'
28
28
  import { loadIndex } from '../shared/wal-index'
29
29
 
@@ -47,7 +47,15 @@ export async function syncRepo(
47
47
  // `isPartial` covers the case reconcile cannot see: an interrupted restore
48
48
  // that happened to finish placing the packs its refs need, but died before
49
49
  // the rest. The marker is the only evidence, so it is trusted over the refs.
50
- if (reconciled.missing.length === 0 && !isPartial(repo.dir)) return reconciled
50
+ if (reconciled.missing.length === 0 && !isPartial(repo.dir)) {
51
+ // HEAD as well as the refs, on every access and not only on a restore: a
52
+ // push moves refs without touching HEAD, so a first push of `feature`
53
+ // leaves it on the unborn `main` `git init` chose until something points
54
+ // it at the Default Branch — and the edge, answering `ls-refs` from the
55
+ // Index, already reports that branch (`shared/edge-refs.ts`).
56
+ ensureHead(repo.dir, index.refs)
57
+ return reconciled
58
+ }
51
59
 
52
60
  const result = await materialize(store, repo, index)
53
61
  return { ...result.reconciled, materialize: result.stats }