@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
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The object-store key namespace — walgit's storage layout, in one file.
3
+ *
4
+ * `repos/<repo_id>/…` is the one thing every module agrees on and the one thing
5
+ * a bucket cannot be migrated away from: the WAL is the source of truth
6
+ * (docs/adr/0007), so a key is not an implementation detail of whichever module
7
+ * happens to write it. It used to be authored in six places and read back by
8
+ * hand in two more — `gc.ts` reconstructed a ULID out of a WAL key with a
9
+ * `split`, a `pop`, a `replace`, an `indexOf` and a `slice`, reversing a format
10
+ * `walKey` produced six modules away without saying so.
11
+ *
12
+ * So: every prefix, every key builder, the `.pack` → `.idx` sibling rule, and
13
+ * the parse back out of a WAL key live here, and nothing else builds one. The
14
+ * layout is:
15
+ *
16
+ * repos/<repo_id>/index.json the Index — the log's head
17
+ * repos/<repo_id>/wal/<seq>-<ulid>.pack one push's objects
18
+ * repos/<repo_id>/wal/<seq>-<ulid>.idx its sibling index
19
+ * repos/<repo_id>/compaction.lease who is compacting, until when
20
+ *
21
+ * Enumerating repositories lives here too, and that is a move rather than a new
22
+ * function: `listRepoIds` was in `usage.ts`, the read-only reporting command,
23
+ * because that is where it was first needed — which left `expire.ts`, whose job
24
+ * is deleting repositories, importing the usage reporter to find them. Nothing
25
+ * about listing a prefix is a usage concern.
26
+ */
27
+
28
+ import type { ObjectStore } from './store'
29
+ import { ulidTime } from './ulid'
30
+
31
+ /** Where every repository's state lives. One flat level: `repos/<repo_id>/`. */
32
+ export const REPOS_PREFIX = 'repos/'
33
+
34
+ /** Everything walgit stores for one repository lives under this prefix. */
35
+ export function repoPrefix(repoId: string): string {
36
+ return `${REPOS_PREFIX}${repoId}/`
37
+ }
38
+
39
+ /** The write-ahead log's objects for one repository. */
40
+ export function walPrefix(repoId: string): string {
41
+ return `${repoPrefix(repoId)}wal/`
42
+ }
43
+
44
+ /** The Index: the compare-and-swap target that makes a push durable. */
45
+ export function indexKey(repoId: string): string {
46
+ return `${repoPrefix(repoId)}index.json`
47
+ }
48
+
49
+ /** Who holds the compaction lease for this repository, and until when. */
50
+ export function leaseKey(repoId: string): string {
51
+ return `${repoPrefix(repoId)}compaction.lease`
52
+ }
53
+
54
+ /** Zero-padded to 12 digits so lexicographic key order is numeric order. */
55
+ export function walKey(repoId: string, seq: number, ulid: string, ext: 'pack' | 'idx'): string {
56
+ return `${walPrefix(repoId)}${String(seq).padStart(12, '0')}-${ulid}.${ext}`
57
+ }
58
+
59
+ /**
60
+ * The `.idx` uploaded beside a pack.
61
+ *
62
+ * Deleted with its pack and never separately, and never an orphan while the
63
+ * pack is live: an entry in the Index names the `.pack` directly and its
64
+ * sibling only implicitly, so every reader that walks entries has to be able to
65
+ * derive one from the other the same way.
66
+ */
67
+ export function siblingIdx(packKey: string): string {
68
+ return packKey.replace(/\.pack$/, '.idx')
69
+ }
70
+
71
+ /**
72
+ * The ULID a WAL key carries, or `null` when it does not carry one.
73
+ *
74
+ * `null` is the "this is not a key this file wrote" answer, not the "it is
75
+ * ancient" one — which matters because the only caller is the collector, and
76
+ * the asymmetry there is that over-retaining costs storage while
77
+ * under-retaining loses data with no error anywhere.
78
+ */
79
+ export function walKeyUlid(key: string): string | null {
80
+ const stem =
81
+ key
82
+ .split('/')
83
+ .pop()
84
+ ?.replace(/\.(pack|idx)$/, '') ?? ''
85
+ const dash = stem.indexOf('-')
86
+ if (dash === -1) return null
87
+ const id = stem.slice(dash + 1)
88
+ return id === '' ? null : id
89
+ }
90
+
91
+ /**
92
+ * When a WAL object was uploaded, from the ULID in its key.
93
+ *
94
+ * The upload time is in the key rather than read from the store because not
95
+ * every store reports one, and a restore has to be able to reason about age
96
+ * from the listing alone.
97
+ */
98
+ export function walKeyUploadedAt(key: string): number | null {
99
+ const id = walKeyUlid(key)
100
+ return id === null ? null : ulidTime(id)
101
+ }
102
+
103
+ /**
104
+ * Which repositories does this bucket hold?
105
+ *
106
+ * `listPrefixes` when the store has it — one delimited LIST instead of walking
107
+ * every key in the bucket — and otherwise derived from the keys themselves, so
108
+ * a store that cannot roll up prefixes still answers correctly rather than not
109
+ * at all.
110
+ */
111
+ export async function listRepoIds(store: ObjectStore): Promise<string[]> {
112
+ if (store.listPrefixes) {
113
+ const prefixes = await store.listPrefixes(REPOS_PREFIX)
114
+ return prefixes
115
+ .map((p) => p.slice(REPOS_PREFIX.length).replace(/\/$/, ''))
116
+ .filter((id) => id.length > 0)
117
+ .sort()
118
+ }
119
+ const keys = await store.list(REPOS_PREFIX)
120
+ const ids = new Set<string>()
121
+ for (const key of keys) {
122
+ const id = key.slice(REPOS_PREFIX.length).split('/')[0]
123
+ if (id) ids.add(id)
124
+ }
125
+ return [...ids].sort()
126
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Size limits: refuse an oversized push in the first second, not the fortieth.
3
+ *
4
+ * Without this, the edge is the only thing enforcing a size, and the edge
5
+ * enforces it in the worst possible way. `http.postBuffer` defaults to 1 MiB,
6
+ * so every real push is chunked — and a chunked body is uploaded IN FULL before
7
+ * the proxy answers. Measured against Fly: with `Content-Length` the edge 413s
8
+ * at 101 MiB after ~2 MB in 1.4 s, but chunked, 99 MiB passes and 100 MiB is
9
+ * refused only AFTER all 104,879,625 bytes have gone up — 37 s of upload to
10
+ * learn the answer, reported as `RPC failed; HTTP 413` and `unexpected
11
+ * disconnect`. That reads like a dropped network, so an agent retries it.
12
+ *
13
+ * So walgit enforces its own caps, and it does so in `pre-receive`: the pack is
14
+ * sitting in the quarantine, its size is known exactly, and nothing has been
15
+ * written to the object store yet. The refusal therefore costs one local stat
16
+ * and one index read, and leaves no orphan behind for `findOrphans` to reclaim.
17
+ *
18
+ * Two caps, because they fail differently. A single huge push is one client
19
+ * sending too much at once; a repository creeping over its total is many small
20
+ * pushes that were each individually fine. Telling an agent "your push is too
21
+ * big" when the push was 2 MiB would send it looking in the wrong place, so the
22
+ * two messages say different things.
23
+ *
24
+ * Both are UNSET by default. A cap this file does not enforce is one `GET /`
25
+ * must not claim, which is why `instructions.ts` renders from the same
26
+ * `Capabilities` this file takes its caps from rather than from a copy of them.
27
+ */
28
+
29
+ import type { Capabilities } from '../shared/capabilities'
30
+ import { describeBytes } from '../shared/policy'
31
+ import type { WalIndex } from './wal-index'
32
+
33
+ export interface Limits {
34
+ /** Largest single push, in bytes. `null` means unlimited. */
35
+ maxPushBytes: number | null
36
+ /** Largest live size of one repository, in bytes. `null` means unlimited. */
37
+ maxRepoBytes: number | null
38
+ }
39
+
40
+ export const NO_LIMITS: Limits = { maxPushBytes: null, maxRepoBytes: null }
41
+
42
+ /**
43
+ * The caps this instance enforces, as the two of nine capabilities this file
44
+ * cares about.
45
+ *
46
+ * A projection rather than a second reading. The parsing lives in
47
+ * `capabilitiesFrom` (`shared/capabilities.ts`), which is also what the three
48
+ * agent-facing documents state their caps from — so the number `pre-receive`
49
+ * refuses on and the number a page prints cannot be arrived at two ways. An
50
+ * unparseable or non-positive value has already read as unset by the time it
51
+ * gets here: zero would refuse every push, and a typo in a deployment env var
52
+ * must not silently become "this host accepts nothing".
53
+ */
54
+ export function limitsOf(caps: Capabilities): Limits {
55
+ return {
56
+ maxPushBytes: caps.maxPushBytes,
57
+ maxRepoBytes: caps.maxRepoBytes,
58
+ }
59
+ }
60
+
61
+ /** Is there anything to check? Nothing is read from the store when there isn't. */
62
+ export function limitsEnforced(limits: Limits): boolean {
63
+ return limits.maxPushBytes !== null || limits.maxRepoBytes !== null
64
+ }
65
+
66
+ /**
67
+ * What this repository costs right now, in bytes.
68
+ *
69
+ * Entries at or below the compaction frontier are superseded: their objects are
70
+ * tombstoned and `gc.ts` deletes them a grace period later, so counting them
71
+ * would charge a repository twice for history it holds once — and would make a
72
+ * repository that compacted itself look like it had grown. This is the same set
73
+ * `pendingEntries` (compact.ts) names for restore, for the same reason: it is
74
+ * what the log actually still holds, and the same number `usage.ts` reports as
75
+ * a repository's `liveBytes` — a cap and a usage report that disagreed would be
76
+ * unexplainable to whoever hit it. The filter is repeated rather than
77
+ * imported so this file stays free of `compact.ts` — dragging git and the
78
+ * materializer into the HTTP server to reuse one `filter` would be a poor
79
+ * trade. The byte formatting is not repeated: it is `shared/policy.ts`'s,
80
+ * because the landing page states the same cap this file refuses on.
81
+ */
82
+ export function liveBytes(index: WalIndex): number {
83
+ return index.entries
84
+ .filter((entry) => entry.seq > index.compaction_frontier)
85
+ .reduce((total, entry) => total + entry.size, 0)
86
+ }
87
+
88
+ export type SizeVerdict = { ok: true } | { ok: false; kind: 'push' | 'repo'; message: string }
89
+
90
+ export interface SizeCheck {
91
+ repoId: string
92
+ /** Bytes this push would add: the quarantine packfile's size. */
93
+ pushBytes: number
94
+ /** Bytes the repository already holds live — see `liveBytes`. */
95
+ repoBytes: number
96
+ limits: Limits
97
+ }
98
+
99
+ /**
100
+ * Judge a push against both caps.
101
+ *
102
+ * Per-push is checked first. When a single push exceeds both caps at once, the
103
+ * per-push message is the actionable one: splitting the push is something the
104
+ * client can do, whereas "this repository is full" would send it to a new name
105
+ * for a push that would be refused there too.
106
+ */
107
+ export function checkSize(check: SizeCheck): SizeVerdict {
108
+ const { maxPushBytes, maxRepoBytes } = check.limits
109
+
110
+ if (maxPushBytes !== null && check.pushBytes > maxPushBytes) {
111
+ return { ok: false, kind: 'push', message: pushTooLarge(check, maxPushBytes) }
112
+ }
113
+ if (maxRepoBytes !== null && check.repoBytes + check.pushBytes > maxRepoBytes) {
114
+ return { ok: false, kind: 'repo', message: repoTooLarge(check, maxRepoBytes) }
115
+ }
116
+ return { ok: true }
117
+ }
118
+
119
+ /**
120
+ * Product copy, not a debug string. `unexpected disconnect` is what this
121
+ * replaces: a message that reads like a transport fault gets retried, and the
122
+ * retry costs the same forty seconds. So the message states a number the client
123
+ * can compare its own pack against, and one concrete thing to do next.
124
+ */
125
+ function pushTooLarge(check: SizeCheck, cap: number): string {
126
+ return [
127
+ `walgit: refused — this push is larger than ${describeBytes(cap)}.`,
128
+ '',
129
+ `You sent ${describeBytes(check.pushBytes)}; the limit for a single push is ${describeBytes(cap)}.`,
130
+ 'This is a walgit limit, not a network failure. Retrying the same push will',
131
+ 'be refused again in the same way.',
132
+ '',
133
+ 'What you can do instead:',
134
+ ' - push your history in stages: git push origin <an-older-commit>:refs/heads/main',
135
+ ' then push the rest, so no single push carries everything at once',
136
+ ' - or leave large files out of the repository entirely — walgit stores git',
137
+ ' objects, and a binary blob costs the same on every clone forever',
138
+ '',
139
+ 'Nothing was uploaded; the repository is unchanged.',
140
+ ].join('\n')
141
+ }
142
+
143
+ function repoTooLarge(check: SizeCheck, cap: number): string {
144
+ const total = check.repoBytes + check.pushBytes
145
+ return [
146
+ `walgit: refused — ${check.repoId} would exceed its ${describeBytes(cap)} total.`,
147
+ '',
148
+ `The repository already holds ${describeBytes(check.repoBytes)} and this push adds`,
149
+ `${describeBytes(check.pushBytes)}, for ${describeBytes(total)}.`,
150
+ 'The push itself is within the per-push limit — it is the repository that is full.',
151
+ 'This is a walgit limit, not a network failure.',
152
+ '',
153
+ 'What you can do instead:',
154
+ ' - start a fresh repository: git remote set-url origin <same-host>/<new-name>.git',
155
+ '',
156
+ 'Nothing was uploaded; the repository is unchanged.',
157
+ ].join('\n')
158
+ }
@@ -3,7 +3,7 @@
3
3
  * Materialize latency, measured as its OWN number.
4
4
  *
5
5
  * The design's target — a cold materialize under two seconds — was written for
6
- * an always-on NVMe node. On Fly with `min_machines_running = 0` the wall-clock
6
+ * an always-on NVMe node. With a container that sleeps when idle the wall-clock
7
7
  * a client experiences is machine wake PLUS this, and wake alone was measured
8
8
  * at ~1.35 s in the milestone-0 spike. Blending them makes a regression
9
9
  * unattributable, so this harness measures the replay half and nothing else:
@@ -25,8 +25,8 @@ import * as os from 'node:os'
25
25
  import * as path from 'node:path'
26
26
 
27
27
  import { compact } from './compact'
28
+ import { indexKey, siblingIdx, walKey } from './keys'
28
29
  import { materialize } from './materialize'
29
- import { sha256 } from './push'
30
30
  import { resolveRepo } from './repo'
31
31
  import { FileStore } from './store'
32
32
  import { ulid } from './ulid'
@@ -34,7 +34,7 @@ import {
34
34
  commitIndex,
35
35
  emptyIndex,
36
36
  loadIndex,
37
- walKey,
37
+ sha256,
38
38
  type WalEntry,
39
39
  type WalIndex,
40
40
  } from './wal-index'
@@ -105,7 +105,10 @@ async function buildLog(repoId: string, count: number): Promise<WalIndex> {
105
105
  input: objects,
106
106
  maxBuffer: 1 << 28,
107
107
  })
108
- const pack = new Uint8Array(packed.stdout)
108
+ // A `Buffer` already IS a `Uint8Array`; wrapping it would only double the
109
+ // memory the bench holds, which is the one thing a bench should not
110
+ // misreport.
111
+ const pack = packed.stdout
109
112
 
110
113
  const seq = i + 1
111
114
  const key = walKey(repoId, seq, ulid(Date.now() + i), 'pack')
@@ -114,10 +117,7 @@ async function buildLog(repoId: string, count: number): Promise<WalIndex> {
114
117
  fs.mkdirSync(staged, { recursive: true })
115
118
  fs.writeFileSync(path.join(staged, 'p.pack'), pack)
116
119
  git(staged, 'index-pack', 'p.pack')
117
- await store.put(
118
- key.replace(/\.pack$/, '.idx'),
119
- new Uint8Array(fs.readFileSync(path.join(staged, 'p.idx'))),
120
- )
120
+ await store.put(siblingIdx(key), fs.readFileSync(path.join(staged, 'p.idx')))
121
121
 
122
122
  const entry: WalEntry = {
123
123
  seq,
@@ -131,7 +131,7 @@ async function buildLog(repoId: string, count: number): Promise<WalIndex> {
131
131
  parent = head
132
132
  }
133
133
 
134
- const existing = await store.get(`repos/${repoId}/index.json`)
134
+ const existing = await store.get(indexKey(repoId))
135
135
  await commitIndex(store, index, existing?.etag ?? null)
136
136
  return index
137
137
  }
@@ -241,7 +241,7 @@ console.log(
241
241
  'Each size is measured twice: over the raw log, and over the same repository ' +
242
242
  'after compaction. The second column is the one that must stay flat.',
243
243
  note:
244
- 'On Fly, a client also pays machine wake (~1350ms, milestone-0 spike). ' +
244
+ 'A client also pays container cold start (median 1770ms, Containers spike). ' +
245
245
  'These numbers are a control loop on the compaction threshold, not a pass/fail gate.',
246
246
  store: 'FileStore (local disk) — a real bucket adds one round trip per entry',
247
247
  platform: `${process.platform}/${process.arch}`,
@@ -6,7 +6,8 @@
6
6
  * is sufficient: `index.json` names every packfile still needed and the full
7
7
  * ref state that results from applying them.
8
8
  *
9
- * On Fly with `min_machines_running = 0` this is the NORMAL path, not disaster
9
+ * With a container that sleeps when idle and a disk wiped on every restart,
10
+ * this is the NORMAL path, not disaster
10
11
  * recovery — an idle repo loses its machine routinely, so materialize runs on
11
12
  * ordinary first access after a pause. The restore path is therefore exercised
12
13
  * continuously instead of only in a crisis, which is the point.
@@ -32,15 +33,17 @@
32
33
  * proportional to bytes already transferred.
33
34
  */
34
35
 
35
- import { spawnSync } from 'node:child_process'
36
36
  import * as fs from 'node:fs'
37
37
  import * as path from 'node:path'
38
38
 
39
- import { ensureBareRepo, type ResolvedRepo } from './repo'
39
+ import { ensureBareRepo } from './cache'
40
+ import { git } from './git'
41
+ import { siblingIdx } from './keys'
42
+ import { acquireLock, type LockRelease } from './mkdir-lock'
40
43
  import { reconcile, type ReconcileResult } from './reconcile'
41
- import { sha256 } from './push'
44
+ import type { ResolvedRepo } from './repo'
42
45
  import type { ObjectStore } from './store'
43
- import { loadIndex, type WalEntry, type WalIndex } from './wal-index'
46
+ import { loadIndex, sha256, type WalEntry, type WalIndex } from './wal-index'
44
47
 
45
48
  /**
46
49
  * Removed only when a materialize completes. Its presence means a previous
@@ -107,6 +110,32 @@ export function neededEntries(index: WalIndex): WalEntry[] {
107
110
  .sort((a, b) => a.seq - b.seq)
108
111
  }
109
112
 
113
+ /** Where git keeps this repo's packfiles. One knower of that layout. */
114
+ export function packDirOf(gitDir: string): string {
115
+ return path.join(gitDir, 'objects', 'pack')
116
+ }
117
+
118
+ /**
119
+ * The entries a restore would still have to fetch: needed by the index, and not
120
+ * already sitting in `objects/pack`.
121
+ *
122
+ * Exported because `verify` asks the same question and must get the same
123
+ * answer. `cli.ts` states the rule it is obeying — the operator commands are a
124
+ * thin front over the functions the server already calls, because a
125
+ * reimplementation "would answer for itself rather than for the server, and
126
+ * would drift silently the first time the real path changed". This predicate is
127
+ * what decides both what materialize downloads and what verify reports missing;
128
+ * two copies of it means a `walgit verify` that can call a node healthy while
129
+ * every access re-downloads its whole log.
130
+ */
131
+ export function absentEntries(gitDir: string, index: WalIndex): WalEntry[] {
132
+ const packDir = packDirOf(gitDir)
133
+ const onDisk = new Set(
134
+ fs.existsSync(packDir) ? fs.readdirSync(packDir).filter((f) => f.endsWith('.pack')) : [],
135
+ )
136
+ return neededEntries(index).filter((entry) => !onDisk.has(`${packBasename(entry)}.pack`))
137
+ }
138
+
110
139
  /**
111
140
  * Rebuild `repo` from the log and reconcile its refs against the index.
112
141
  *
@@ -128,12 +157,11 @@ export async function materialize(
128
157
  const release = await acquire(repo.dir)
129
158
  const waited = release.waited
130
159
  try {
131
- const packDir = path.join(repo.dir, 'objects', 'pack')
160
+ const packDir = packDirOf(repo.dir)
132
161
  fs.mkdirSync(packDir, { recursive: true })
133
- const onDisk = new Set(fs.readdirSync(packDir).filter((f) => f.endsWith('.pack')))
134
162
 
135
163
  const needed = neededEntries(index)
136
- const absent = needed.filter((entry) => !onDisk.has(`${packBasename(entry)}.pack`))
164
+ const absent = absentEntries(repo.dir, index)
137
165
 
138
166
  const fetchStart = performance.now()
139
167
  let bytes = 0
@@ -196,7 +224,7 @@ async function placeEntry(store: ObjectStore, packDir: string, entry: WalEntry):
196
224
  }
197
225
 
198
226
  const base = path.join(packDir, packBasename(entry))
199
- const idxKey = entry.key.replace(/\.pack$/, '.idx')
227
+ const idxKey = siblingIdx(entry.key)
200
228
  const idx = await store.get(idxKey)
201
229
 
202
230
  writeAtomic(`${base}.pack`, found.body)
@@ -205,11 +233,9 @@ async function placeEntry(store: ObjectStore, packDir: string, entry: WalEntry):
205
233
  } else {
206
234
  // Only when the log predates uploading the index, or the sibling was lost.
207
235
  // It is the expensive path the `.idx` upload exists to avoid, so it says so.
208
- const built = spawnSync('git', ['index-pack', `${base}.pack`], {
209
- stdio: ['ignore', 'ignore', 'pipe'],
210
- })
236
+ const built = git(['index-pack', `${base}.pack`])
211
237
  if (built.status !== 0) {
212
- throw new Error(`walgit: could not index ${entry.key}: ${built.stderr?.toString().trim()}`)
238
+ throw new Error(`walgit: could not index ${entry.key}: ${built.stderr.trim()}`)
213
239
  }
214
240
  }
215
241
  return found.body.byteLength
@@ -252,39 +278,21 @@ function ensureHead(gitDir: string, index: WalIndex): void {
252
278
  * `packed-refs` rewrite is not something two writers should race on, and paying
253
279
  * for the same download twice is the latency this milestone is measured by.
254
280
  *
255
- * `mkdir` is the primitive because it is atomic on POSIX and needs no daemon —
256
- * the same choice `FileStore` makes, and for the same reason.
281
+ * Six seconds before the lock is broken, not one: unlike a `FileStore` write
282
+ * the holder here is downloading packfiles, so a lock still held after a second
283
+ * usually means a slow restore rather than a dead one. Breaking it eventually
284
+ * is still required — the container is stopped whenever it is idle — and
285
+ * still safe, because the loser re-reads the directory and downloads only what
286
+ * is genuinely absent.
257
287
  */
258
- async function acquire(gitDir: string): Promise<(() => void) & { waited: boolean }> {
259
- const lockPath = path.join(gitDir, LOCK)
260
- let waited = false
261
- for (let i = 0; ; i += 1) {
262
- try {
263
- fs.mkdirSync(lockPath)
264
- const release = () => {
265
- try {
266
- fs.rmdirSync(lockPath)
267
- } catch {
268
- /* already released */
269
- }
270
- }
271
- return Object.assign(release, { waited })
272
- } catch {
273
- waited = true
274
- // A holder killed mid-restore would otherwise wedge the repo forever, and
275
- // on Fly a machine is stopped whenever it is idle — so the wait is
276
- // bounded and then broken. Breaking it is safe: the loser re-reads the
277
- // directory and downloads only what is genuinely absent.
278
- if (i > 1200) fs.rmSync(lockPath, { recursive: true, force: true })
279
- await new Promise((r) => setTimeout(r, 5))
280
- }
281
- }
288
+ function acquire(gitDir: string): Promise<LockRelease> {
289
+ return acquireLock(path.join(gitDir, LOCK), { breakAfter: 1200 })
282
290
  }
283
291
 
284
292
  /**
285
293
  * One machine-readable line per restore.
286
294
  *
287
- * It is reported separately from anything else on purpose: on Fly, machine wake
295
+ * It is reported separately from anything else on purpose: container cold start
288
296
  * alone is ~1.35 s (measured in the milestone-0 spike), so a single
289
297
  * end-to-end number cannot attribute a regression to either half. This is the
290
298
  * materialize half and nothing else.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * A mutual exclusion between processes on one machine, built out of `mkdir`.
3
+ *
4
+ * `mkdir` is the primitive because it is atomic on POSIX and needs no daemon:
5
+ * exactly one of N concurrent callers creates the directory and the rest get
6
+ * `EEXIST`. That is the whole mechanism. walgit needs it in two places — a
7
+ * `FileStore` conditional write, and a materialize that must not run twice into
8
+ * the same directory — and until this module they were two hand-rolled copies
9
+ * whose comments each pointed at the other.
10
+ *
11
+ * **Breaking the lock is the subtle part, and it is why one copy is not
12
+ * enough.** A holder that is killed mid-write releases nothing, and in a container a
13
+ * machine is stopped whenever it is idle, so a lock that only a graceful
14
+ * release could clear would wedge a repository permanently — a failure that
15
+ * presents as everything quietly hanging. So the wait is bounded and then the
16
+ * lock is taken by force. That is safe only because both callers are
17
+ * idempotent: the loser re-reads what is on disk and redoes only what is
18
+ * genuinely absent.
19
+ *
20
+ * `breakAfter` is an argument rather than a constant because the two callers
21
+ * legitimately differ — a conditional write is over in milliseconds, a cold
22
+ * restore downloads packfiles — and passing it makes that difference a decision
23
+ * the call site states rather than a number that drifted.
24
+ */
25
+
26
+ import * as fs from 'node:fs'
27
+
28
+ /** How long between attempts. Short: contention here is measured in ms. */
29
+ const POLL_MS = 5
30
+
31
+ export interface LockOptions {
32
+ /**
33
+ * How many failed attempts to tolerate before breaking the lock. Attempts are
34
+ * `POLL_MS` apart, so this is a duration in disguise: 200 ≈ 1 s, 1200 ≈ 6 s.
35
+ */
36
+ breakAfter: number
37
+ }
38
+
39
+ /**
40
+ * Releases the lock. `waited` says whether anyone was holding it on arrival —
41
+ * which is the difference between "this restore was the only one" and "this
42
+ * restore queued behind another", and materialize reports it.
43
+ */
44
+ export type LockRelease = (() => void) & { waited: boolean }
45
+
46
+ /** Take `lockPath`, waiting for it if held. The parent directory must exist. */
47
+ export async function acquireLock(lockPath: string, opts: LockOptions): Promise<LockRelease> {
48
+ let waited = false
49
+ for (let i = 0; ; i += 1) {
50
+ try {
51
+ fs.mkdirSync(lockPath)
52
+ const release = () => {
53
+ try {
54
+ fs.rmdirSync(lockPath)
55
+ } catch {
56
+ /* already released, or broken by a waiter */
57
+ }
58
+ }
59
+ return Object.assign(release, { waited })
60
+ } catch {
61
+ waited = true
62
+ if (i > opts.breakAfter) fs.rmSync(lockPath, { recursive: true, force: true })
63
+ await new Promise((r) => setTimeout(r, POLL_MS))
64
+ }
65
+ }
66
+ }
@@ -19,6 +19,7 @@
19
19
  * garbage.
20
20
  */
21
21
 
22
+ import { siblingIdx, walPrefix } from './keys'
22
23
  import type { ObjectStore } from './store'
23
24
  import { loadIndex } from './wal-index'
24
25
 
@@ -28,10 +29,6 @@ export interface Orphan {
28
29
  ageMs?: number
29
30
  }
30
31
 
31
- export function walPrefix(repoId: string): string {
32
- return `repos/${repoId}/wal/`
33
- }
34
-
35
32
  /**
36
33
  * Keys under the WAL prefix that `index.json` does not reference.
37
34
  *
@@ -47,7 +44,7 @@ export async function findOrphans(store: ObjectStore, repoId: string): Promise<s
47
44
  const live = new Set<string>()
48
45
  for (const entry of index.entries) {
49
46
  live.add(entry.key)
50
- live.add(entry.key.replace(/\.pack$/, '.idx'))
47
+ live.add(siblingIdx(entry.key))
51
48
  }
52
49
  return keys.filter((key) => !live.has(key))
53
50
  }