Public: anyone can read this; the crew can change it.
Revert "The repo is durable in the bucket: each push's pack is written to the BlobStore before ack, refs stay in the database with CAS" #16725
Check · Review · Land · Live done — Landed and live in production.
revert-16674 → main 0 commits
8 files
changed +0
−589
docs/BLOBS.md −8
| @@ -50,11 +50,3 @@ Blobs over a size policy are copied here by object id after a push and served by | ||
| 50 | 50 | |
| 51 | 51 | Archiving finished run logs and attachments onto the store and the cold-tier lifecycle are later steps of #4481, each with |
| 52 | 52 | its own issue. |
| 53 | ||
| 54 | ## Packs: the repository in the bucket | |
| 55 | ||
| 56 | `src/blob/packs.ts` (#4491, step 4 of #4481; the write path and the rebuild, the first slice). Inside `pre-receive`, after the forge's own checks pass and before git moves a ref, a push's new objects are written to the store as one pack (`packs/<owner>/<name>/pending/<hash>/<seq>.pack`). A store that fails, or gives no answer in 60 s, refuses the push with a 503 and nothing moves, so the pusher is acked only for a push the store holds. The record of its ref updates (`<seq>.json`) is written in `post-receive`, after git applied them: a push git then refused leaves a pack no record names, which a rebuild never reads. The first time the store is used for a repository that already has refs, its history is written first as a base record (`0000000000000-base.json` and `base.pack`), so a rebuild has what the first push's old values name. | |
| 57 | ||
| 58 | `bun scripts/rebuild-repo.ts <data-dir> <owner> <name> <empty-target-dir>` makes a bare repository from nothing: it indexes each record's pack in order and replays its updates with `update-ref <ref> <new> <old>`, so a record that does not fit stops the rebuild and is named. The target must have no refs. A repository whose refs moved outside receive-pack (the web editor, merges) stops a rebuild at the first record whose old value they changed. | |
| 59 | ||
| 60 | On when the forge has a bucket (`S3_*`) or `FORGE_PACK_STORE=dir` (a directory under the data directory); `FORGE_PACK_STORE=off` turns it off. Not done yet: pushes that skip receive-pack (web editor, merges), refs kept in the database, rebuilding on a missing repository at boot, evicting idle repositories, clearing packs no record names, and the scheduled repack and compaction on the primary. |
scripts/rebuild-repo.ts deleted −27
| @@ -1,27 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Rebuild a repository from the pack store (#4491), run by the operator: | |
| 3 | * bun scripts/rebuild-repo.ts <data-dir> <owner> <name> <empty-target-dir> | |
| 4 | * Reads the same store the forge writes (`S3_*`, or `FORGE_PACK_STORE=dir` under <data-dir>), | |
| 5 | * indexes each push's pack and replays its ref updates with a compare-and-swap. Exit 0 only | |
| 6 | * when every record fit; the first that does not is named and nothing after it is applied. | |
| 7 | * See docs/BLOBS.md. | |
| 8 | */ | |
| 9 | import { packStore, rebuildRepo } from "../src/blob/packs.ts"; | |
| 10 | ||
| 11 | const [dataDir, owner, name, target] = process.argv.slice(2); | |
| 12 | if (!dataDir || !owner || !name || !target) { | |
| 13 | console.error("usage: bun scripts/rebuild-repo.ts <data-dir> <owner> <name> <empty-target-dir>"); | |
| 14 | process.exit(2); | |
| 15 | } | |
| 16 | const store = packStore(dataDir); | |
| 17 | if (store === undefined) { | |
| 18 | console.error("no pack store: set S3_* or FORGE_PACK_STORE=dir"); | |
| 19 | process.exit(2); | |
| 20 | } | |
| 21 | try { | |
| 22 | const n = await rebuildRepo({ store, dir: target, owner, name }); | |
| 23 | console.log(`rebuilt ${owner}/${name} into ${target}: ${n} pushes replayed`); | |
| 24 | } catch (error) { | |
| 25 | console.error(`rebuild stopped: ${error instanceof Error ? error.message : String(error)}`); | |
| 26 | process.exit(1); | |
| 27 | } |
src/blob/packs.ts deleted −290
| @@ -1,290 +0,0 @@ | ||
| 1 | /** | |
| 2 | * The repository is durable in the bucket (#4491, step 4 of #4481): the first slice, the write | |
| 3 | * path and the rebuild. | |
| 4 | * | |
| 5 | * A push's new objects are written to the BlobStore as one pack inside `pre-receive`: after the | |
| 6 | * forge's own checks passed and before git moves a ref, so the pusher is acked only for a push | |
| 7 | * the store holds. A store that fails, or does not answer in `STORE_MS`, refuses the push (503, | |
| 8 | * nothing moved; the pusher tries again). The record of the ref updates is written in | |
| 9 | * `post-receive`, after git applied them (`commitPush`), so a push git then refused (a lost | |
| 10 | * race, a lock, a client that hung up) leaves a pack no record names, which a rebuild never | |
| 11 | * reads. Refs stay in git; `rebuildRepo` replays them: from an empty bare repository it indexes | |
| 12 | * each record's pack and applies its updates with a compare-and-swap (`update-ref <ref> <new> | |
| 13 | * <old>`), so a record whose old value is not what the repository holds stops the rebuild | |
| 14 | * instead of forking history. `scripts/rebuild-repo.ts` is the operator's way in. | |
| 15 | * | |
| 16 | * Keys under `packs/<owner>/<name>/`: | |
| 17 | * - `pending/<hash>/<seq>.pack`: a push's pack, named by the hash of its tips; | |
| 18 | * - `<seq>.json`: the record that commits a push (the ref updates and which pack, if any); | |
| 19 | * - `0000000000000-base.json` and `base.pack`: the history the repository held when the store | |
| 20 | * was first used for it, written before that first push, so a rebuild has the objects and | |
| 21 | * refs the first record's old values name. | |
| 22 | * `<seq>` is 13 digits of milliseconds and a random suffix, so records sort in push order. | |
| 23 | * | |
| 24 | * Off unless the forge has a bucket (`S3_*`) or `FORGE_PACK_STORE=dir` (a directory under the | |
| 25 | * data directory); `FORGE_PACK_STORE=off` turns it off. Pushes that do not pass through | |
| 26 | * receive-pack (the web editor, merges) are not covered yet: a rebuild of a repository they | |
| 27 | * moved stops at the first record whose old value they changed, and says which. | |
| 28 | */ | |
| 29 | ||
| 30 | import { createHash } from "node:crypto"; | |
| 31 | import { mkdir } from "node:fs/promises"; | |
| 32 | import { join } from "node:path"; | |
| 33 | import { gitEnv, runGit } from "../git/env.ts"; | |
| 34 | import { isSafeOid } from "../git/guard.ts"; | |
| 35 | import { ZERO_OID, type RefUpdate } from "../git/hook-protocol.ts"; | |
| 36 | import { dirStore, s3FromEnv, s3Store, type BlobStore } from "./store.ts"; | |
| 37 | ||
| 38 | const prefixOf = (owner: string, name: string): string => | |
| 39 | `packs/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/`; | |
| 40 | ||
| 41 | /** How long the store may take to hold a push's pack or record before the push is refused. */ | |
| 42 | export const STORE_MS = 60_000; | |
| 43 | ||
| 44 | /** The record that commits a push: the ref updates it made, and the pack that holds its objects. */ | |
| 45 | export interface PushRecord { | |
| 46 | readonly updates: readonly RefUpdate[]; | |
| 47 | /** The pack's key under the repository's prefix, without `.pack`; none when no object is new. */ | |
| 48 | readonly pack?: string; | |
| 49 | } | |
| 50 | ||
| 51 | const PACK_NAME = /^(base|pending\/[0-9a-f]{64}\/[0-9]{13}-[0-9a-f]{8})$/; | |
| 52 | const BASE_RECORD = "0000000000000-base"; | |
| 53 | ||
| 54 | /** | |
| 55 | * `work` or, when the store does not answer in `ms`, an error: a hung bucket must not hold a push. | |
| 56 | */ | |
| 57 | async function within<T>(work: Promise<T>, what: string, ms: number): Promise<T> { | |
| 58 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 59 | const late = new Promise<never>((_, reject) => { | |
| 60 | timer = setTimeout(() => reject(new Error(`the store gave no answer to ${what} in ${ms} ms`)), ms); | |
| 61 | }); | |
| 62 | work.catch(() => {}); | |
| 63 | try { | |
| 64 | return await Promise.race([work, late]); | |
| 65 | } finally { | |
| 66 | clearTimeout(timer); | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | // The bucket's store is made once per process, from the first environment `packStore` sees: a | |
| 71 | // later change to `S3_*` needs a restart (a test that changes it sees the first store). | |
| 72 | let shared: BlobStore | undefined; | |
| 73 | /** Where packs go, or undefined when the forge keeps none. */ | |
| 74 | export function packStore( | |
| 75 | dataDir: string, | |
| 76 | env: Record<string, string | undefined> = process.env, | |
| 77 | ): BlobStore | undefined { | |
| 78 | const mode = env["FORGE_PACK_STORE"]?.trim().toLowerCase(); | |
| 79 | if (mode === "off") return undefined; | |
| 80 | const target = s3FromEnv(env); | |
| 81 | if (target !== undefined) return (shared ??= s3Store(target, 2)); | |
| 82 | return mode === "dir" ? dirStore(join(dataDir, "packs")) : undefined; | |
| 83 | } | |
| 84 | ||
| 85 | const sequence = (): string => | |
| 86 | `${String(Date.now()).padStart(13, "0")}-${crypto.randomUUID().slice(0, 8)}`; | |
| 87 | ||
| 88 | const tipsOf = (updates: readonly RefUpdate[]): string[] => { | |
| 89 | const tips = [...new Set(updates.map((u) => u.newOid).filter((oid) => !ZERO_OID.test(oid)))].sort(); | |
| 90 | for (const oid of tips) if (!isSafeOid(oid)) throw new Error("a tip is not an object id"); | |
| 91 | return tips; | |
| 92 | }; | |
| 93 | const tipsHash = (tips: readonly string[]): string => createHash("sha256").update(tips.join("\n")).digest("hex"); | |
| 94 | ||
| 95 | /** `git pack-objects` of `revs` (tips, then `^`-excluded ones) streamed into the store at `key`. */ | |
| 96 | async function putPack( | |
| 97 | store: BlobStore, | |
| 98 | key: string, | |
| 99 | dir: string, | |
| 100 | revs: readonly string[], | |
| 101 | env: Record<string, string>, | |
| 102 | ms: number, | |
| 103 | ): Promise<void> { | |
| 104 | const proc = Bun.spawn(["git", "pack-objects", "--revs", "--stdout", "-q"], { | |
| 105 | cwd: dir, | |
| 106 | env: gitEnv(env), | |
| 107 | stdin: new Blob([`${revs.join("\n")}\n`]), | |
| 108 | stdout: "pipe", | |
| 109 | stderr: "ignore", | |
| 110 | }); | |
| 111 | try { | |
| 112 | await within(store.putStream(key, proc.stdout), "the pack", ms); | |
| 113 | if ((await proc.exited) !== 0) throw new Error("git pack-objects failed"); | |
| 114 | } catch (error) { | |
| 115 | proc.kill(); | |
| 116 | await store.delete(key).catch(() => {}); | |
| 117 | throw error; | |
| 118 | } | |
| 119 | } | |
| 120 | ||
| 121 | /** Every ref the repository holds, as `[oid, ref]`. */ | |
| 122 | async function heldRefs(dir: string): Promise<[string, string][]> { | |
| 123 | const held = await runGit(["for-each-ref", "--format=%(objectname) %(refname)"], { cwd: dir }); | |
| 124 | if (!held.ok) throw new Error("git for-each-ref failed"); | |
| 125 | const out: [string, string][] = []; | |
| 126 | for (const line of held.value.split("\n")) { | |
| 127 | const [oid, ref] = line.split(" "); | |
| 128 | if (oid !== undefined && ref !== undefined && isSafeOid(oid)) out.push([oid, ref]); | |
| 129 | } | |
| 130 | return out; | |
| 131 | } | |
| 132 | ||
| 133 | interface Where { | |
| 134 | readonly store: BlobStore; | |
| 135 | readonly dir: string; | |
| 136 | readonly owner: string; | |
| 137 | readonly name: string; | |
| 138 | readonly ms?: number; | |
| 139 | } | |
| 140 | ||
| 141 | /** | |
| 142 | * A repository that already has history when the store is first used for it: write that history | |
| 143 | * as the first record, so the pack and the refs a rebuild starts from exist. It describes what | |
| 144 | * is true now, so it is safe to write before the push moves anything. | |
| 145 | */ | |
| 146 | async function backfill(w: Where, refs: [string, string][]): Promise<void> { | |
| 147 | const prefix = prefixOf(w.owner, w.name); | |
| 148 | const ms = w.ms ?? STORE_MS; | |
| 149 | await putPack(w.store, `${prefix}base.pack`, w.dir, [...new Set(refs.map(([oid]) => oid))], {}, ms); | |
| 150 | const record: PushRecord = { | |
| 151 | pack: "base", | |
| 152 | updates: refs.map(([oid, ref]) => ({ oldOid: "0".repeat(oid.length), newOid: oid, ref })), | |
| 153 | }; | |
| 154 | try { | |
| 155 | await within(w.store.put(`${prefix}${BASE_RECORD}.json`, JSON.stringify(record)), "the base record", ms); | |
| 156 | } catch (error) { | |
| 157 | await w.store.delete(`${prefix}base.pack`).catch(() => {}); | |
| 158 | throw error; | |
| 159 | } | |
| 160 | } | |
| 161 | ||
| 162 | /** | |
| 163 | * `pre-receive`: write the push's new objects to the store, and, the first time the store is | |
| 164 | * used for a repository that already has refs, its history before them. Nothing is committed: no | |
| 165 | * record names this pack until `commitPush` runs after git applied the update. | |
| 166 | * `gitEnvForQuarantine` is the push's quarantine environment, the only way git sees its objects. | |
| 167 | * Throws when the store or git fails, or the store does not answer in time. | |
| 168 | */ | |
| 169 | export async function storePush( | |
| 170 | input: Where & { | |
| 171 | readonly updates: readonly RefUpdate[]; | |
| 172 | readonly gitEnvForQuarantine: Record<string, string>; | |
| 173 | }, | |
| 174 | ): Promise<void> { | |
| 175 | const tips = tipsOf(input.updates); | |
| 176 | const ms = input.ms ?? STORE_MS; | |
| 177 | const refs = await heldRefs(input.dir); | |
| 178 | if (refs.length > 0 && (await pushKeys(input.store, input.owner, input.name)).length === 0) { | |
| 179 | await backfill(input, refs); | |
| 180 | } | |
| 181 | if (tips.length === 0) return; | |
| 182 | // What the repository already holds, named by its refs' tips (`--all` is not a rev here). | |
| 183 | const have = [...new Set(refs.map(([oid]) => `^${oid}`))]; | |
| 184 | const key = `${prefixOf(input.owner, input.name)}pending/${tipsHash(tips)}/${sequence()}.pack`; | |
| 185 | await putPack(input.store, key, input.dir, [...tips, ...have], input.gitEnvForQuarantine, ms); | |
| 186 | } | |
| 187 | ||
| 188 | /** | |
| 189 | * `post-receive`: git applied `updates`, so commit them: the record that names the push's pack. | |
| 190 | * The pack is the one `storePush` wrote for these tips; when there is none (git applied only | |
| 191 | * some of a push's refs, so the tips differ) the pack is made again from the repository, which | |
| 192 | * now holds the objects, over-inclusive but whole. Throws when the store fails. | |
| 193 | */ | |
| 194 | export async function commitPush(input: Where & { readonly updates: readonly RefUpdate[] }): Promise<string> { | |
| 195 | const { store, updates } = input; | |
| 196 | const prefix = prefixOf(input.owner, input.name); | |
| 197 | const ms = input.ms ?? STORE_MS; | |
| 198 | const tips = tipsOf(updates); | |
| 199 | let pack: string | undefined; | |
| 200 | if (tips.length > 0) { | |
| 201 | const dirKey = `${prefix}pending/${tipsHash(tips)}/`; | |
| 202 | const made = (await within(store.list(dirKey), "the pending list", ms)).filter((k) => k.endsWith(".pack")).sort(); | |
| 203 | const found = made.at(-1); | |
| 204 | if (found !== undefined) pack = found.slice(prefix.length, -".pack".length); | |
| 205 | else { | |
| 206 | pack = `pending/${tipsHash(tips)}/${sequence()}`; | |
| 207 | const before = [...new Set(updates.map((u) => u.oldOid).filter((oid) => !ZERO_OID.test(oid)))].map((o) => `^${o}`); | |
| 208 | await putPack(store, `${prefix}${pack}.pack`, input.dir, [...tips, ...before], {}, ms); | |
| 209 | } | |
| 210 | } | |
| 211 | const record: PushRecord = { | |
| 212 | ...(pack === undefined ? {} : { pack }), | |
| 213 | updates: updates.map(({ oldOid, newOid, ref }) => ({ oldOid, newOid, ref })), | |
| 214 | }; | |
| 215 | const key = `${prefix}${sequence()}`; | |
| 216 | await within(store.put(`${key}.json`, JSON.stringify(record)), "the record", ms); | |
| 217 | return key; | |
| 218 | } | |
| 219 | ||
| 220 | /** The record keys under a repository, in push order. */ | |
| 221 | export async function pushKeys(store: BlobStore, owner: string, name: string): Promise<string[]> { | |
| 222 | const prefix = prefixOf(owner, name); | |
| 223 | return (await store.list(prefix)) | |
| 224 | .filter((k) => k.endsWith(".json") && !k.slice(prefix.length).includes("/")) | |
| 225 | .map((k) => k.slice(0, -".json".length)) | |
| 226 | .sort(); | |
| 227 | } | |
| 228 | ||
| 229 | export function readRecord(bytes: Uint8Array): PushRecord | undefined { | |
| 230 | try { | |
| 231 | const v = JSON.parse(new TextDecoder().decode(bytes)) as { updates?: unknown; pack?: unknown }; | |
| 232 | if (!Array.isArray(v.updates)) return undefined; | |
| 233 | if (v.pack !== undefined && (typeof v.pack !== "string" || !PACK_NAME.test(v.pack))) return undefined; | |
| 234 | const updates: RefUpdate[] = []; | |
| 235 | for (const u of v.updates as Partial<RefUpdate>[]) { | |
| 236 | if (typeof u?.oldOid !== "string" || typeof u.newOid !== "string" || typeof u.ref !== "string") return undefined; | |
| 237 | if (!isSafeOid(u.oldOid) || !isSafeOid(u.newOid) || !u.ref.startsWith("refs/")) return undefined; | |
| 238 | updates.push({ oldOid: u.oldOid, newOid: u.newOid, ref: u.ref }); | |
| 239 | } | |
| 240 | return { updates, ...(v.pack === undefined ? {} : { pack: v.pack }) }; | |
| 241 | } catch { | |
| 242 | return undefined; | |
| 243 | } | |
| 244 | } | |
| 245 | ||
| 246 | /** | |
| 247 | * Build a repository from the store into `dir` (created if missing; refused when it already has | |
| 248 | * refs): every record's pack indexed, every ref update replayed with a compare-and-swap. Returns | |
| 249 | * how many records were replayed; throws on the first one that does not fit, or whose pack is | |
| 250 | * missing, and on a store with no records at all. | |
| 251 | */ | |
| 252 | export async function rebuildRepo(input: { | |
| 253 | readonly store: BlobStore; | |
| 254 | readonly dir: string; | |
| 255 | readonly owner: string; | |
| 256 | readonly name: string; | |
| 257 | }): Promise<number> { | |
| 258 | const { store, dir } = input; | |
| 259 | const prefix = prefixOf(input.owner, input.name); | |
| 260 | const keys = await pushKeys(store, input.owner, input.name); | |
| 261 | if (keys.length === 0) throw new Error("the store holds no pushes for this repository"); | |
| 262 | await mkdir(dir, { recursive: true }); | |
| 263 | const existing = await runGit(["for-each-ref", "--count=1", "--format=%(refname)"], { cwd: dir, env: { GIT_DIR: dir } }); | |
| 264 | if (existing.ok && existing.value.trim() !== "") throw new Error("the target already has refs; rebuild into an empty one"); | |
| 265 | const init = await runGit(["init", "--bare", "-q", "--initial-branch=main", dir]); | |
| 266 | if (!init.ok) throw new Error("git init failed"); | |
| 267 | let replayed = 0; | |
| 268 | for (const key of keys) { | |
| 269 | const bytes = await store.get(`${key}.json`); | |
| 270 | const record = bytes === undefined ? undefined : readRecord(bytes); | |
| 271 | if (record === undefined) throw new Error(`${key}: the push record is unreadable`); | |
| 272 | if (record.pack !== undefined) { | |
| 273 | const pack = await store.getStream(`${prefix}${record.pack}.pack`); | |
| 274 | if (pack === undefined) throw new Error(`${key}: its pack is missing`); | |
| 275 | const proc = Bun.spawn(["git", "index-pack", "--stdin", "--fix-thin"], { | |
| 276 | cwd: dir, env: gitEnv(), stdin: pack, stdout: "ignore", stderr: "ignore", | |
| 277 | }); | |
| 278 | if ((await proc.exited) !== 0) throw new Error(`${key}: the pack does not index`); | |
| 279 | } | |
| 280 | for (const u of record.updates) { | |
| 281 | const gone = ZERO_OID.test(u.newOid); | |
| 282 | const old = ZERO_OID.test(u.oldOid) ? "0".repeat(u.newOid.length) : u.oldOid; | |
| 283 | const args = gone ? ["update-ref", "-d", u.ref, u.oldOid] : ["update-ref", u.ref, u.newOid, old]; | |
| 284 | const done = await runGit(args, { cwd: dir }); | |
| 285 | if (!done.ok) throw new Error(`${key}: ${u.ref} is not at ${u.oldOid}`); | |
| 286 | } | |
| 287 | replayed++; | |
| 288 | } | |
| 289 | return replayed; | |
| 290 | } |
src/http/hook.ts −41
| @@ -21,7 +21,6 @@ import { unsealReleased } from "../actions/sealed.ts"; | ||
| 21 | 21 | import { forkPushLines } from "../actions/fork_push.ts"; |
| 22 | 22 | import { contribPushPulls, contribPushRefusal } from "../actions/contribute_push.ts"; |
| 23 | 23 | import { queueScanPush } from "../checks/scan.ts"; |
| 24 | import { commitPush, packStore, storePush } from "../blob/packs.ts"; | |
| 25 | 24 | import { PUSH_HOLDS_SECRET, pushHolds } from "../crew/leak.ts"; |
| 26 | 25 | import { heldLongForms } from "../kernel/log.ts"; |
| 27 | 26 | import { runGit } from "../git/env.ts"; |
| @@ -183,28 +182,6 @@ export async function handleHook(app: App, request: Request): Promise<Response> | ||
| 183 | 182 | if (!forwarded.ok) { |
| 184 | 183 | return new Response(forwarded.error.message, { status: 403 }); |
| 185 | 184 | } |
| 186 | // Last: only a push the forge accepts is stored, and the pusher is acked only for one the | |
| 187 | // store holds (`blob/packs.ts`). A store that fails or stalls refuses the push; nothing has | |
| 188 | // moved. The record that commits it is written in post-receive, after git applied the update. | |
| 189 | const packs = packStore(app.config.dataDir); | |
| 190 | if (packs !== undefined) { | |
| 191 | try { | |
| 192 | await storePush({ | |
| 193 | store: packs, | |
| 194 | dir: repoDir(app.reposRoot, repo.ownerName, repo.name), | |
| 195 | owner: repo.ownerName, | |
| 196 | name: repo.name, | |
| 197 | updates: input.updates, | |
| 198 | gitEnvForQuarantine: input.gitEnv, | |
| 199 | }); | |
| 200 | } catch (error) { | |
| 201 | app.log.warn("push not stored", { repo: `${repo.ownerName}/${repo.name}`, why: String(error).slice(0, 200) }); | |
| 202 | return new Response("the push could not be stored durably; nothing was changed, try again", { | |
| 203 | status: 503, | |
| 204 | headers: { "retry-after": "5" }, | |
| 205 | }); | |
| 206 | } | |
| 207 | } | |
| 208 | 185 | return new Response(""); |
| 209 | 186 | } |
| 210 | 187 | |
| @@ -262,24 +239,6 @@ export async function handleHook(app: App, request: Request): Promise<Response> | ||
| 262 | 239 | printed = lines.join("\n"); |
| 263 | 240 | } |
| 264 | 241 | |
| 265 | // post-receive: git applied the update, so the store's record of it is written now. The push | |
| 266 | // is already in; a store that fails here is logged loudly, never undone (`blob/packs.ts`). | |
| 267 | const packs = packStore(app.config.dataDir); | |
| 268 | if (packs !== undefined) { | |
| 269 | await commitPush({ | |
| 270 | store: packs, | |
| 271 | dir: repoDir(app.reposRoot, repo.ownerName, repo.name), | |
| 272 | owner: repo.ownerName, | |
| 273 | name: repo.name, | |
| 274 | updates: input.updates, | |
| 275 | }).catch((error) => | |
| 276 | app.log.error("push applied but its record was not stored", { | |
| 277 | repo: `${repo.ownerName}/${repo.name}`, | |
| 278 | why: String(error).slice(0, 200), | |
| 279 | }), | |
| 280 | ); | |
| 281 | } | |
| 282 | ||
| 283 | 242 | // post-receive: the push is durable — record it and wake listeners. |
| 284 | 243 | app.bus.append({ |
| 285 | 244 | kind: "push", |
test/packs-durable.test.ts deleted −219
| @@ -1,219 +0,0 @@ | ||
| 1 | /** | |
| 2 | * The repository is durable in the bucket (#4491): a real `git push` writes its pack and ref | |
| 3 | * updates to the store before it is acked, a store that fails refuses the push, and a fresh | |
| 4 | * repository rebuilt from the store has the refs the original has. | |
| 5 | */ | |
| 6 | import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { dirStore, type BlobStore } from "../src/blob/store.ts"; | |
| 12 | import { commitPush, packStore, pushKeys, readRecord, rebuildRepo, storePush } from "../src/blob/packs.ts"; | |
| 13 | import { runGit } from "../src/git/env.ts"; | |
| 14 | import { repoDir } from "../src/git/repos.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 17 | import { gitClientEnv, gitRun } from "./helpers/git-client.ts"; | |
| 18 | ||
| 19 | const gitOut = (cwd: string, ...args: string[]): string => gitRun(cwd, ...args); | |
| 20 | /** Async, for a git that talks to the in-process server (a sync spawn would block it). */ | |
| 21 | const git = async (cwd: string, ...args: string[]): Promise<string> => { | |
| 22 | const done = await runGit(args, { cwd, env: gitClientEnv() }); | |
| 23 | if (!done.ok) throw new Error(done.error.stderr); | |
| 24 | return done.value; | |
| 25 | }; | |
| 26 | const refs = (dir: string): string => gitOut(dir, "for-each-ref", "--format=%(refname) %(objectname)"); | |
| 27 | ||
| 28 | describe("packs", () => { | |
| 29 | test("the store is off unless there is a bucket or FORGE_PACK_STORE=dir", () => { | |
| 30 | expect(packStore("/d", {})).toBeUndefined(); | |
| 31 | expect(packStore("/d", { FORGE_PACK_STORE: "dir" })).toBeDefined(); | |
| 32 | expect(packStore("/d", { FORGE_PACK_STORE: "off", S3_ENDPOINT: "https://s3.example", S3_BUCKET: "b", S3_ACCESS_KEY: "k", S3_SECRET_KEY: "s" })).toBeUndefined(); | |
| 33 | }); | |
| 34 | }); | |
| 35 | ||
| 36 | describe("a push through git", () => { | |
| 37 | let dataDir: string; | |
| 38 | let work: string; | |
| 39 | let app: App; | |
| 40 | let servers: Servers; | |
| 41 | let remote: string; | |
| 42 | const was = process.env["FORGE_PACK_STORE"]; | |
| 43 | ||
| 44 | beforeAll(async () => { | |
| 45 | process.env["FORGE_PACK_STORE"] = "dir"; | |
| 46 | dataDir = await mkdtemp(join(tmpdir(), "forge-packs-")); | |
| 47 | work = await mkdtemp(join(tmpdir(), "forge-packswork-")); | |
| 48 | app = createApp({ dataDir, port: 0 }); | |
| 49 | servers = await serve(app); | |
| 50 | const seeded = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 51 | if (!seeded.ok) throw new Error(seeded.error); | |
| 52 | const minted = await fetch(`${servers.url}/api/v1/tokens`, { | |
| 53 | method: "POST", | |
| 54 | headers: { "content-type": "application/json" }, | |
| 55 | body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }), | |
| 56 | }); | |
| 57 | const token = ((await minted.json()) as { token: string }).token; | |
| 58 | const made = await fetch(`${servers.url}/api/v1/repos`, { | |
| 59 | method: "POST", | |
| 60 | headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, | |
| 61 | body: JSON.stringify({ name: "app" }), | |
| 62 | }); | |
| 63 | expect(made.status).toBe(201); | |
| 64 | remote = `${servers.url.replace("http://", `http://alice:${token}@`)}/alice/app.git`; | |
| 65 | }); | |
| 66 | ||
| 67 | afterAll(async () => { | |
| 68 | if (was === undefined) delete process.env["FORGE_PACK_STORE"]; | |
| 69 | else process.env["FORGE_PACK_STORE"] = was; | |
| 70 | servers.stop(); | |
| 71 | app.close(); | |
| 72 | await rm(dataDir, { recursive: true, force: true }); | |
| 73 | await rm(work, { recursive: true, force: true }); | |
| 74 | }); | |
| 75 | ||
| 76 | const commit = async (dir: string, file: string, text: string): Promise<void> => { | |
| 77 | await writeFile(join(dir, file), text); | |
| 78 | await git(dir, "add", "."); | |
| 79 | await git(dir, "commit", "-m", file); | |
| 80 | }; | |
| 81 | ||
| 82 | test("each push is in the store; a rebuild has the same refs; a failing store refuses", async () => { | |
| 83 | await git(work, "clone", remote, "app"); | |
| 84 | const dir = join(work, "app"); | |
| 85 | await commit(dir, "a.txt", "one\n"); | |
| 86 | await git(dir, "push", "origin", "HEAD:refs/heads/main"); | |
| 87 | await commit(dir, "b.txt", "two\n"); | |
| 88 | await git(dir, "push", "origin", "HEAD:refs/heads/main", "HEAD:refs/heads/topic"); | |
| 89 | await git(dir, "push", "origin", ":refs/heads/topic"); | |
| 90 | ||
| 91 | const store = dirStore(join(dataDir, "packs")); | |
| 92 | expect((await pushKeys(store, "alice", "app")).length).toBe(3); | |
| 93 | ||
| 94 | const rebuilt = join(work, "rebuilt.git"); | |
| 95 | expect(await rebuildRepo({ store, dir: rebuilt, owner: "alice", name: "app" })).toBe(3); | |
| 96 | const original = refs(repoDir(app.reposRoot, "alice", "app")); | |
| 97 | expect(original).toContain("refs/heads/main"); | |
| 98 | expect(original).not.toContain("refs/heads/topic"); | |
| 99 | expect(refs(rebuilt)).toBe(original); | |
| 100 | const fsck = await runGit(["fsck", "--no-dangling"], { cwd: rebuilt }); | |
| 101 | expect(fsck.ok).toBe(true); | |
| 102 | ||
| 103 | // The store fails (its directory is a file): the push is refused and no ref moves. | |
| 104 | await rm(join(dataDir, "packs"), { recursive: true, force: true }); | |
| 105 | await writeFile(join(dataDir, "packs"), "not a directory"); | |
| 106 | await commit(dir, "c.txt", "three\n"); | |
| 107 | await expect(git(dir, "push", "origin", "HEAD:refs/heads/main")).rejects.toThrow("stored durably"); | |
| 108 | expect(refs(repoDir(app.reposRoot, "alice", "app"))).toBe(original); | |
| 109 | }); | |
| 110 | }); | |
| 111 | ||
| 112 | describe("the store, without a push through the forge", () => { | |
| 113 | let root: string; | |
| 114 | let origin: string; | |
| 115 | let work: string; | |
| 116 | let store: BlobStore; | |
| 117 | let c1: string; | |
| 118 | let c2: string; | |
| 119 | const where = () => ({ store, dir: origin, owner: "o", name: "r" }); | |
| 120 | ||
| 121 | beforeEach(async () => { | |
| 122 | root = await mkdtemp(join(tmpdir(), "forge-packs-unit-")); | |
| 123 | origin = join(root, "origin.git"); | |
| 124 | work = join(root, "work"); | |
| 125 | store = dirStore(join(root, "store")); | |
| 126 | gitOut(root, "init", "--bare", "-q", "--initial-branch=main", origin); | |
| 127 | gitOut(root, "init", "-q", "--initial-branch=main", work); | |
| 128 | await writeFile(join(work, "a"), "1"); | |
| 129 | gitOut(work, "add", "."); | |
| 130 | gitOut(work, "commit", "-m", "one"); | |
| 131 | c1 = gitOut(work, "rev-parse", "HEAD"); | |
| 132 | gitOut(work, "push", origin, "HEAD:refs/heads/main"); | |
| 133 | // The second commit's objects reach the repository (as a push's quarantine would) with no ref. | |
| 134 | await writeFile(join(work, "b"), "2"); | |
| 135 | gitOut(work, "add", "."); | |
| 136 | gitOut(work, "commit", "-m", "two"); | |
| 137 | c2 = gitOut(work, "rev-parse", "HEAD"); | |
| 138 | gitOut(work, "push", origin, "HEAD:refs/heads/scratch"); | |
| 139 | gitOut(origin, "update-ref", "-d", "refs/heads/scratch"); | |
| 140 | }); | |
| 141 | afterEach(() => rm(root, { recursive: true, force: true })); | |
| 142 | ||
| 143 | const update = { oldOid: "", newOid: "", ref: "refs/heads/main" }; | |
| 144 | const move = () => [{ ...update, oldOid: c1, newOid: c2 }]; | |
| 145 | ||
| 146 | test("a push git never applied leaves a pack and no record, and a rebuild never reads it", async () => { | |
| 147 | await storePush({ ...where(), updates: move(), gitEnvForQuarantine: {} }); | |
| 148 | const keys = await store.list("packs/o/r/"); | |
| 149 | expect(keys.some((k) => k.includes("/pending/") && k.endsWith(".pack"))).toBe(true); | |
| 150 | // Only the history before the store: the unapplied push has no record. | |
| 151 | expect(await pushKeys(store, "o", "r")).toHaveLength(1); | |
| 152 | const into = join(root, "rebuilt.git"); | |
| 153 | expect(await rebuildRepo({ store, dir: into, owner: "o", name: "r" })).toBe(1); | |
| 154 | expect(refs(into)).toBe(`refs/heads/main ${c1}`); | |
| 155 | }); | |
| 156 | ||
| 157 | test("a repository that had history before the store rebuilds, and an applied push is committed", async () => { | |
| 158 | await storePush({ ...where(), updates: move(), gitEnvForQuarantine: {} }); | |
| 159 | gitOut(origin, "update-ref", "refs/heads/main", c2, c1); | |
| 160 | await commitPush({ ...where(), updates: move() }); | |
| 161 | const into = join(root, "rebuilt.git"); | |
| 162 | expect(await rebuildRepo({ store, dir: into, owner: "o", name: "r" })).toBe(2); | |
| 163 | expect(refs(into)).toBe(refs(origin)); | |
| 164 | expect(gitOut(into, "fsck", "--no-dangling")).not.toContain("missing"); | |
| 165 | }); | |
| 166 | ||
| 167 | test("a push committed with no pack waiting gets one made from the repository", async () => { | |
| 168 | gitOut(origin, "update-ref", "refs/heads/main", c2, c1); | |
| 169 | const key = await commitPush({ ...where(), updates: move() }); | |
| 170 | const record = readRecord((await store.get(`${key}.json`))!); | |
| 171 | expect(record?.pack).toMatch(/^pending\//); | |
| 172 | expect(await store.size(`packs/o/r/${record!.pack}.pack`)).toBeGreaterThan(0); | |
| 173 | }); | |
| 174 | ||
| 175 | test("a record whose old value is not what the repository holds stops the rebuild", async () => { | |
| 176 | await storePush({ ...where(), updates: move(), gitEnvForQuarantine: {} }); | |
| 177 | const wrong = { oldOid: "1".repeat(c1.length), newOid: c2, ref: "refs/heads/main" }; | |
| 178 | await store.put("packs/o/r/9999999999999-aaaaaaaa.json", JSON.stringify({ updates: [wrong] })); | |
| 179 | await expect(rebuildRepo({ store, dir: join(root, "x.git"), owner: "o", name: "r" })).rejects.toThrow("is not at"); | |
| 180 | }); | |
| 181 | ||
| 182 | test("an unreadable record, a missing pack and an empty store each stop the rebuild", async () => { | |
| 183 | await expect(rebuildRepo({ store, dir: join(root, "x.git"), owner: "o", name: "r" })).rejects.toThrow("no pushes"); | |
| 184 | await store.put("packs/o/r/0000000000001-aaaaaaaa.json", "{not json"); | |
| 185 | await expect(rebuildRepo({ store, dir: join(root, "y.git"), owner: "o", name: "r" })).rejects.toThrow("unreadable"); | |
| 186 | await store.delete("packs/o/r/0000000000001-aaaaaaaa.json"); | |
| 187 | const pack = `pending/${"a".repeat(64)}/0000000000001-aaaaaaaa`; | |
| 188 | await store.put("packs/o/r/0000000000002-aaaaaaaa.json", JSON.stringify({ pack, updates: [] })); | |
| 189 | await expect(rebuildRepo({ store, dir: join(root, "z.git"), owner: "o", name: "r" })).rejects.toThrow("pack is missing"); | |
| 190 | }); | |
| 191 | ||
| 192 | test("a record is read only with safe oids, refs under refs/ and a named pack", () => { | |
| 193 | const enc = (v: unknown) => new TextEncoder().encode(JSON.stringify(v)); | |
| 194 | const ok = { oldOid: c1, newOid: c2, ref: "refs/heads/main" }; | |
| 195 | expect(readRecord(enc({ updates: [ok] }))?.updates).toHaveLength(1); | |
| 196 | expect(readRecord(enc({ updates: [{ ...ok, newOid: "--upload-pack=x" }] }))).toBeUndefined(); | |
| 197 | expect(readRecord(enc({ updates: [{ ...ok, ref: "HEAD" }] }))).toBeUndefined(); | |
| 198 | expect(readRecord(enc({ updates: [ok], pack: "../../etc" }))).toBeUndefined(); | |
| 199 | expect(readRecord(enc({ updates: "no" }))).toBeUndefined(); | |
| 200 | }); | |
| 201 | ||
| 202 | test("a failed record write deletes the pack it followed", async () => { | |
| 203 | const failing: BlobStore = { ...store, put: () => Promise.reject(new Error("bucket down")) }; | |
| 204 | await expect(storePush({ ...where(), store: failing, updates: move(), gitEnvForQuarantine: {} })).rejects.toThrow("bucket down"); | |
| 205 | expect(await store.list("packs/o/r/")).toEqual([]); | |
| 206 | }); | |
| 207 | ||
| 208 | test("a store that gives no answer refuses the push in time, not never", async () => { | |
| 209 | const hung: BlobStore = { ...store, putStream: () => new Promise(() => {}) }; | |
| 210 | const started = Date.now(); | |
| 211 | await expect(storePush({ ...where(), store: hung, updates: move(), gitEnvForQuarantine: {}, ms: 100 })).rejects.toThrow("no answer"); | |
| 212 | expect(Date.now() - started).toBeLessThan(5000); | |
| 213 | }); | |
| 214 | ||
| 215 | test("a rebuild is refused into a repository that already has refs", async () => { | |
| 216 | await storePush({ ...where(), updates: move(), gitEnvForQuarantine: {} }); | |
| 217 | await expect(rebuildRepo({ ...where(), dir: origin })).rejects.toThrow("already has refs"); | |
| 218 | }); | |
| 219 | }); |
test/spawn-pipes.test.ts −1
| @@ -23,7 +23,6 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = { | ||
| 23 | 23 | "src/spawn/archive.ts": { sites: ["stdout+stderr"], reason: "tar() reads the listing from stdout and the failure text from stderr, then waits for exit" }, |
| 24 | 24 | "src/spawn/cell.ts": { sites: ["stdout+stderr"], reason: "drain() reads the child forge's stdout and stderr to its log until exit" }, |
| 25 | 25 | "src/blob/large.ts": { sites: ["stdout"], reason: "cat-file stdout is the blob, read to the end into the store; stderr is ignored" }, |
| 26 | "src/blob/packs.ts": { sites: ["stdout"], reason: "pack-objects stdout streams into the store until the child exits; stderr is ignored" }, | |
| 27 | 26 | "src/chaos/faults.ts": { sites: ["stdout"], reason: "stdout is read until the kill closes it, then cancelled; stderr is ignored" }, |
| 28 | 27 | "src/crew/claude.ts": { sites: ["stdout+stderr", "stdout"], reason: "session pumps stdout and stderr; --version awaits stdout, stderr ignored" }, |
| 29 | 28 | "src/crew/claude_usage.ts": { sites: ["stdout"], reason: "/usage stdout awaited with the exit, under a kill timer; stderr ignored" }, |
test/spawn-sites.test.ts −2
| @@ -21,8 +21,6 @@ const SITES: Record<string, string> = { | ||
| 21 | 21 | "runs the app's own `tty` command from forge.json, a writer's text, in the app's cell; the person at the terminal reaches only the pty's stdin, never argv", |
| 22 | 22 | "src/blob/large.ts": |
| 23 | 23 | "`git cat-file blob <oid>` in a repository the forge made, the oid checked as a safe hex id first; nothing else from a request", |
| 24 | "src/blob/packs.ts": | |
| 25 | "`git pack-objects` and `git index-pack` in a repository the forge made, with oids checked as safe hex ids first; nothing else from a request", | |
| 26 | 24 | "src/chaos/faults.ts": |
| 27 | 25 | "chaos harness: runs bun on its own worker.ts with a database path and repo id the harness made", |
| 28 | 26 | "src/chaos/invariants.ts": |
test/timers-named.test.ts −1
| @@ -99,7 +99,6 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 99 | 99 | ...allow("setTimeout", `an ssh login's auth deadline, ${PER_CONNECTION}`, [["src/ssh/server.ts", "() => { this.transport.disconnect("]]), |
| 100 | 100 | ...allow("setInterval", `an ssh connection's idle watch once it is in (#14786), ${PER_CONNECTION}`, [["src/ssh/server.ts", "() => { if (this.channels.openCount > 0)"]]), |
| 101 | 101 | ...allow("setTimeout", "a v1.0.0 close's proof deadline: it rejects a promise and does no work on the loop", [["src/actions/chapters.ts", "() => reject(new Error(\"proof timed out\"))"]]), |
| 102 | ...allow("setTimeout", "a pack store call's deadline: it rejects a promise and does no work on the loop, cleared when the call ends", [["src/blob/packs.ts", "() => reject(new Error(`the store gave no answer"]]), | |
| 103 | 102 | ...allow("setTimeout", "a maintenance duty's deadline on one call: it rejects a promise and does no work on the loop", [["src/maintain/runner.ts", "() => reject(new Error(\"timed out\"))"]]), |
| 104 | 103 | ...allow("setTimeout", "an app request's look-again sleep in the ladder: it holds one request, does no work on the loop, and ends within the bound", [["src/http/app_turn.ts", "r"]]), |
| 105 | 104 | ...allow("setTimeout", `a media stream's idle deadline, ${PER_CONNECTION}`, [["src/git/read.ts", "() => { finish(); controller.error("]]), |
new above
offline