32 files, 2397 lines added, 22 removed.
Binary file package-lock.json changed: 8a30a196a127 -> 346745f531bc
--- a/package.json
+++ b/package.json
@@ -11,13 +11,20 @@
1212 "test": "node --import ./client/test/setup.ts --test \"src/**/*.test.ts\" \"worker/project/**/*.test.ts\" \"client/test/**/*.test.ts\" \"scripts/**/*.test.ts\" \"server/test/**/*.test.ts\"", 1313 "typecheck": "tsc --noEmit -p tsconfig.json", 14− "check": "npm run typecheck && npm run typecheck:server && npm test",
14+ "check": "npm run check:git-runtime && npm run typecheck && npm run typecheck:server && npm test", 1515 "build": "node scripts/build-client.mjs", 1616 "pack:npm": "node scripts/pack-npm.mjs", 1717 "check:changed": "node scripts/check-changed.mjs", 1818 "format": "biome check --write .", 1919 "lint": "biome ci .", 20− "typecheck:server": "tsc --noEmit -p server/tsconfig.json"
20+ "typecheck:server": "tsc --noEmit -p server/tsconfig.json", 21+ "install:git-runtime": "node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git", 22+ "check:git-runtime": "node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check", 23+ "postinstall": "npm run install:git-runtime", 24+ "prebuild": "npm run check:git-runtime", 25+ "pretest": "npm run check:git-runtime", 26+ "pretypecheck": "npm run check:git-runtime", 27+ "pretypecheck:server": "npm run check:git-runtime" 2229 "devDependencies": { 2330 "@biomejs/biome": "2.5.15", @@ -27,7 +34,7 @@
2734 "typescript": "^5.9.3" 30− "isomorphic-git": "^1.43.0",
37+ "isomorphic-git": "1.44.2", Binary file server/package-lock.json changed: f5cebad6e233 -> 68f93bb4aa97
--- a/server/package.json
+++ b/server/package.json
@@ -8,10 +8,15 @@
99 "dev": "wrangler dev --local", 1010 "deploy": "wrangler deploy", 11− "typecheck": "tsc --noEmit -p tsconfig.json"
11+ "typecheck": "tsc --noEmit -p tsconfig.json", 12+ "install:git-runtime": "node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git", 13+ "check:git-runtime": "node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check", 14+ "postinstall": "npm run install:git-runtime", 15+ "predev": "npm run check:git-runtime", 16+ "predeploy": "npm run check:git-runtime" 14− "isomorphic-git": "^1.43.0"
19+ "isomorphic-git": "1.44.2" 1621 "devDependencies": { 1722 "@cloudflare/workers-types": "^5.20261001.1", --- /dev/null
+++ b/server/scripts/capacity-git-bounded-fifo.mjs
@@ -0,0 +1,61 @@
1+/** One pending chunk; a producer cannot advance until the consumer takes it. */ 2+export class BoundedPackFIFO { 3+ constructor(cancel = async () => {}) { 6+ this.error = undefined; 7+ this.pending = undefined; 8+ this.reader = undefined; 9+ this.writer = undefined; 12+ if (this.ended) throw this.error ?? Error("Pack stream is closed"); 13+ if (this.pending !== undefined || this.writer) throw Error("Concurrent pack writes"); 15+ const reader = this.reader; 16+ this.reader = undefined; 17+ reader.resolve({ value, done: false }); 20+ this.pending = value; 21+ await new Promise((resolve, reject) => { 22+ this.writer = { resolve, reject }; 26+ if (this.error) throw this.error; 27+ if (this.pending !== undefined) { 28+ const value = this.pending; 29+ this.pending = undefined; 30+ this.writer?.resolve(); 31+ this.writer = undefined; 32+ return { value, done: false }; 34+ if (this.ended) return { done: true }; 35+ if (this.reader) throw Error("Concurrent pack reads"); 36+ return new Promise((resolve, reject) => { 37+ this.reader = { resolve, reject }; 42+ this.reader?.resolve({ done: true }); 43+ this.reader = undefined; 48+ this.pending = undefined; 49+ this.reader?.reject(error); 50+ this.writer?.reject(error); 51+ this.reader = this.writer = undefined; 54+ this.destroy(Error("Pack consumer cancelled")); 56+ return { done: true }; 58+ [Symbol.asyncIterator]() { --- /dev/null
+++ b/server/scripts/capacity-install-git-runtime.mjs
@@ -0,0 +1,61 @@
1+import { execFileSync } from "node:child_process"; 2+import { createHash } from "node:crypto"; 3+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; 4+import { tmpdir } from "node:os"; 5+import { basename, dirname, join, resolve } from "node:path"; 6+import { fileURLToPath } from "node:url"; 8+const scripts = dirname(fileURLToPath(import.meta.url)); 9+const rootIndex = process.argv.indexOf("--root"); 10+if (rootIndex < 0 || !process.argv[rootIndex + 1]) 11+ throw Error("Pass --root with the exact isomorphic-git package directory"); 12+const root = resolve(process.argv[rootIndex + 1]); 13+const hash = (bytes) => createHash("sha256").update(bytes).digest("hex"); 15+ "index.js": "66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084", 16+ "index.cjs": "b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367", 19+ "index.js": "50ada141b506bff7cced797098f5ea70a6e40cda859884cc25b0dea985b10592", 20+ "index.cjs": "3b8a78b7145330038cf56e057f7726004a78d0af9a55845b685cf1f65443bae0", 22+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2") 23+ throw Error("Unsupported Git version"); 24+const installed = Object.fromEntries(Object.keys(original).map((file) => [file, readFileSync(join(root, file))])); 25+if (Object.entries(expected).every(([file, digest]) => hash(installed[file]) === digest)) { 26+ console.log("Verified the complete Git capacity runtime patch."); 29+if (process.argv.includes("--check")) throw Error("Complete Git capacity runtime patch is absent or modified"); 30+for (const [file, digest] of Object.entries(original)) { 31+ if (hash(installed[file]) !== digest) throw Error(`Unrecognized or partially patched Git bundle: ${file}`); 33+const temporary = mkdtempSync(join(tmpdir(), "abso-git-patch-")); 34+if (dirname(resolve(temporary)) !== resolve(tmpdir()) || !basename(temporary).startsWith("abso-git-patch-")) 35+ throw Error("Unexpected temporary cleanup path"); 37+ const staged = join(temporary, "capacity-git-dependency-sandbox/node_modules/isomorphic-git"); 38+ mkdirSync(staged, { recursive: true }); 39+ copyFileSync(join(root, "package.json"), join(staged, "package.json")); 40+ for (const [file, bytes] of Object.entries(installed)) writeFileSync(join(staged, file), bytes); 41+ copyFileSync(join(scripts, "capacity-git-bounded-fifo.mjs"), join(temporary, "capacity-git-bounded-fifo.mjs")); 42+ for (const stage of ["push", "fetch", "sideband", "progress", "pump"]) { 43+ execFileSync(process.execPath, [join(scripts, `capacity-patch-git-${stage}.mjs`)], { 48+ const outputs = Object.fromEntries(Object.keys(expected).map((file) => [file, readFileSync(join(staged, file))])); 49+ for (const [file, digest] of Object.entries(expected)) { 50+ if (hash(outputs[file]) !== digest) throw Error(`Unexpected complete Git patch: ${file}`); 52+ // All stages and both final hashes pass before touching the installed package. 53+ for (const [file, bytes] of Object.entries(outputs)) writeFileSync(join(root, file), bytes); 54+ console.log("Installed and verified the complete Git capacity runtime patch."); 57+ rmSync(temporary, { recursive: true, force: true }); 59+ console.warn("Could not remove the Git patch staging directory."); --- /dev/null
+++ b/server/scripts/capacity-patch-git-fetch.mjs
@@ -0,0 +1,91 @@
1+import { createHash } from "node:crypto"; 2+import { readFileSync, writeFileSync } from "node:fs"; 3+import { join } from "node:path"; 5+// Extends only the reviewed-version push prototype in this isolated dependency tree. 6+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git"; 8+ "index.js": "0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8", 9+ "index.cjs": "6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7", 11+const hash = (source) => createHash("sha256").update(source).digest("hex"); 12+const expectedOutputs = { 13+ "index.js": "eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d", 14+ "index.cjs": "33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447", 16+function once(source, before, after) { 17+ if (source.split(before).length !== 2) throw Error("Fetch patch anchor mismatch"); 18+ return source.replace(before, after); 20+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2") { 21+ throw Error("Unsupported Git version"); 24+const installed = Object.fromEntries(Object.keys(inputs).map((file) => [file, readFileSync(join(root, file), "utf8")])); 25+if (Object.entries(expectedOutputs).every(([file, expected]) => hash(installed[file]) === expected)) { 29+ scope: "Isolated fetch prototype", 30+ bundles: expectedOutputs, 35+for (const [file, expected] of Object.entries(inputs)) { 36+ const source = installed[file]; 37+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`); 40+ " const packfile = Buffer.from(await collect(response.packfile));", 41+ ` const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')]; 43+ await diskPack.ingest(response.packfile, () => new pako.Inflate({ chunkSize: 16384 })); 44+ if (raw.body.error) throw raw.body.error 46+ defaultBranch: response.HEAD, 47+ fetchHead: response.FETCH_HEAD.oid, 48+ fetchHeadDescription: response.FETCH_HEAD.description, 50+ if (response.headers) result.headers = response.headers; 51+ if (prune) result.pruned = response.pruned; 54+ const packfile = Buffer.from(await collect(response.packfile));`, 56+ const readStart = result.indexOf("async function _readObject({"); 57+ const readEnd = result.indexOf("\nclass AlreadyExistsError", readStart); 58+ if (readStart < 0 || readEnd < 0) throw Error("Missing object reader boundary"); 59+ const readFunction = once( 60+ result.slice(readStart, readEnd), 61+ " // Curry the current read method so that the packfile un-deltification", 62+ ` const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')]; 63+ if (diskPack && format === 'content') { 64+ const stored = await diskPack.read(oid); 65+ if (stored) return stored 68+ // Curry the current read method so that the packfile un-deltification`, 70+ result = result.slice(0, readStart) + readFunction + result.slice(readEnd); 71+ if (hash(result) !== expectedOutputs[file]) throw Error(`Unexpected fetch patch output: ${file}`); 72+ outputs.push({ file, result, sha256: hash(result) }); 74+// Validate both installed bundles and every anchor before either write. 75+if (!process.argv.includes("--check")) { 76+ for (const { file, result } of outputs) writeFileSync(join(root, file), result); 78+ "capacity-git-fetch-patch-manifest.json", 80+ outputs.map(({ file, sha256 }) => ({ file, sha256 })), 88+ scope: "Isolated fetch prototype; runtime adapter and transport acceptance still required", 89+ outputs: outputs.map(({ file, sha256 }) => ({ file, sha256 })), --- /dev/null
+++ b/server/scripts/capacity-patch-git-progress.mjs
@@ -0,0 +1,53 @@
1+import { createHash } from "node:crypto"; 2+import { readFileSync, writeFileSync } from "node:fs"; 3+import { join } from "node:path"; 5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git"; 7+ "index.js": "20512aae32eb8dd64b798c0dd4ba666ea801bec6c9de37d259527c93ce3e48ec", 8+ "index.cjs": "b4cd8c52f3fa945b553dbb7a740c965b48b93dfc2469f10849e111abd00c7460", 10+const hash = (value) => createHash("sha256").update(value).digest("hex"); 11+function once(source, before, after) { 12+ if (source.split(before).length !== 2) throw Error(`Progress anchor mismatch: ${before}`); 13+ return source.replace(before, after); 16+for (const [file, expected] of Object.entries(inputs)) { 17+ let source = readFileSync(join(root, file), "utf8"); 18+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`); 21+ " static demux(input, bounded = false) {", 22+ " static demux(input, bounded = false, discardProgress = false) {", 26+ " progress.write(line.slice(1));", 27+ " if (!discardProgress) progress.write(line.slice(1));", 29+ source = once(source, " progress.write(error);", " if (!discardProgress) progress.write(error);"); 32+ "async function parseUploadPackResponse(stream, bounded = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);", 33+ "async function parseUploadPackResponse(stream, bounded = false, discardProgress = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded, discardProgress);", 37+ " const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));", 38+ " const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]), Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]) && !onProgress && !onMessage);", 40+ outputs.push({ file, source, sha256: hash(source) }); 42+if (!process.argv.includes("--check")) { 43+ for (const { file, source } of outputs) writeFileSync(join(root, file), source); 45+ "capacity-git-progress-patch-manifest.json", 47+ outputs.map(({ file, sha256 }) => ({ file, sha256 })), 53+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 })))); --- /dev/null
+++ b/server/scripts/capacity-patch-git-pump.mjs
@@ -0,0 +1,31 @@
1+import { createHash } from "node:crypto"; 2+import { readFileSync, writeFileSync } from "node:fs"; 3+import { join } from "node:path"; 5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git"; 7+ "index.js": "4e0e9ee5a21754ebd718864dba2705385fc8254ed0c9e0d4ff56c8a2ff6fccf8", 8+ "index.cjs": "fe66bb236ed6d95bf720e646afc9fff1dbe3efbc441b194efde09b1b698cd583", 10+const hash = (value) => createHash("sha256").update(value).digest("hex"); 11+function once(source, before, after) { 12+ if (source.split(before).length !== 2) throw Error("Git pump anchor mismatch"); 13+ return source.replace(before, after); 16+for (const [file, expected] of Object.entries(inputs)) { 17+ let source = readFileSync(join(root, file), "utf8"); 18+ if (hash(source) !== expected) throw Error(`Unrecognized pump input: ${file}`); 21+ " const nextBit = async function () {", 22+ " const nextBit = async function () {\n while (true) {", 24+ source = once(source, " if (line === null) return nextBit()", " if (line === null) continue"); 25+ source = once(source, " return nextBit();\n };", " }\n };"); 26+ outputs.push({ file, source, sha256: hash(source) }); 28+if (!process.argv.includes("--check")) { 29+ for (const { file, source } of outputs) writeFileSync(join(root, file), source); 31+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 })))); --- /dev/null
+++ b/server/scripts/capacity-patch-git-push.mjs
@@ -0,0 +1,94 @@
1+import { createHash } from "node:crypto"; 2+import { readFileSync, writeFileSync } from "node:fs"; 3+import { join } from "node:path"; 5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git"; 7+ "index.js": "66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084", 8+ "index.cjs": "b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367", 11+ "index.js": "0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8", 12+ "index.cjs": "6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7", 14+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2") 15+ throw Error("Unsupported Git version"); 16+const installed = Object.fromEntries( 17+ Object.keys(hashes).map((file) => [ 20+ .update(readFileSync(join(root, file))) 24+if (Object.keys(patched).every((file) => installed[file] === patched[file])) { 25+ console.log(JSON.stringify({ verified: true, version: "1.44.2", bundles: installed })); 28+if (process.argv.includes("--check")) throw Error("Git runtime patch is absent or modified"); 29+function replaceOnce(source, before, after) { 30+ if (source.split(before).length !== 2) throw Error("Patch anchor mismatch"); 31+ return source.replace(before, after); 34+for (const [file, expected] of Object.entries(hashes)) { 35+ const original = readFileSync(join(root, file), "utf8"); 36+ if (createHash("sha256").update(original).digest("hex") !== expected) throw Error(`Unrecognized source: ${file}`); 37+ const start = original.indexOf("async function _pack({"); 38+ const end = original.indexOf("\n// @ts-check", start); 39+ if (start < 0 || end < 0) throw Error("Missing pack implementation"); 40+ const old = original.slice(start, end); 41+ let streamed = replaceOnce(old, "async function _pack({", "async function* _packStream({"); 42+ streamed = replaceOnce( 44+ " for (const oid of oids) {", 45+ " yield* outputStream;\n outputStream.length = 0;\n for (const oid of oids) {", 47+ streamed = replaceOnce( 49+ " await writeObject({ write, object, stype: type });", 50+ " await writeObject({ write, object, stype: type });\n yield* outputStream;\n outputStream.length = 0;", 52+ streamed = replaceOnce(streamed, " outputStream.push(digest);\n return outputStream", " yield digest;"); 54+ original.slice(0, start) + 56+ "\nasync function _pack(options) {\n const output = [];\n for await (const chunk of _packStream(options)) output.push(chunk);\n return output;\n}\n" + 58+ const begin = result.indexOf(" const packstream2 = _delete"); 59+ const finish = result.indexOf(" const res = await GitRemoteHTTP.connect({", begin); 60+ if (begin < 0 || finish < 0) throw Error("Missing push implementation"); 62+ result.slice(0, begin) + 63+ ` const packoids = [...objects]; 64+ // Recreate the stream for every authentication retry; never retain a whole pack. 66+ async *[Symbol.asyncIterator]() { 68+ if (!_delete) yield* _packStream({ fs, cache, gitdir, oids: packoids }); 72+ result.slice(finish); 73+ result = replaceOnce(result, " body: [...packstream1, ...packstream2],", " body: packbody,"); 74+ const sha256 = createHash("sha256").update(result).digest("hex"); 75+ if (sha256 !== patched[file]) throw Error(`Unexpected patch output: ${file}`); 76+ outputs.push({ file, result, sha256 }); 78+// Validate every input before changing either runtime bundle. 79+for (const output of outputs) writeFileSync(join(root, output.file), output.result); 81+ "capacity-git-push-patch-manifest.json", 83+ outputs.map(({ file, sha256 }) => ({ file, sha256 })), 91+ patched: outputs.map(({ file, sha256 }) => ({ file, sha256 })), 92+ scope: "Isolated push patch; fetch and install integration incomplete", --- /dev/null
+++ b/server/scripts/capacity-patch-git-sideband.mjs
@@ -0,0 +1,58 @@
1+import { createHash } from "node:crypto"; 2+import { readFileSync, writeFileSync } from "node:fs"; 3+import { join } from "node:path"; 5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git"; 7+ "index.js": "eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d", 8+ "index.cjs": "33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447", 10+const hash = (value) => createHash("sha256").update(value).digest("hex"); 11+const queue = readFileSync("capacity-git-bounded-fifo.mjs", "utf8").replace("export class", "class"); 12+function once(source, before, after) { 13+ if (source.split(before).length !== 2) throw Error(`Sideband anchor mismatch: ${before}`); 14+ return source.replace(before, after); 17+for (const [file, expected] of Object.entries(inputs)) { 18+ let source = readFileSync(join(root, file), "utf8"); 19+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`); 20+ source = once(source, "class GitSideBand {", `${queue}\nclass GitSideBand {`); 21+ source = once(source, " static demux(input) {", " static demux(input, bounded = false) {"); 24+ " const packfile = new FIFO();", 25+ " const packfile = bounded ? new BoundedPackFIFO(async () => { await getIterator(input).return?.(); }) : new FIFO();", 27+ source = once(source, " packfile.write(line.slice(1));", " await packfile.write(line.slice(1));"); 30+ " nextBit();\n };\n nextBit();", 33+ nextBit().catch(error => { packetlines.destroy(error); progress.destroy(error); packfile.destroy(error); });`, 37+ "async function parseUploadPackResponse(stream) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream);", 38+ "async function parseUploadPackResponse(stream, bounded = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);", 42+ " const response = await parseUploadPackResponse(raw.body);", 43+ " const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));", 45+ outputs.push({ file, source, sha256: hash(source) }); 47+if (!process.argv.includes("--check")) { 48+ for (const { file, source } of outputs) writeFileSync(join(root, file), source); 50+ "capacity-git-sideband-patch-manifest.json", 52+ outputs.map(({ file, sha256 }) => ({ file, sha256 })), 58+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 })))); --- /dev/null
+++ b/server/src/git-blob-text.ts
@@ -0,0 +1,22 @@
1+import type { GitByteRanges } from "./git-delta-stream.ts"; 3+export class InvalidGitUtf8 extends Error {} 5+/** Strict UTF-8 decoding with the same BOM handling as whole-file intake. */ 6+export function* gitBlobText(bytes: GitByteRanges): IterableIterator<string> { 7+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }); 9+ const decode = (chunk?: Uint8Array, stream = false) => { 11+ return decoder.decode(chunk, { stream }); 13+ throw new InvalidGitUtf8("Git blob is not UTF-8", { cause: error }); 16+ for (let at = 0; at < bytes.byteLength; at += size) { 17+ const text = decode(bytes.read(at, Math.min(size, bytes.byteLength - at)), true); 18+ for (let offset = 0; offset < text.length; offset += size) yield text.slice(offset, offset + size); 20+ const tail = decode(); 21+ if (tail) yield tail; --- /dev/null
+++ b/server/src/git-delta-stream.ts
@@ -0,0 +1,73 @@
1+export interface GitByteRanges { 2+ readonly byteLength: number; 3+ read(start: number, length: number): Uint8Array; 6+/** Decode without retaining the base or complete result. Caller must roll back output if decoding throws. */ 7+export function applyGitDeltaChunks( 10+ write: (chunk: Uint8Array) => void, 11+ maxResultBytes: number, 13+ if (!Number.isSafeInteger(maxResultBytes) || maxResultBytes < 0) throw Error("invalid delta result limit"); 16+ let cached: Uint8Array = new Uint8Array(0), 19+ if (position >= delta.byteLength) throw Error("truncated Git delta"); 20+ if (position < cacheStart || position >= cacheStart + cached.length) { 21+ cacheStart = position; 22+ const count = Math.min(65536, delta.byteLength - position); 23+ cached = delta.read(position, count); 24+ if (cached.length !== count) throw Error("missing delta bytes"); 26+ return cached[position++ - cacheStart]!; 28+ const integer = () => { 31+ for (let i = 0; i < 8; i++) { 33+ value += (next & 127) * multiplier; 34+ if (!Number.isSafeInteger(value)) throw Error("Git delta integer overflow"); 35+ if (!(next & 128)) return value; 38+ throw Error("Git delta integer overflow"); 40+ if (integer() !== base.byteLength) throw Error("Git delta base length mismatch"); 41+ const size = integer(); 42+ if (size > maxResultBytes) throw Error("Git delta result exceeds bound"); 43+ const emit = (chunk: Uint8Array) => { 44+ if (produced + chunk.length > size) throw Error("Git delta result length mismatch"); 46+ produced += chunk.length; 48+ while (position < delta.byteLength) { 49+ const instruction = byte(); 50+ if (instruction & 128) { 53+ for (let i = 0; i < 4; i++) if (instruction & (1 << i)) offset += byte() * 2 ** (8 * i); 54+ for (let i = 0; i < 3; i++) if (instruction & (16 << i)) length += byte() * 2 ** (8 * i); 55+ if (!length) length = 65536; 56+ if (offset + length > base.byteLength) throw Error("Git delta copy exceeds base"); 57+ if (produced + length > size) throw Error("Git delta result length mismatch"); 58+ for (let at = 0; at < length; at += 65536) { 59+ const count = Math.min(65536, length - at), 60+ chunk = base.read(offset + at, count); 61+ if (chunk.length !== count) throw Error("missing delta base bytes"); 65+ if (!instruction) throw Error("invalid Git delta instruction"); 66+ const literal = new Uint8Array(instruction); 67+ for (let i = 0; i < instruction; i++) literal[i] = byte(); 71+ if (produced !== size) throw Error("Git delta result length mismatch"); --- /dev/null
+++ b/server/src/git-disk-intake.ts
@@ -0,0 +1,102 @@
1+import type { SqliteStorage } from "./engine-project.ts"; 2+import type { StoredGitBytes } from "./git-object-bytes.ts"; 3+import { decodeGitPack, type PackInflater } from "./git-pack-decode.ts"; 4+import { GitPackResolver } from "./git-pack-resolver.ts"; 5+import { GitPackSpool } from "./git-pack-spool.ts"; 7+/** One clone's temporary pack store. The caller must dispose it in finally. */ 8+export class GitDiskIntake { 9+ /** Cold object construction only, before any intake or reader is created. */ 10+ static recover(storage: SqliteStorage): void { 11+ // Constructors establish scratch tables only; they do not alter project state. 12+ const resolver = new GitPackResolver(storage, 0); 13+ storage.transactionSync(() => { 14+ GitPackSpool.recover(storage); 15+ storage.sql.exec("DELETE FROM git_pack_resolve"); 16+ storage.sql.exec("DELETE FROM git_object_bytes"); 17+ storage.sql.exec("DELETE FROM git_object_meta"); 18+ storage.sql.exec("DELETE FROM git_object_budget"); 22+ private readonly spool: GitPackSpool; 23+ private readonly resolver: GitPackResolver; 24+ private readonly maxPackBytes: number; 25+ private state: "new" | "loading" | "ready" | "closed" = "new"; 26+ constructor(storage: SqliteStorage, maxPackBytes: number, maxObjectBytes: number, maxDecodedBytes = maxPackBytes) { 27+ if (!Number.isSafeInteger(maxPackBytes) || maxPackBytes < 32) throw Error("invalid pack limit"); 28+ this.maxPackBytes = maxPackBytes; 29+ this.resolver = new GitPackResolver(storage, maxObjectBytes, maxDecodedBytes); 30+ this.spool = new GitPackSpool(storage); 32+ attach(cache: object): void { 33+ const key = Symbol.for("abso.git.disk-pack"); 34+ if (key in cache) throw Error("Git disk intake already attached"); 35+ Object.defineProperty(cache, key, { value: this }); 38+ chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array> | AsyncIterator<Uint8Array>, 39+ createInflater: () => PackInflater, 41+ if (this.state !== "new") throw Error("Git disk intake already used"); 42+ this.state = "loading"; 44+ Symbol.asyncIterator in chunks 45+ ? chunks[Symbol.asyncIterator]() 46+ : Symbol.iterator in chunks 47+ ? chunks[Symbol.iterator]() 51+ [Symbol.asyncIterator]: () => ({ 52+ next: async () => iterator.next(), 53+ return: async () => (iterator.return ? iterator.return() : { done: true as const, value: undefined }), 56+ await this.spool.ingest(source, this.maxPackBytes); 57+ if (this.state !== "loading") throw Error("Git disk intake closed during download"); 58+ decodeGitPack(this.spool, this.resolver, createInflater); 59+ this.spool.dispose(); 60+ this.state = "ready"; 63+ await iterator.return?.(); 65+ /* Preserve the intake failure. */ 71+ bytes(oid: string): StoredGitBytes | undefined { 72+ if (this.state === "closed") throw Error("Git disk intake is closed"); 73+ if (this.state !== "ready") return undefined; 74+ return this.resolver.find(oid); 76+ read(oid: string): { format: "content"; type: string; object: Buffer } | undefined { 77+ const stored = this.bytes(oid); 78+ if (!stored) return undefined; 79+ // Existing Git consumers require one complete object. This does not claim 80+ // bounded blob consumption; it removes whole-pack retention and caching. 81+ const object = Buffer.alloc(stored.byteLength); 82+ for (let at = 0; at < stored.byteLength; at += 65536) { 83+ object.set(stored.read(at, Math.min(65536, stored.byteLength - at)), at); 85+ return { format: "content", type: stored.type, object }; 87+ assertReady(): void { 88+ if (this.state !== "ready") throw Error("Git disk intake was not used by the installed runtime"); 90+ [Symbol.dispose](): void { 94+ if (this.state === "closed") return; 95+ this.state = "closed"; 97+ this.resolver.dispose(); 99+ this.spool.dispose(); --- /dev/null
+++ b/server/src/git-http.ts
@@ -0,0 +1,58 @@
1+import type { HttpClient } from "isomorphic-git"; 3+/** Stream Git HTTP request chunks without a second complete upload buffer. */ 4+export function gitHttp(fetcher: typeof fetch = fetch): HttpClient { 6+ async request({ url, method = "GET", headers = {}, body, signal, fetchOptions = {} }) { 7+ const input = body as AsyncIterable<Uint8Array> | Iterable<Uint8Array> | undefined; 8+ const iterator = input 9+ ? Symbol.asyncIterator in input 10+ ? input[Symbol.asyncIterator]() 11+ : input[Symbol.iterator]() 13+ const stream = iterator 14+ ? new ReadableStream<Uint8Array>( 16+ async pull(controller) { 18+ const next = await iterator.next(); 19+ if (next.done) controller.close(); 20+ else controller.enqueue(next.value); 22+ controller.error(error); 26+ await iterator.return?.(); 29+ { highWaterMark: 0 }, 32+ let response: Response; 34+ const options: RequestInit & { duplex?: string } = { 39+ signal: signal ?? fetchOptions.signal, 40+ ...(stream ? { duplex: "half" } : {}), 42+ response = await fetcher(url, options); 44+ await iterator?.return?.(); 47+ const responseBody = response.body; 51+ statusCode: response.status, 52+ statusMessage: response.statusText, 53+ headers: Object.fromEntries(response.headers.entries()), 54+ body: responseBody ? responseBody[Symbol.asyncIterator]() : (async function* () {})(), --- /dev/null
+++ b/server/src/git-intake-trees.ts
@@ -0,0 +1,77 @@
1+import { StoredText } from "../../src/engine/stored-text.ts"; 2+import type { SqliteStorage } from "./engine-project.ts"; 3+import type { PushedCommits } from "./ingest.ts"; 4+import { SqliteWriterState } from "./writer-host.ts"; 6+type Tree = Pick<PushedCommits["commits"][number], "files" | "modes" | "blobs">; 8+/** Keeps earlier Git trees on disk while later commits are decoded. */ 9+export class GitIntakeTrees { 10+ /** Only at a cold Durable Object start, before any intake can be active. */ 11+ static recover(storage: SqliteStorage): void { 12+ SqliteWriterState.initialize(storage); 13+ storage.sql.exec("DELETE FROM writer_state WHERE namespace GLOB 'git-intake:*'"); 15+ readonly namespace = `git-intake:${crypto.randomUUID()}`; 16+ readonly storage: SqliteStorage; 17+ readonly text: StoredText; 19+ private active = true; 20+ constructor(storage: SqliteStorage) { 21+ this.storage = storage; 22+ SqliteWriterState.initialize(storage); 23+ this.text = new StoredText(new SqliteWriterState(storage, this.namespace), "files"); 25+ /** Created outside any scope containing decoded file text or a whole tree. */ 26+ private getter(key: string): () => string { 28+ if (!this.active) throw Error("Git intake trees are closed"); 29+ return this.text.read(key); 32+ retainFile(files: Record<string, string>, path: string, body: string, oid?: string): void { 37+ for (let at = 0; at < body.length; at += StoredText.chunkCharacters) 38+ yield body.slice(at, at + StoredText.chunkCharacters); 43+ retainChunks(files: Record<string, string>, path: string, chunks: Iterable<string>, oid?: string): void { 44+ if (!this.active) throw Error("Git intake trees are closed"); 45+ if (oid !== undefined && !/^[0-9a-f]{40}$/.test(oid)) throw Error("Invalid Git blob id"); 46+ const key = oid === undefined ? String(this.next++) : `blob:${oid}`; 47+ this.storage.transactionSync(() => { 48+ if (this.text.storage.read(this.text.collection, key) === undefined) this.text.writeChunks(key, chunks); 50+ Object.defineProperty(files, path, { 52+ get: this.getter(key), 55+ retain(tree: Tree): Tree { 56+ if (!this.active) throw Error("Git intake trees are closed"); 57+ const files: Record<string, string> = Object.create(null); 58+ this.storage.transactionSync(() => { 59+ for (const path of Object.keys(tree.files)) { 60+ const key = String(this.next++); 61+ this.text.write(key, tree.files[path]!); 62+ Object.defineProperty(files, path, { 64+ get: this.getter(key), 68+ return { files, modes: tree.modes, blobs: tree.blobs }; 70+ [Symbol.dispose](): void { 75+ this.storage.sql.exec("DELETE FROM writer_state WHERE namespace = ?", this.namespace); --- /dev/null
+++ b/server/src/git-object-bytes.ts
@@ -0,0 +1,146 @@
1+import { createHash } from "node:crypto"; 2+import type { SqliteStorage } from "./engine-project.ts"; 3+import type { GitByteRanges } from "./git-delta-stream.ts"; 5+export type StoredGitBytes = GitByteRanges & { 11+/** Intake-local object bytes; callers own this store's lifetime. */ 12+export class GitObjectBytes { 13+ readonly scope = crypto.randomUUID(); 14+ private closed = false; 15+ private readonly storage: SqliteStorage; 16+ private readonly maxDecodedBytes: number; 17+ constructor(storage: SqliteStorage, maxDecodedBytes = Number.MAX_SAFE_INTEGER) { 18+ if (!Number.isSafeInteger(maxDecodedBytes) || maxDecodedBytes < 0) throw Error("invalid decoded byte limit"); 19+ this.storage = storage; 20+ this.maxDecodedBytes = maxDecodedBytes; 22+ "CREATE TABLE IF NOT EXISTS git_object_bytes (scope TEXT, id TEXT, part INTEGER, data BLOB NOT NULL, PRIMARY KEY(scope,id,part))", 25+ "CREATE TABLE IF NOT EXISTS git_object_meta (scope TEXT, id TEXT, type TEXT, bytes INTEGER, oid TEXT, PRIMARY KEY(scope,id))", 27+ storage.sql.exec("CREATE TABLE IF NOT EXISTS git_object_budget (scope TEXT PRIMARY KEY, decoded INTEGER NOT NULL)"); 28+ storage.sql.exec("INSERT INTO git_object_budget VALUES (?, 0)", this.scope); 30+ private active(): void { 31+ if (this.closed) throw Error("Git object store is closed"); 33+ put(type: string, produce: (write: (bytes: Uint8Array) => void) => void, maxBytes: number): StoredGitBytes { 35+ if (!["blob", "tree", "commit", "tag"].includes(type) || !Number.isSafeInteger(maxBytes) || maxBytes < 0) 36+ throw Error("invalid Git object limits or type"); 37+ const id = crypto.randomUUID(); 38+ this.storage.transactionSync(() => { 39+ const budget = this.storage.sql 40+ .exec("SELECT decoded FROM git_object_budget WHERE scope = ?", this.scope) 41+ .toArray() as { decoded: number }[]; 42+ if (budget.length !== 1) throw Error("missing Git decoded budget"); 43+ const remaining = this.maxDecodedBytes - budget[0]!.decoded; 47+ const pending = new Uint8Array(65536); 48+ const flush = () => { 49+ this.storage.sql.exec( 50+ "INSERT INTO git_object_bytes VALUES (?, ?, ?, ?)", 54+ pending.slice(0, used), 59+ if (length + bytes.length > maxBytes) throw Error("Git object exceeds byte limit"); 60+ if (length + bytes.length > remaining) throw Error("Git pack exceeds total decoded byte limit"); 61+ length += bytes.length; 62+ for (let at = 0; at < bytes.length; ) { 63+ const count = Math.min(pending.length - used, bytes.length - at); 64+ pending.set(bytes.subarray(at, at + count), used); 67+ if (used === pending.length) flush(); 71+ const hash = createHash("sha1").update(`${type} ${length}\0`); 72+ for (let index = 0; index < part; index++) hash.update(this.chunk(id, index)); 73+ this.storage.sql.exec( 74+ "INSERT INTO git_object_meta VALUES (?, ?, ?, ?, ?)", 81+ this.storage.sql.exec("UPDATE git_object_budget SET decoded = decoded + ? WHERE scope = ?", length, this.scope); 85+ private chunk(id: string, part: number): Uint8Array { 87+ const rows = this.storage.sql 88+ .exec("SELECT data FROM git_object_bytes WHERE scope = ? AND id = ? AND part = ?", this.scope, id, part) 89+ .toArray() as { data: ArrayBuffer }[]; 90+ if (rows.length !== 1) throw Error("missing Git object chunk"); 91+ const bytes = new Uint8Array(rows[0]!.data); 92+ if (!bytes.length || bytes.length > 65536) throw Error("invalid Git object chunk"); 95+ get(id: string): StoredGitBytes { 97+ const rows = this.storage.sql 98+ .exec("SELECT type, bytes, oid FROM git_object_meta WHERE scope = ? AND id = ?", this.scope, id) 99+ .toArray() as { type: string; bytes: number; oid: string }[]; 100+ if (rows.length !== 1) throw Error("missing Git object"); 101+ const meta = rows[0]!; 106+ byteLength: meta.bytes, 107+ read: (start, length) => { 110+ !Number.isSafeInteger(start) || 111+ !Number.isSafeInteger(length) || 115+ start + length > meta.bytes 117+ throw Error("invalid Git object range"); 118+ const result = new Uint8Array(length); 119+ for (let copied = 0; copied < length; ) { 120+ const position = start + copied, 121+ chunk = this.chunk(id, Math.floor(position / 65536)); 122+ const offset = position % 65536, 123+ count = Math.min(length - copied, chunk.length - offset); 124+ if (count <= 0) throw Error("truncated Git object chunk"); 125+ result.set(chunk.subarray(offset, offset + count), copied); 132+ /** Remove obsolete delta instructions without refunding their decoded-work budget. */ 133+ remove(id: string): void { 135+ this.storage.sql.exec("DELETE FROM git_object_bytes WHERE scope = ? AND id = ?", this.scope, id); 136+ this.storage.sql.exec("DELETE FROM git_object_meta WHERE scope = ? AND id = ?", this.scope, id); 140+ this.storage.transactionSync(() => { 141+ this.storage.sql.exec("DELETE FROM git_object_bytes WHERE scope = ?", this.scope); 142+ this.storage.sql.exec("DELETE FROM git_object_meta WHERE scope = ?", this.scope); 143+ this.storage.sql.exec("DELETE FROM git_object_budget WHERE scope = ?", this.scope); --- /dev/null
+++ b/server/src/git-pack-decode.ts
@@ -0,0 +1,100 @@
1+import type { GitPackResolver } from "./git-pack-resolver.ts"; 2+import type { GitPackSpool } from "./git-pack-spool.ts"; 4+/** Structural adapter for the pinned Git dependency's streaming inflater. */ 5+export interface PackInflater { 6+ onData: (bytes: Uint8Array) => void; 7+ push(bytes: Uint8Array, final: boolean): unknown; 11+ strm: { avail_in: number }; 14+/** Decode verified disk bytes without collecting a pack or decoded object in memory. */ 15+export function decodeGitPack( 17+ resolver: GitPackResolver, 18+ createInflater: () => PackInflater, 21+ decodeVerifiedPack(spool, resolver, createInflater); 23+ // Intake owns this resolver. Never expose earlier objects from a rejected pack. 29+function decodeVerifiedPack(spool: GitPackSpool, resolver: GitPackResolver, createInflater: () => PackInflater): void { 30+ const end = spool.byteLength - 20; 31+ const header = spool.read(0, 12); 32+ const count = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8); 34+ let cached: Uint8Array = new Uint8Array(0), 37+ if (position >= end) throw Error("truncated Git pack header"); 38+ if (position < cachedAt || position >= cachedAt + cached.length) { 40+ cached = spool.read(position, Math.min(65536, end - position)); 42+ return cached[position++ - cachedAt]!; 44+ for (let index = 0; index < count; index++) { 45+ const offset = position; 46+ let current = byte(); 47+ const kind = (current >> 4) & 7; 48+ let length = current & 15, 50+ while (current & 128) { 52+ length += (current & 127) * factor; 54+ if (!Number.isSafeInteger(length) || !Number.isSafeInteger(factor)) throw Error("invalid Git object size"); 56+ let base: number | string | undefined; 59+ let distance = current & 127; 60+ while (current & 128) { 62+ distance = (distance + 1) * 128 + (current & 127); 63+ if (!Number.isSafeInteger(distance)) throw Error("invalid Git delta distance"); 65+ base = offset - distance; 66+ } else if (kind === 7) { 68+ for (let i = 0; i < 20; i++) reference += byte().toString(16).padStart(2, "0"); 71+ const type = ["", "commit", "tree", "blob", "tag", "", "delta", "delta"][kind]; 72+ if (!type) throw Error("unsupported Git object type"); 77+ const inflater = createInflater(); 79+ inflater.onData = (bytes) => { 80+ decoded += bytes.length; 81+ if (bytes.length > 65536 || decoded > length) throw Error("invalid inflated Git object size"); 84+ while (!inflater.ended) { 85+ if (position >= end) throw Error("truncated compressed Git object"); 86+ const chunk = spool.read(position, Math.min(65536, end - position)); 87+ inflater.push(chunk, false); 88+ if (inflater.err) throw Error(`Git inflate failed: ${inflater.msg}`); 89+ const consumed = chunk.length - inflater.strm.avail_in; 90+ if (consumed <= 0 || consumed > chunk.length) throw Error("Git inflater made no progress"); 91+ position += consumed; 93+ if (decoded !== length) throw Error("inflated Git object size mismatch"); 98+ if (position !== end) throw Error("unexpected bytes after Git pack objects"); --- /dev/null
+++ b/server/src/git-pack-resolver.ts
@@ -0,0 +1,133 @@
1+import type { SqliteStorage } from "./engine-project.ts"; 2+import { applyGitDeltaChunks } from "./git-delta-stream.ts"; 3+import { GitObjectBytes, type StoredGitBytes } from "./git-object-bytes.ts"; 5+/** Scratch index and decoded objects for one pack. No in-memory object map. */ 6+export class GitPackResolver { 7+ readonly scope = crypto.randomUUID(); 8+ readonly objects: GitObjectBytes; 9+ private readonly storage: SqliteStorage; 10+ private readonly maxObjectBytes: number; 11+ private closed = false; 12+ constructor(storage: SqliteStorage, maxObjectBytes: number, maxDecodedBytes = maxObjectBytes) { 13+ if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0) throw Error("invalid object limit"); 14+ this.storage = storage; 15+ this.maxObjectBytes = maxObjectBytes; 16+ this.objects = new GitObjectBytes(storage, maxDecodedBytes); 18+ "CREATE TABLE IF NOT EXISTS git_pack_resolve (scope TEXT, offset INTEGER, raw TEXT, base_offset INTEGER, base_oid TEXT, result TEXT, oid TEXT, depth INTEGER, PRIMARY KEY(scope,offset))", 20+ storage.sql.exec("CREATE INDEX IF NOT EXISTS git_pack_resolve_oid ON git_pack_resolve(scope,oid)"); 22+ "CREATE INDEX IF NOT EXISTS git_pack_unresolved ON git_pack_resolve(scope,offset) WHERE result IS NULL", 25+ private active(): void { 26+ if (this.closed) throw Error("pack resolver is closed"); 28+ add(offset: number, type: string, data: Uint8Array, base?: number | string): void { 29+ this.addChunks(offset, type, (write) => write(data), base); 31+ /** The inflater writes bounded output directly into the transactional object store. */ 35+ produce: (write: (bytes: Uint8Array) => void) => void, 36+ base?: number | string, 39+ if (!Number.isSafeInteger(offset) || offset < 12) throw Error("invalid pack offset"); 40+ if (type === "delta") { 42+ typeof base === "number" 43+ ? !Number.isSafeInteger(base) || base < 12 || base >= offset 44+ : typeof base !== "string" || !/^[0-9a-f]{40}$/.test(base) 46+ throw Error("invalid delta base reference"); 47+ } else if (base !== undefined) throw Error("ordinary object has delta base"); 48+ this.storage.transactionSync(() => { 49+ const stored = this.objects.put(type === "delta" ? "blob" : type, produce, this.maxObjectBytes); 50+ this.storage.sql.exec( 51+ "INSERT INTO git_pack_resolve VALUES (?, ?, ?, ?, ?, ?, ?, ?)", 55+ typeof base === "number" ? base : null, 56+ typeof base === "string" ? base : null, 57+ type === "delta" ? null : stored.id, 58+ type === "delta" ? null : stored.oid, 59+ type === "delta" ? null : 0, 65+ this.storage.transactionSync(() => { 67+ const rows = this.storage.sql 69+ `SELECT p.offset, p.raw, COALESCE(b.result, r.result) AS base, COALESCE(b.depth, r.depth) AS depth 70+FROM git_pack_resolve p 71+LEFT JOIN git_pack_resolve b ON b.scope = p.scope AND b.offset = p.base_offset 72+LEFT JOIN git_pack_resolve r ON r.scope = p.scope AND r.oid = p.base_oid 73+WHERE p.scope = ? AND p.result IS NULL AND (b.result IS NOT NULL OR r.result IS NOT NULL) 74+ORDER BY p.offset LIMIT 1`, 83+ if (!rows.length) break; 84+ const row = rows[0]!; 85+ if (row.depth >= 64) throw Error("Git delta chain exceeds depth limit"); 86+ const base = this.objects.get(row.base), 87+ delta = this.objects.get(row.raw); 88+ const result = this.objects.put( 91+ applyGitDeltaChunks(delta, base, write, this.maxObjectBytes); 95+ this.storage.sql.exec( 96+ "UPDATE git_pack_resolve SET result = ?, oid = ?, depth = ? WHERE scope = ? AND offset = ?", 103+ this.objects.remove(row.raw); 107+ .exec("SELECT offset FROM git_pack_resolve WHERE scope = ? AND result IS NULL LIMIT 1", this.scope) 110+ throw Error("unresolved or cyclic Git delta base"); 113+ get(oid: string): StoredGitBytes { 114+ const value = this.find(oid); 115+ if (!value) throw Error("missing packed Git object"); 118+ find(oid: string): StoredGitBytes | undefined { 120+ const rows = this.storage.sql 121+ .exec("SELECT result FROM git_pack_resolve WHERE scope = ? AND oid = ? LIMIT 1", this.scope, oid) 122+ .toArray() as { result: string }[]; 123+ if (!rows.length) return undefined; 124+ return this.objects.get(rows[0]!.result); 128+ this.storage.transactionSync(() => { 129+ this.storage.sql.exec("DELETE FROM git_pack_resolve WHERE scope = ?", this.scope); 130+ this.objects.dispose(); --- /dev/null
+++ b/server/src/git-pack-spool.ts
@@ -0,0 +1,119 @@
1+import { createHash } from "node:crypto"; 2+import type { SqliteStorage } from "./engine-project.ts"; 4+/** Temporary verified pack bytes. No whole-pack read API is exposed. */ 5+export class GitPackSpool { 6+ static readonly chunkBytes = 65536; 7+ /** Cold Durable Object construction only, before any intake starts. */ 8+ static recover(storage: SqliteStorage): void { 9+ GitPackSpool.initialize(storage); 10+ storage.sql.exec("DELETE FROM git_pack_spool"); 12+ private static initialize(storage: SqliteStorage): void { 14+ "CREATE TABLE IF NOT EXISTS git_pack_spool (id TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (id, part))", 17+ readonly id = crypto.randomUUID(); 19+ private sealed = false; 20+ private closed = false; 21+ private readonly storage: SqliteStorage; 22+ constructor(storage: SqliteStorage) { 23+ this.storage = storage; 24+ GitPackSpool.initialize(storage); 26+ get byteLength(): number { 27+ this.assertReadable(); 30+ private assertReadable(): void { 31+ if (!this.sealed || this.closed) throw Error("pack spool is not readable"); 33+ async ingest(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, maxBytes: number): Promise<string> { 34+ if (this.size || this.sealed || this.closed) throw Error("pack spool already used"); 35+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 32) throw Error("invalid pack byte limit"); 36+ const hash = createHash("sha1"); 37+ let tail = new Uint8Array(0); 38+ let pending = new Uint8Array(GitPackSpool.chunkBytes), 42+ if (this.closed) throw Error("pack spool is closed"); 43+ this.storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", this.id, part++, pending.slice(0, used)); 47+ for await (const chunk of chunks) { 48+ if (this.closed) throw Error("pack spool is closed"); 49+ if (!(chunk instanceof Uint8Array)) throw Error("invalid pack chunk"); 50+ for (let at = 0; at < chunk.length; ) { 51+ const count = Math.min(GitPackSpool.chunkBytes - used, chunk.length - at); 52+ if (this.size + count > maxBytes) throw Error("pack exceeds byte limit"); 53+ const piece = chunk.subarray(at, at + count); 54+ const joined = new Uint8Array(tail.length + piece.length); 56+ joined.set(piece, tail.length); 57+ const end = Math.max(0, joined.length - 20); 58+ hash.update(joined.subarray(0, end)); 59+ tail = joined.slice(end); 60+ pending.set(piece, used); 64+ if (used === pending.length) save(); 68+ if (this.size < 32 || tail.length !== 20) throw Error("truncated pack"); 69+ const digest = hash.digest("hex"); 70+ if (digest !== Buffer.from(tail).toString("hex")) throw Error("pack checksum mismatch"); 72+ const header = this.read(0, 12); 73+ if (new TextDecoder().decode(header.subarray(0, 4)) !== "PACK" || new DataView(header.buffer).getUint32(4) !== 2) 74+ throw Error("unsupported pack header"); 81+ read(start: number, length: number): Uint8Array { 82+ this.assertReadable(); 84+ !Number.isSafeInteger(start) || 85+ !Number.isSafeInteger(length) || 88+ length > GitPackSpool.chunkBytes || 89+ start + length > this.size 91+ throw Error("invalid pack byte range"); 92+ const result = new Uint8Array(length); 94+ while (copied < length) { 95+ const position = start + copied, 96+ part = Math.floor(position / GitPackSpool.chunkBytes); 97+ const rows = this.storage.sql 98+ .exec("SELECT data FROM git_pack_spool WHERE id = ? AND part = ?", this.id, part) 99+ .toArray() as { data: ArrayBuffer }[]; 100+ if (rows.length !== 1) throw Error("missing pack chunk"); 101+ const data = new Uint8Array(rows[0]!.data), 102+ offset = position % GitPackSpool.chunkBytes; 103+ const count = Math.min(length - copied, data.length - offset); 104+ if (count <= 0 || data.length > GitPackSpool.chunkBytes) throw Error("invalid pack chunk"); 105+ result.set(data.subarray(offset, offset + count), copied); 110+ *chunks(): IterableIterator<Uint8Array> { 111+ this.assertReadable(); 112+ for (let start = 0; start < this.size; start += GitPackSpool.chunkBytes) 113+ yield this.read(start, Math.min(GitPackSpool.chunkBytes, this.size - start)); 117+ this.storage.sql.exec("DELETE FROM git_pack_spool WHERE id = ?", this.id); --- a/server/src/ingest.ts
+++ b/server/src/ingest.ts
@@ -2,12 +2,17 @@
22// project's Artifacts repo, read back for project.ingest. Every commit the 33// Worker pushes ends "abso-version: N" ("avcs-version: N" before the rename); the commits above the newest such 44// commit that haven't been taken in yet are the person's, and N is their base. 5−import git from "isomorphic-git";
6−import http from "isomorphic-git/http/web";
5+import git, { type HttpClient } from "isomorphic-git"; 76import type { FileModes } from "../../worker/project/project-api.ts"; 7+import type { SqliteStorage } from "./engine-project.ts"; 8+import { gitBlobText, InvalidGitUtf8 } from "./git-blob-text.ts"; 9+import { GitDiskIntake } from "./git-disk-intake.ts"; 10+import { gitHttp } from "./git-http.ts"; 811import { MemoryFS } from "./memory-fs.ts"; 912import { repoName } from "./push.ts"; 14+const http = gitHttp(); 1116const EXEC = 0o100755; 1217const LINK = 0o120000; @@ -40,7 +45,10 @@
4045async function readAccess( 4146 artifacts: Artifacts, 43−): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> {
50+ onAuth: () => { username: string; password: string }; 4452 let repo: Awaited<ReturnType<Artifacts["get"]>>; 4654 repo = await artifacts.get(repoName(project)); @@ -57,7 +65,12 @@
5765export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> { 5866 const access = await readAccess(artifacts, project); 5967 if (!access) return null; 60− const refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: "refs/heads/main" });
68+ const refs = await git.listServerRefs({ 71+ onAuth: access.onAuth, 72+ prefix: "refs/heads/main", 6174 return refs.find((r) => r.ref === "refs/heads/main")?.oid ?? null; @@ -67,6 +80,12 @@
6881/** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */ 6982export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>; 83+export type RetainFileChunks = ( 84+ files: Record<string, string>, 86+ chunks: Iterable<string>, 7291 * `oldBlob` gives shared's blob for a path: a binary file over the limit @@ -78,14 +97,35 @@
7897 seen: string | undefined, 7998 storeBlob?: StoreBlob, 8099 oldBlob: (path: string) => string | undefined = () => undefined, 100+ retainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void = ( 108+ storage: SqliteStorage; 109+ maxPackBytes: number; 110+ maxObjectBytes: number; 111+ maxDecodedBytes?: number; 113+ retainFileChunks?: RetainFileChunks; 81115): Promise<PushedCommits | null> { 82116 const access = await readAccess(artifacts, project); 83117 if (!access) return null; 84118 const fs = new MemoryFS(); 85119 const dir = "/repo"; 121+ ? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes) 123+ const cache = disk ? {} : undefined; 124+ if (intake && cache) intake.attach(cache); 88− http,
128+ http: disk?.http ?? http, 91131 onAuth: access.onAuth, @@ -94,7 +134,8 @@
97− const log = await git.log({ fs, dir, ref: "main", depth: DEPTH });
137+ intake?.assertReady(); 138+ const log = await git.log({ fs, dir, cache, ref: "main", depth: DEPTH }); 98139 if (log.length === 0) return null; 99140 const head = log[0]!.oid; 100141 const fresh: typeof log = []; @@ -113,9 +154,26 @@
115156 message: c.commit.message.trim(), 116− ...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)),
167+ disk?.retainFileChunks, 118− return { head, author: fresh.at(-1)?.commit.author.name ?? "git", base, commits, tooBig: [...tooBig] };
172+ author: fresh.at(-1)?.commit.author.name ?? "git", 175+ tooBig: [...tooBig], @@ -123,24 +181,59 @@
123181 * a link (120000) is "" with its target in modes. Files that aren't UTF-8 126−async function treeText(
184+export async function treeText( 130188 storeBlob: StoreBlob | undefined, 131189 tooBig: Set<string>, 132190 oldBlob: (path: string) => string | undefined, 133−): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> {
191+ retainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void, 193+ intake?: GitDiskIntake, 194+ retainFileChunks?: RetainFileChunks, 196+ files: Record<string, string>; 198+ blobs: Record<string, string>; 134200 const files: Record<string, string> = {}; 135201 const modes: FileModes = {}; 136202 const blobs: Record<string, string> = {}; 140207 trees: [git.TREE({ ref: oid })], 208+ iterate: async (walk, children) => { 209+ for (const child of children) await walk(child); 212+ reduce: async () => undefined, 141213 map: async (path, [entry]) => { 142214 if (!entry || path === ".") return true; 143215 if ((await entry.type()) !== "blob") return true; 216+ const mode = await entry.mode(); 217+ const blobOid = await entry.oid(); 218+ if (intake && retainFileChunks && mode !== LINK) { 219+ const stored = intake.bytes(blobOid); 220+ if (stored?.type !== "blob") throw Error("Git intake blob is missing"); 223+ // Validate before retaining: a late invalid byte must take the binary path. 224+ for (const _ of gitBlobText(stored)) { 225+ /* Retain no decoded text. */ 228+ if (!(error instanceof InvalidGitUtf8)) throw error; 232+ retainFileChunks(files, path, gitBlobText(stored), blobOid); 233+ modes[path] = { exec: mode === EXEC, link: null }; 144237 const bytes = await entry.content(); 145238 if (!bytes) return true; @@ -151,7 +244,7 @@
151244 const sha = storeBlob ? await storeBlob(bytes) : null; 153246 blobs[path] = sha; 154− modes[path] = { exec: (await entry.mode()) === EXEC, link: null };
247+ modes[path] = { exec: mode === EXEC, link: null }; 155248 } else if (storeBlob) { 157250 const kept = oldBlob(path); @@ -159,12 +252,11 @@
162− const mode = await entry.mode();
163255 if (mode === LINK) { 164− files[path] = "";
256+ retainFile(files, path, ""); 165257 modes[path] = { exec: false, link: body }; 167− files[path] = body;
259+ retainFile(files, path, body, blobOid); 168260 modes[path] = { exec: mode === EXEC, link: null }; --- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -12,6 +12,8 @@
1212import { DiskFirstRuntime } from "./disk-first-runtime.ts"; 1313import { EngineProject, SqliteLog } from "./engine-project.ts"; 1414import { artifactsOf, type Env } from "./env.ts"; 15+import { GitDiskIntake } from "./git-disk-intake.ts"; 16+import { GitIntakeTrees } from "./git-intake-trees.ts"; 1517import { pushedSince, remoteHead } from "./ingest.ts"; @@ -59,6 +61,10 @@
5961export const PUSH_EVERY_MS = 60_000; 6062/** While agents are working, how often a call looks for plain-git pushes to the repo. */ 6163const GIT_CHECK_MS = 15_000; 64+// Disk scratch admission limits, independent of the Worker's resident memory. 65+const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024; 66+const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024; 67+const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024; 6470 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim @@ -119,6 +125,10 @@
119125 constructor(ctx: DurableObjectState, env: Env) { 121127 this.blobs = new BlobStore(ctx.storage); 128+ if (env.ABSO_DISK_FIRST === "on") { 129+ GitDiskIntake.recover(ctx.storage); 130+ GitIntakeTrees.recover(ctx.storage); 124134 /** Where files kept whole go: the project's blob store. */ @@ -533,12 +543,23 @@
533543 const head = await remoteHead(artifacts, name); 534544 if (!head || head === seen || head === pushed?.commit) return null; 535545 const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {}); 546+ using trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined; 536547 const found = await pushedSince( 540551 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)), 541552 (path) => sharedBlobs[path], 553+ trees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined, 556+ storage: this.ctx.storage, 557+ maxPackBytes: GIT_PACK_MAX_BYTES, 558+ maxObjectBytes: GIT_OBJECT_MAX_BYTES, 559+ maxDecodedBytes: GIT_DECODED_MAX_BYTES, 560+ retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid), 543564 if (!found || found.commits.length === 0) { 544565 if (found) await this.ctx.storage.put("git:head", found.head); --- /dev/null
+++ b/server/test/git-blob-text.test.ts
@@ -0,0 +1,58 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { gitBlobText, InvalidGitUtf8 } from "../src/git-blob-text.ts"; 4+import { GitIntakeTrees } from "../src/git-intake-trees.ts"; 5+import { memoryStorage } from "./helpers.ts"; 7+function source(bytes: Uint8Array) { 9+ byteLength: bytes.length, 10+ read(start: number, length: number) { 11+ assert.ok(length <= 16384); 12+ return bytes.slice(start, start + length); 17+test("Git text chunks preserve BOM and split UTF-8 semantics with bounded pieces", () => { 18+ for (const text of ["", "\ufefftext", "x".repeat(16383) + "🚀é中".repeat(20000), "nul\0text"]) { 19+ const bytes = new TextEncoder().encode(text); 20+ const chunks = [...gitBlobText(source(bytes))]; 21+ assert.ok(chunks.every((chunk) => chunk.length <= 16384)); 22+ assert.equal(chunks.join(""), new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes)); 26+test("late invalid UTF-8 rolls back retained chunks without publishing a file", (t) => { 27+ const storage = memoryStorage(); 28+ t.after(() => storage.db.close()); 29+ const trees = new GitIntakeTrees(storage); 30+ const files: Record<string, string> = {}; 31+ const bytes = new Uint8Array(100000).fill(97); 32+ bytes[bytes.length - 1] = 0xf0; 33+ assert.throws(() => trees.retainChunks(files, "bad", gitBlobText(source(bytes)), "a".repeat(40)), InvalidGitUtf8); 34+ assert.deepEqual(Object.keys(files), []); 36+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n, 39+ bytes[bytes.length - 1] = 98; 40+ trees.retainChunks(files, "good", gitBlobText(source(bytes)), "a".repeat(40)); 41+ assert.equal(files.good, new TextDecoder().decode(bytes)); 45+test("Git text reading preserves storage errors instead of classifying them as binary", () => { 46+ const failure = new TypeError("storage failure"); 56+ (error) => error === failure, --- /dev/null
+++ b/server/test/git-budget-recovery.test.ts
@@ -0,0 +1,31 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { GitDiskIntake } from "../src/git-disk-intake.ts"; 4+import { GitPackResolver } from "../src/git-pack-resolver.ts"; 5+import { memoryStorage } from "./helpers.ts"; 7+test("cold Git recovery removes abandoned byte budgets without touching canonical data", (t) => { 8+ const storage = memoryStorage(); 9+ t.after(() => storage.db.close()); 10+ storage.sql.exec("CREATE TABLE canonical_budget_fixture (value TEXT)"); 11+ storage.sql.exec("INSERT INTO canonical_budget_fixture VALUES ('preserved')"); 12+ const abandoned = new GitPackResolver(storage, 100, 100); 13+ abandoned.add(12, "blob", new TextEncoder().encode("abandoned")); 14+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 9); 15+ GitDiskIntake.recover(storage); 16+ GitDiskIntake.recover(storage); 17+ for (const table of [ 24+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 25+ assert.equal(storage.db.prepare("SELECT value FROM canonical_budget_fixture").get()!.value, "preserved"); 26+ const retry = new GitPackResolver(storage, 3, 3); 27+ retry.add(12, "blob", new TextEncoder().encode("new")); 28+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 3); 30+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_budget").get()!.n, 0); --- /dev/null
+++ b/server/test/git-delta-stream.test.ts
@@ -0,0 +1,64 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { applyGitDeltaChunks, type GitByteRanges } from "../src/git-delta-stream.ts"; 5+const ranges = (bytes: Uint8Array): GitByteRanges => ({ 6+ byteLength: bytes.length, 8+ assert.ok(length <= 65536); 9+ return bytes.slice(start, start + length); 12+const integer = (value: number) => { 15+ const next = value % 128; 16+ value = Math.floor(value / 128); 17+ bytes.push(next | (value ? 128 : 0)); 21+test("delta copy and literal instructions use bounded base reads and output", () => { 22+ const base = Uint8Array.from({ length: 200000 }, (_, i) => i % 251); 23+ // Copy 131072 bytes from offset zero, then append three literal bytes. 24+ const delta = Uint8Array.from([...integer(base.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]); 25+ const output: Uint8Array[] = []; 31+ assert.ok(chunk.length <= 65536); 38+ assert.deepEqual(Buffer.concat(output), Buffer.concat([base.subarray(0, 131072), new Uint8Array([4, 5, 6])])); 40+test("delta refuses malformed instructions, bounds and truncated input", () => { 41+ for (const bytes of [ 49+ assert.throws(() => applyGitDeltaChunks(ranges(Uint8Array.from(bytes)), ranges(new Uint8Array()), () => {}, 10)); 54+ ranges(new Uint8Array([0, 11])), 55+ ranges(new Uint8Array()), 63+ assert.equal(writes, 0); --- /dev/null
+++ b/server/test/git-disk-clone.test.ts
@@ -0,0 +1,213 @@
1+import assert from "node:assert/strict"; 2+import { randomBytes } from "node:crypto"; 3+import { test } from "node:test"; 4+import git, { type HttpClient } from "isomorphic-git"; 5+import { GitDiskIntake } from "../src/git-disk-intake.ts"; 6+import { GitIntakeTrees } from "../src/git-intake-trees.ts"; 7+import { pushedSince } from "../src/ingest.ts"; 8+import { MemoryFS } from "../src/memory-fs.ts"; 9+import { memoryStorage } from "./helpers.ts"; 11+const packet = (text: string | Uint8Array) => { 12+ const body = Buffer.from(text); 13+ return Buffer.concat([Buffer.from((body.length + 4).toString(16).padStart(4, "0")), body]); 16+for (const mode of ["success", "limit", "fatal", "server-intake", "text-intake"]) 17+ test(`actual disk clone handles ${mode}`, async (t) => { 18+ const rejectPack = mode === "limit"; 19+ const source = new MemoryFS(), 21+ await git.init({ fs: source, dir, defaultBranch: "main" }); 22+ const blob = mode === "text-intake" ? Buffer.from("x".repeat(16383) + "🚀é中".repeat(20000)) : randomBytes(400000); 23+ const blobOid = await git.writeBlob({ fs: source, dir, blob }); 24+ const tree = await git.writeTree({ 27+ tree: [{ mode: "100644", path: "large.bin", oid: blobOid, type: "blob" }], 30+ name: "Capacity fixture", 31+ email: "fixture@example.invalid", 35+ const base = await git.writeCommit({ 43+ message: "Base\n\nabso-version: 0\n", 46+ const head = await git.writeCommit({ 54+ message: "Fixture\n", 58+ await git.packObjects({ 61+ oids: [head, base, tree, blobOid], 65+ const advertisement = Buffer.concat([ 66+ packet("# service=git-upload-pack\n"), 68+ packet(`${head} HEAD\0symref=HEAD:refs/heads/main side-band-64k shallow\n`), 69+ packet(`${head} refs/heads/main\n`), 73+ let uploadChunksRead = 0; 74+ let uploadClosed = false; 75+ const uploadParts = [packet("NAK\n")]; 76+ for (let at = 0; at < packed.length; at += 16000) { 77+ uploadParts.push(packet(Buffer.concat([Buffer.from([1]), packed.subarray(at, at + 16000)]))); 79+ packet(Buffer.concat([Buffer.from([2]), Buffer.from("Counting objects: 50% (1/2)\n".repeat(200))])), 81+ if (mode === "fatal" && at === 16000) { 82+ uploadParts.push(packet(Buffer.concat([Buffer.from([3]), Buffer.from("fixture remote failure")]))); 86+ uploadParts.push(Buffer.from("0000")); 87+ const http: HttpClient = { 88+ request: async ({ url, method }) => { 89+ const body = method === "POST" ? Buffer.concat(uploadParts) : advertisement; 90+ if (method === "POST") uploads++; 93+ method: method ?? "GET", 97+ body: (async function* () { 99+ for (let at = 0; at < body.length; at += 997) { 100+ if (method === "POST") uploadChunksRead++; 101+ yield body.subarray(at, at + 997); 104+ if (method === "POST") uploadClosed = true; 110+ const storage = memoryStorage(); 111+ const intake = new GitDiskIntake(storage, rejectPack ? 70000 : 2000000, 1000000); 112+ const ingest = intake.ingest.bind(intake); 113+ intake.ingest = async (...args) => { 114+ await new Promise((resolve) => setTimeout(resolve, 25)); 115+ assert.ok(uploadChunksRead < 64, `pack source read ahead ${uploadChunksRead} chunks before disk consumption`); 116+ return ingest(...args); 119+ intake.attach(cache); 120+ const fs = new MemoryFS(); 121+ const write = fs.promises.writeFile; 122+ fs.promises.writeFile = async (path, ...args) => { 123+ assert.ok(!/\.(pack|idx)$/.test(path), "clone must not persist a collected pack or index"); 124+ return write(path, ...args); 127+ if (mode === "server-intake" || mode === "text-intake") { 128+ const trees = new GitIntakeTrees(storage); 129+ if (mode === "text-intake") { 130+ const original = GitDiskIntake.prototype.read; 131+ t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) { 132+ if (oid === blobOid) throw Error("whole text blob read forbidden"); 133+ return original.call(this, oid); 138+ info: async () => ({ remote: "https://fixture.invalid/repo" }), 139+ createToken: async () => ({ plaintext: "invented-test-token" }), 140+ [Symbol.dispose]() {}, 143+ const found = await pushedSince( 148+ assert.deepEqual(Buffer.from(bytes), blob); 149+ return "fixture-blob"; 155+ maxPackBytes: 2000000, 156+ maxObjectBytes: 1000000, 158+ retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid), 161+ assert.equal(found!.base, 0); 162+ assert.equal(found!.commits.length, 1); 163+ if (mode === "text-intake") assert.equal(found!.commits[0]!.files["large.bin"], blob.toString("utf8")); 164+ else assert.equal(found!.commits[0]!.blobs["large.bin"], "fixture-blob"); 166+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"]) 167+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 170+ const clone = git.clone({ 175+ url: "https://fixture.invalid/repo", 180+ if (mode !== "success") { 181+ await assert.rejects(clone, rejectPack ? /pack exceeds byte limit/ : /fixture remote failure/); 182+ assert.equal(uploadClosed, true); 183+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"]) 184+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 188+ intake.assertReady(); 189+ assert.equal((await git.log({ fs, dir, cache, ref: "main" })).length, 2); 195+ trees: [git.TREE({ ref: head })], 196+ map: async (path, [entry]) => { 197+ if (path === "large.bin") { 198+ assert.deepEqual(Buffer.from((await entry!.content())!), blob); 204+ assert.equal(walked, 1); 205+ assert.equal(uploads, 1); 206+ assert.equal(await git.resolveRef({ fs, dir, ref: "main" }), head); 207+ assert.equal((await git.readCommit({ fs, dir, cache, oid: head })).commit.tree, tree); 208+ assert.deepEqual(Buffer.from((await git.readBlob({ fs, dir, cache, oid: blobOid })).blob), blob); --- /dev/null
+++ b/server/test/git-intake-trees.test.ts
@@ -0,0 +1,118 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { GitIntakeTrees } from "../src/git-intake-trees.ts"; 4+import { SqliteWriterState } from "../src/writer-host.ts"; 5+import { memoryStorage } from "./helpers.ts"; 7+test("unchanged Git blobs share stored text across paths and commits", (t) => { 8+ const storage = memoryStorage(); 9+ t.after(() => storage.db.close()); 10+ const trees = new GitIntakeTrees(storage); 11+ const body = "unchanged\n".repeat(10000); 12+ const oid = "a".repeat(40); 14+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n; 15+ const first: Record<string, string> = {}; 16+ trees.retainFile(first, "original", body, oid); 17+ const initialRows = count(); 18+ for (let i = 0; i < 100; i++) { 19+ const files: Record<string, string> = {}; 20+ trees.retainFile(files, `renamed-${i}`, body, oid); 21+ assert.equal(files[`renamed-${i}`], body); 23+ assert.equal(count(), initialRows); 24+ trees.retainFile(first, "changed", "new text", "b".repeat(40)); 25+ assert.equal(first.original, body); 26+ assert.equal(first.changed, "new text"); 27+ assert.ok(Number(count()) > Number(initialRows)); 28+ assert.throws(() => trees.retainFile(first, "bad", "text", "bad-id"), /Invalid Git blob id/); 30+ assert.equal(count(), 0); 33+test("Git intake stores each decoded file before the next file arrives", (t) => { 34+ const storage = memoryStorage(); 35+ t.after(() => storage.db.close()); 36+ const trees = new GitIntakeTrees(storage); 37+ const files: Record<string, string> = Object.create(null); 38+ for (let i = 0; i < 20; i++) { 39+ trees.retainFile(files, `file-${i}`, `${i}:${"x".repeat(50000)}`); 40+ assert.equal(Object.getOwnPropertyDescriptor(files, `file-${i}`)?.value, undefined); 41+ assert.equal(files[`file-${i}`], `${i}:${"x".repeat(50000)}`); 43+ assert.equal(Object.keys(files).length, 20); 45+ assert.throws(() => files["file-0"], /closed/); 46+ assert.throws(() => trees.retainFile(files, "later", "text"), /closed/); 49+test("Git intake retains independent trees on disk and releases their text rows", (t) => { 50+ const storage = memoryStorage(); 51+ t.after(() => storage.db.close()); 52+ const trees = new GitIntakeTrees(storage); 53+ const retained: ReturnType<GitIntakeTrees["retain"]>[] = []; 54+ for (let i = 0; i < 50; i++) { 56+ "a.txt": `${i}:${"\ud83d\ude80".repeat(20000)}\n`, 62+ modes: { "a.txt": { exec: true, link: null } }, 66+ files["a.txt"] = "changed after retention"; 68+ for (let i = 0; i < retained.length; i++) { 69+ const tree = retained[i]!; 70+ assert.deepEqual(Object.keys(tree.files), ["a.txt", "empty.txt"]); 71+ assert.equal(Object.getOwnPropertyDescriptor(tree.files, "a.txt")?.value, undefined); 72+ assert.equal(tree.files["a.txt"], `${i}:${"\ud83d\ude80".repeat(20000)}\n`); 73+ assert.equal(tree.files["empty.txt"], ""); 74+ assert.equal(tree.modes["a.txt"]?.exec, true); 77+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n; 78+ assert.ok(Number(count()) > 0); 80+ assert.equal(count(), 0); 81+ assert.throws(() => retained[0]!.files["a.txt"], /closed/); 82+ assert.throws(() => trees.retain({ files: {}, modes: {}, blobs: {} }), /closed/); 86+test("disposing one intake does not delete another concurrent intake", (t) => { 87+ const storage = memoryStorage(); 88+ t.after(() => storage.db.close()); 89+ const first = new GitIntakeTrees(storage); 90+ const second = new GitIntakeTrees(storage); 91+ first.retain({ files: { a: "first" }, modes: {}, blobs: {} }); 92+ const retained = second.retain({ 93+ files: { a: "second" }, 98+ assert.equal(retained.files.a, "second"); 102+test("cold recovery removes abandoned intake text and preserves canonical writer state", (t) => { 103+ const storage = memoryStorage(); 104+ t.after(() => storage.db.close()); 105+ const abandoned = new GitIntakeTrees(storage); 106+ abandoned.retain({ files: { a: "abandoned text" }, modes: {}, blobs: {} }); 107+ const canonical = new SqliteWriterState(storage, "server-disk-v1"); 108+ canonical.write("receipt", "operation", { committed: true }); 109+ GitIntakeTrees.recover(storage); 110+ assert.deepEqual(canonical.read("receipt", "operation"), { committed: true }); 112+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(abandoned.namespace)!.n, 115+ const retry = new GitIntakeTrees(storage); 116+ assert.equal(retry.retain({ files: { a: "retry" }, modes: {}, blobs: {} }).files.a, "retry"); --- /dev/null
+++ b/server/test/git-object-bytes.test.ts
@@ -0,0 +1,74 @@
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { test } from "node:test"; 4+import { applyGitDeltaChunks } from "../src/git-delta-stream.ts"; 5+import { GitObjectBytes } from "../src/git-object-bytes.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+const integer = (value: number) => { 11+ const part = value % 128; 12+ value = Math.floor(value / 128); 13+ bytes.push(part | (value ? 128 : 0)); 17+test("disk delta output has exact Git identity and partial failures roll back", (t) => { 18+ const storage = memoryStorage(); 19+ t.after(() => storage.db.close()); 20+ const objects = new GitObjectBytes(storage); 21+ const bytes = Uint8Array.from({ length: 200000 }, (_, i) => i % 251); 22+ const base = objects.put("blob", (write) => write(bytes), 200000); 23+ const instructions = Uint8Array.from([...integer(bytes.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]); 24+ const delta = objects.put("blob", (write) => write(instructions), 100); 25+ const result = objects.put( 28+ applyGitDeltaChunks(delta, base, write, 200000); 32+ const expected = Buffer.concat([bytes.subarray(0, 131072), new Uint8Array([4, 5, 6])]); 33+ assert.equal(result.oid, createHash("sha1").update(`blob ${expected.length}\0`).update(expected).digest("hex")); 34+ assert.deepEqual(result.read(65530, 100), new Uint8Array(expected.subarray(65530, 65630))); 35+ assert.equal(result.byteLength, expected.length); 36+ const counts = () => [ 37+ storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_bytes").get()!.n, 38+ storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, 40+ const bad = objects.put("blob", (write) => write(Uint8Array.from([...instructions, 0])), 101); 41+ const before = counts(); 47+ applyGitDeltaChunks(bad, base, write, 200000); 51+ /invalid Git delta instruction/, 53+ assert.deepEqual(counts(), before); 60+ throw Error("injected producer failure"); 64+ /injected producer failure/, 66+ assert.deepEqual(counts(), before); 67+ assert.throws(() => objects.put("blob", (write) => write(bytes), 100000), /exceeds byte limit/); 68+ assert.deepEqual(counts(), before); 69+ assert.deepEqual(base.read(0, 100), bytes.slice(0, 100)); 70+ assert.equal(objects.put("blob", () => {}, 0).oid, "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"); 72+ assert.deepEqual(counts(), [0, 0]); 73+ assert.throws(() => base.read(0, 1), /closed/); --- /dev/null
+++ b/server/test/git-pack-decode.test.ts
@@ -0,0 +1,183 @@
1+import assert from "node:assert/strict"; 2+import { createHash, randomBytes } from "node:crypto"; 3+import { createRequire } from "node:module"; 4+import { test } from "node:test"; 5+import { deflateSync } from "node:zlib"; 6+import { GitDiskIntake } from "../src/git-disk-intake.ts"; 7+import { decodeGitPack, type PackInflater } from "../src/git-pack-decode.ts"; 8+import { GitPackResolver } from "../src/git-pack-resolver.ts"; 9+import { GitPackSpool } from "../src/git-pack-spool.ts"; 10+import { memoryStorage } from "./helpers.ts"; 12+const require = createRequire(import.meta.url); 13+const { Inflate } = require("pako") as { 14+ Inflate: new (options: { chunkSize: number }) => PackInflater; 17+test("cold intake recovery removes abandoned scratch and preserves project rows", () => { 18+ const storage = memoryStorage(); 20+ GitDiskIntake.recover(storage); 21+ storage.sql.exec("CREATE TABLE canonical_fixture (value TEXT)"); 22+ storage.sql.exec("INSERT INTO canonical_fixture VALUES (?)", "preserved"); 23+ const resolver = new GitPackResolver(storage, 1000); 24+ resolver.add(12, "blob", new TextEncoder().encode("abc")); 25+ storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", "abandoned", 0, new Uint8Array([1])); 26+ GitDiskIntake.recover(storage); 27+ GitDiskIntake.recover(storage); 28+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"]) 29+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 30+ assert.equal(storage.db.prepare("SELECT value FROM canonical_fixture").get()!.value, "preserved"); 36+test("disk intake exposes only verified objects and disposes all scratch", async () => { 37+ const storage = memoryStorage(); 39+ for (const corrupt of [false, true]) { 40+ const intake = new GitDiskIntake(storage, 1000000, 1000000); 42+ intake.attach(cache); 43+ assert.equal(Reflect.get(cache, Symbol.for("abso.git.disk-pack")), intake); 44+ assert.throws(() => intake.attach(cache), /already attached/); 45+ assert.equal(intake.read("0".repeat(40)), undefined); 46+ const bytes = pack([Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc"))])]); 47+ if (corrupt) bytes[bytes.length - 1]! ^= 1; 50+ await assert.rejects( 51+ intake.ingest([bytes], () => new Inflate({ chunkSize: 16384 })), 54+ assert.throws(() => intake.read("0".repeat(40)), /closed/); 56+ await intake.ingest([bytes], () => new Inflate({ chunkSize: 16384 })); 57+ const oid = createHash("sha1").update("blob 3\0abc").digest("hex"); 58+ assert.equal(intake.read(oid)!.object.toString(), "abc"); 59+ assert.equal(intake.read("0".repeat(40)), undefined); 60+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0); 65+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"]) 66+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 72+test("late input cannot recreate scratch after intake disposal", async () => { 73+ const storage = memoryStorage(); 74+ const intake = new GitDiskIntake(storage, 1000000, 1000000); 75+ let sourceClosed = false; 76+ async function* source() { 78+ yield new Uint8Array(65536); 80+ yield new Uint8Array(65536); 86+ await assert.rejects( 87+ intake.ingest(source(), () => new Inflate({ chunkSize: 16384 })), 90+ assert.equal(sourceClosed, true); 91+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"]) 92+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 99+function objectHeader(kind: number, size: number): Uint8Array { 100+ const bytes = [(kind << 4) | (size & 15)]; 101+ size = Math.floor(size / 16); 103+ bytes[bytes.length - 1]! |= 128; 104+ bytes.push(size & 127); 105+ size = Math.floor(size / 128); 107+ return Uint8Array.from(bytes); 109+function pack(entries: Uint8Array[]): Uint8Array { 110+ const header = Buffer.alloc(12); 111+ header.write("PACK"); 112+ header.writeUInt32BE(2, 4); 113+ header.writeUInt32BE(entries.length, 8); 114+ const body = Buffer.concat([header, ...entries]); 115+ return Buffer.concat([body, createHash("sha1").update(body).digest()]); 118+test("verified disk pack inflates large objects and forward deltas without collected output", async () => { 119+ const storage = memoryStorage(); 120+ const spool = new GitPackSpool(storage); 121+ const resolver = new GitPackResolver(storage, 2000000); 123+ const large = randomBytes(800000); 124+ const base = Buffer.from("abc"); 125+ const baseId = createHash("sha1").update("blob 3\0").update(base).digest(); 126+ const delta = Uint8Array.from([3, 4, 0x90, 3, 1, 100]); 127+ const bytes = pack([ 128+ Buffer.concat([objectHeader(7, delta.length), baseId, deflateSync(delta)]), 129+ Buffer.concat([objectHeader(3, large.length), deflateSync(large)]), 130+ Buffer.concat([objectHeader(3, base.length), deflateSync(base)]), 132+ await spool.ingest([bytes], 2000000); 133+ decodeGitPack(spool, resolver, () => { 134+ const inflater = new Inflate({ chunkSize: 16384 }); 135+ Object.defineProperty(inflater, "result", { 136+ set(value: Uint8Array) { 137+ assert.equal(value.length, 0, "inflater must not collect decoded bytes"); 142+ const largeId = createHash("sha1").update(`blob ${large.length}\0`).update(large).digest("hex"); 143+ const stored = resolver.get(largeId); 144+ for (let at = 0; at < large.length; at += 65536) { 145+ const n = Math.min(65536, large.length - at); 146+ assert.deepEqual(stored.read(at, n), new Uint8Array(large.subarray(at, at + n))); 148+ const deltaId = createHash("sha1").update("blob 4\0abcd").digest("hex"); 149+ assert.equal(new TextDecoder().decode(resolver.get(deltaId).read(0, 4)), "abcd"); 157+test("invalid later pack entries clear earlier decoded objects and close the resolver", async () => { 158+ const valid = Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc"))]); 160+ Buffer.concat([objectHeader(3, 4), deflateSync(Buffer.from("abc"))]), 161+ Buffer.concat([objectHeader(3, 2), deflateSync(Buffer.from("abc"))]), 162+ Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc")).subarray(0, 3)]), 163+ Uint8Array.from([0]), 164+ Buffer.concat([objectHeader(6, 0), Uint8Array.from([0]), deflateSync(new Uint8Array())]), 165+ Buffer.concat([objectHeader(7, 2), Buffer.alloc(20, 255), deflateSync(Uint8Array.from([0, 0]))]), 167+ for (const invalid of cases) { 168+ const storage = memoryStorage(); 169+ const spool = new GitPackSpool(storage); 170+ const resolver = new GitPackResolver(storage, 1000000); 172+ await spool.ingest([pack([valid, invalid])], 1000000); 173+ assert.throws(() => decodeGitPack(spool, resolver, () => new Inflate({ chunkSize: 16384 }))); 174+ assert.throws(() => resolver.get("0".repeat(40)), /closed/); 175+ for (const table of ["git_pack_resolve", "git_object_meta", "git_object_bytes"]) 176+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); --- /dev/null
+++ b/server/test/git-pack-resolver.test.ts
@@ -0,0 +1,117 @@
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { test } from "node:test"; 4+import { GitPackResolver } from "../src/git-pack-resolver.ts"; 5+import { memoryStorage } from "./helpers.ts"; 7+const oid = (text: string) => createHash("sha1").update(`blob ${text.length}\0${text}`).digest("hex"); 8+const text = (value: ReturnType<GitPackResolver["get"]>) => new TextDecoder().decode(value.read(0, value.byteLength)); 10+test("decoded budget spans objects and rolls back failed additions", (t) => { 11+ const storage = memoryStorage(); 12+ t.after(() => storage.db.close()); 13+ const resolver = new GitPackResolver(storage, 10, 8); 14+ resolver.add(12, "blob", new TextEncoder().encode("abc")); 15+ assert.throws(() => resolver.add(12, "blob", new Uint8Array(4)), /UNIQUE/); 16+ resolver.add(30, "blob", new TextEncoder().encode("defgh")); 17+ assert.throws(() => resolver.add(50, "blob", new Uint8Array(1)), /total decoded byte limit/); 18+ assert.equal(text(resolver.get(oid("defgh"))), "defgh"); 19+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 8); 21+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_budget").get()!.n, 0); 24+test("delta results consume budget and failed resolution rolls back all accounting", (t) => { 25+ const storage = memoryStorage(); 26+ t.after(() => storage.db.close()); 27+ const resolver = new GitPackResolver(storage, 100, 12); 28+ resolver.add(12, "blob", new TextEncoder().encode("abc")); 29+ resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12); 30+ assert.throws(() => resolver.resolve(), /total decoded byte limit/); 31+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 9); 32+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, 2); 33+ assert.throws(() => resolver.get(oid("abcd")), /missing/); 37+test("resolved delta instructions are deleted without refunding decoded work", (t) => { 38+ const storage = memoryStorage(); 39+ t.after(() => storage.db.close()); 40+ const resolver = new GitPackResolver(storage, 100, 13); 41+ resolver.add(12, "blob", new TextEncoder().encode("abc")); 42+ resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12); 44+ assert.equal(text(resolver.get(oid("abcd"))), "abcd"); 45+ assert.equal(storage.db.prepare("SELECT SUM(bytes) AS n FROM git_object_meta").get()!.n, 7); 46+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 13); 47+ assert.throws(() => resolver.add(50, "blob", new Uint8Array(1)), /total decoded byte limit/); 52+test("disk pack resolver handles forward ID bases and offset delta chains", (t) => { 53+ const storage = memoryStorage(); 54+ t.after(() => storage.db.close()); 55+ const resolver = new GitPackResolver(storage, 1000); 56+ resolver.add(12, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), oid("abc")); 57+ resolver.add(40, "blob", new TextEncoder().encode("abc")); 58+ resolver.add(80, "delta", new Uint8Array([4, 5, 0x90, 4, 1, 101]), 12); 60+ for (const expected of ["abc", "abcd", "abcde"]) assert.equal(text(resolver.get(oid(expected))), expected); 63+ assert.throws(() => resolver.get(oid("abc")), /closed/); 64+ for (const table of ["git_pack_resolve", "git_object_meta", "git_object_bytes"]) 65+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 68+test("unresolved references roll back earlier resolutions in the same pass", (t) => { 69+ const storage = memoryStorage(); 70+ t.after(() => storage.db.close()); 71+ const resolver = new GitPackResolver(storage, 1000); 72+ resolver.add(12, "blob", new TextEncoder().encode("abc")); 73+ resolver.add(40, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12); 74+ resolver.add(80, "delta", new Uint8Array([0, 0]), "f".repeat(40)); 75+ const before = storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n; 76+ assert.throws(() => resolver.resolve(), /unresolved or cyclic/); 77+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, before); 78+ assert.throws(() => resolver.get(oid("abcd")), /missing/); 79+ assert.equal(text(resolver.get(oid("abc"))), "abc"); 83+test("decoded objects stream into the resolver and producer failures roll back", (t) => { 84+ const storage = memoryStorage(); 85+ const resolver = new GitPackResolver(storage, 1000000); 93+ const expected = createHash("sha1").update("blob 800000\0"); 94+ resolver.addChunks(12, "blob", (write) => { 95+ for (let i = 0; i < 100; i++) { 96+ const chunk = new Uint8Array(8000).fill(i); 97+ expected.update(chunk); 102+ const object = resolver.get(expected.digest("hex")); 103+ assert.equal(object.byteLength, 800000); 104+ assert.deepEqual(object.read(799990, 10), new Uint8Array(10).fill(99)); 105+ assert.ok(Number(storage.db.prepare("SELECT MAX(length(data)) AS n FROM git_object_bytes").get()!.n) <= 65536); 106+ const before = storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n; 109+ resolver.addChunks(40, "blob", (write) => { 110+ write(new Uint8Array(70000)); 111+ throw Error("inflate failed"); 115+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, before); 116+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_resolve WHERE offset = 40").get()!.n, 0); --- /dev/null
+++ b/server/test/git-pack-spool.test.ts
@@ -0,0 +1,70 @@
1+import assert from "node:assert/strict"; 2+import { randomBytes } from "node:crypto"; 3+import { test } from "node:test"; 4+import git from "isomorphic-git"; 5+import { GitPackSpool } from "../src/git-pack-spool.ts"; 6+import { MemoryFS } from "../src/memory-fs.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("cold pack recovery clears abandoned scratch without changing canonical tables", (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ GitPackSpool.recover(storage); 13+ storage.sql.exec("CREATE TABLE canonical_test (value TEXT)"); 14+ storage.sql.exec("INSERT INTO canonical_test VALUES (?)", "preserved"); 15+ storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", "abandoned", 0, new Uint8Array([1, 2])); 16+ GitPackSpool.recover(storage); 17+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0); 18+ assert.equal(storage.db.prepare("SELECT value FROM canonical_test").get()!.value, "preserved"); 19+ GitPackSpool.recover(storage); 22+test("pack spool verifies real pack bytes and serves bounded ranges across chunk boundaries", async (t) => { 23+ const storage = memoryStorage(); 24+ t.after(() => storage.db.close()); 25+ const fs = new MemoryFS(), 27+ await git.init({ fs, dir }); 29+ for (let i = 0; i < 4; i++) oids.push(await git.writeBlob({ fs, dir, blob: randomBytes(180000) })); 30+ const packed = await git.packObjects({ fs, dir, oids, write: false }); 31+ const bytes = packed.packfile!; 32+ const spool = new GitPackSpool(storage); 33+ assert.throws(() => spool.read(0, 0), /not readable/); 34+ async function* source() { 35+ for (let at = 0; at < bytes.length; at += 997) yield bytes.subarray(at, at + 997); 37+ assert.equal(await spool.ingest(source(), 1000000), Buffer.from(bytes.subarray(-20)).toString("hex")); 38+ assert.equal(spool.byteLength, bytes.length); 39+ for (const start of [0, 65530, 65536, 131070, bytes.length - 101]) { 40+ const length = Math.min(101, bytes.length - start); 41+ assert.deepEqual(spool.read(start, length), new Uint8Array(bytes.subarray(start, start + length))); 43+ assert.deepEqual(Buffer.concat([...spool.chunks()]), Buffer.from(bytes)); 44+ assert.throws(() => spool.read(0, 65537), /invalid pack byte range/); 45+ assert.throws(() => spool.read(bytes.length, 1), /invalid pack byte range/); 46+ const max = storage.db.prepare("SELECT MAX(length(data)) AS n FROM git_pack_spool").get()!.n; 47+ assert.ok(Number(max) <= 65536); 49+ assert.throws(() => spool.read(0, 0), /not readable/); 50+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0); 51+ for (const mode of ["corrupt", "limit", "source-error"]) { 52+ const bad = new GitPackSpool(storage); 54+ async function* broken() { 56+ const data = Uint8Array.from(bytes); 57+ if (mode === "corrupt") data[20]! ^= 1; 58+ yield data.subarray(0, 100000); 59+ if (mode === "source-error") throw Error("injected source failure"); 60+ yield data.subarray(100000); 65+ await assert.rejects(bad.ingest(broken(), mode === "limit" ? 70000 : 1000000)); 66+ assert.equal(closed, true); 67+ assert.throws(() => bad.read(0, 0), /not readable/); 68+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0); --- a/server/test/project-object-disk-first.test.ts
+++ b/server/test/project-object-disk-first.test.ts
@@ -1,9 +1,10 @@
11import assert from "node:assert/strict"; 2−import { registerHooks } from "node:module";
2+import { createRequire, registerHooks } from "node:module"; 33import { test } from "node:test"; 44import git from "isomorphic-git"; 55import { Project } from "../../worker/project/project.ts"; 66import { EngineProject } from "../src/engine-project.ts"; 7+import { GitDiskIntake } from "../src/git-disk-intake.ts"; 78import { MemoryFS } from "../src/memory-fs.ts"; 89import { memoryStorage } from "./helpers.ts"; @@ -20,6 +21,40 @@
2021const { ProjectObject } = await import("../src/project-object.ts"); 24+function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) { 25+ for (const table of [ 32+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table); 35+/** Keep transport synthetic while exercising the real disk pack decoder and cache. */ 36+async function cloneFixture(remote: MemoryFS, options: Parameters<typeof git.clone>[0]) { 37+ const intake = (options.cache as Record<symbol, GitDiskIntake> | undefined)?.[Symbol.for("abso.git.disk-pack")]; 39+ (options.fs as MemoryFS).entries = structuredClone(remote.entries); 42+ const oids = [...remote.entries.keys()].flatMap((path) => { 43+ const match = /\/objects\/([0-9a-f]{2})\/([0-9a-f]{38})$/.exec(path); 44+ return match ? [match[1]! + match[2]!] : []; 46+ const pack = (await git.packObjects({ fs: remote, dir: "/repo", oids, write: false })).packfile!; 47+ const { Inflate } = createRequire(import.meta.url)("pako"); 48+ await intake.ingest([pack], () => new Inflate({ chunkSize: 16384 })); 49+ await git.init({ fs: options.fs, dir: options.dir, defaultBranch: "main" }); 54+ value: await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }), 2358test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => { 2459 const storage = memoryStorage(); 2560 t.after(() => storage.db.close()); @@ -344,9 +379,14 @@
344379 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true }); 345380 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]); 346381 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 347− (options.fs as MemoryFS).entries = structuredClone(remote.entries);
382+ await cloneFixture(remote, options); 349384 const beforeIntake = rows(); 385+ const originalRead = GitDiskIntake.prototype.read; 386+ t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) { 387+ if (oid === blob) throw Error("whole intake text blob forbidden"); 388+ return originalRead.call(this, oid); 350390 const originalIngest = EngineProject.prototype.ingest; 351391 const failedIngest = t.mock.method( 352392 EngineProject.prototype, @@ -357,15 +397,18 @@
359399 await assert.rejects(() => bound().gitSync(), /injected after Git intake/); 400+ assertGitScratchEmpty(storage); 360401 assert.deepEqual(rows(), beforeIntake); 361402 assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head"); 362403 failedIngest.mock.restore(); 363404 failGitAcknowledgement = true; 364405 await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/); 406+ assertGitScratchEmpty(storage); 365407 const committedIntake = rows(); 366408 assert.equal((await bound().out()).version, 3); 367409 assert.equal((await bound().out()).git.head, parent); 368410 const intake = await bound().gitSync(); 411+ assertGitScratchEmpty(storage); 369412 assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt"); 370413 assert.ok(intake); 371414 assert.equal(intake?.head, incoming); @@ -443,7 +486,7 @@
443486 let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]); 444487 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]); 445488 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 446− (options.fs as MemoryFS).entries = structuredClone(remote.entries);
489+ await cloneFixture(remote, options); 448491 const refused = await object().gitSync(); 449492 assert.ok(refused);