15 files, 723 lines added, 46 removed.
--- a/server/src/git-delta-stream.ts
+++ b/server/src/git-delta-stream.ts
@@ -39,7 +39,7 @@
4040 if (integer() !== base.byteLength) throw Error("Git delta base length mismatch"); 4141 const size = integer(); 42− if (size > maxResultBytes) throw Error("Git delta result exceeds bound");
42+ if (size > maxResultBytes) throw new GitIntakeLimitError("object", "Git delta result exceeds bound"); 4343 const emit = (chunk: Uint8Array) => { 4444 if (produced + chunk.length > size) throw Error("Git delta result length mismatch"); @@ -71,3 +71,5 @@
7171 if (produced !== size) throw Error("Git delta result length mismatch"); 75+import { GitIntakeLimitError } from "./git-intake-limit.ts"; --- /dev/null
+++ b/server/src/git-file-contents.ts
@@ -0,0 +1,108 @@
1+import type { SqliteStorage } from "./engine-project.ts"; 2+import type { FileContents } from "./memory-fs.ts"; 4+function initialize(storage: SqliteStorage): void { 6+ "CREATE TABLE IF NOT EXISTS git_fs_meta (scope TEXT, path TEXT, bytes INTEGER, PRIMARY KEY(scope,path))", 9+ "CREATE TABLE IF NOT EXISTS git_fs_chunks (scope TEXT, path TEXT, part INTEGER, data BLOB NOT NULL, PRIMARY KEY(scope,path,part))", 11+ storage.sql.exec("CREATE TABLE IF NOT EXISTS git_fs_budget (scope TEXT PRIMARY KEY, bytes INTEGER NOT NULL)"); 14+/** One Git operation's scratch files. Reads materialize one file, never the whole filesystem. */ 15+export class GitFileContents implements FileContents { 16+ static recover(storage: SqliteStorage): void { 18+ storage.transactionSync(() => { 19+ for (const table of ["git_fs_chunks", "git_fs_meta", "git_fs_budget"]) storage.sql.exec(`DELETE FROM ${table}`); 22+ readonly scope = crypto.randomUUID(); 23+ private readonly storage: SqliteStorage; 24+ private readonly maxFileBytes: number; 25+ private readonly maxTotalBytes: number; 26+ private closed = false; 27+ constructor(storage: SqliteStorage, maxFileBytes: number, maxTotalBytes: number) { 28+ if (![maxFileBytes, maxTotalBytes].every((n) => Number.isSafeInteger(n) && n >= 0)) 29+ throw Error("invalid Git scratch limits"); 30+ this.storage = storage; 31+ this.maxFileBytes = maxFileBytes; 32+ this.maxTotalBytes = maxTotalBytes; 34+ storage.sql.exec("INSERT INTO git_fs_budget VALUES (?, 0)", this.scope); 36+ private active(): void { 37+ if (this.closed) throw Error("Git scratch files are closed"); 39+ private size(path: string): number | undefined { 40+ const rows = this.storage.sql 41+ .exec("SELECT bytes FROM git_fs_meta WHERE scope = ? AND path = ?", this.scope, path) 42+ .toArray() as { bytes: number }[]; 43+ return rows[0]?.bytes; 45+ write(path: string, bytes: Uint8Array): void { 47+ if (bytes.byteLength > this.maxFileBytes) throw Error("Git scratch file exceeds byte limit"); 48+ this.storage.transactionSync(() => { 49+ const old = this.size(path) ?? 0; 50+ const rows = this.storage.sql.exec("SELECT bytes FROM git_fs_budget WHERE scope = ?", this.scope).toArray() as { 53+ if (rows.length !== 1) throw Error("missing Git scratch budget"); 54+ const next = rows[0]!.bytes - old + bytes.byteLength; 55+ if (!Number.isSafeInteger(next) || next < 0 || next > this.maxTotalBytes) 56+ throw Error("Git scratch exceeds total byte limit"); 57+ this.storage.sql.exec("DELETE FROM git_fs_chunks WHERE scope = ? AND path = ?", this.scope, path); 58+ for (let at = 0; at < bytes.byteLength; at += 65536) 59+ this.storage.sql.exec( 60+ "INSERT INTO git_fs_chunks VALUES (?, ?, ?, ?)", 64+ bytes.slice(at, at + 65536), 66+ this.storage.sql.exec("INSERT OR REPLACE INTO git_fs_meta VALUES (?, ?, ?)", this.scope, path, bytes.byteLength); 67+ this.storage.sql.exec("UPDATE git_fs_budget SET bytes = ? WHERE scope = ?", next, this.scope); 70+ read(path: string): Uint8Array { 72+ const size = this.size(path); 73+ if (size === undefined || !Number.isSafeInteger(size) || size < 0 || size > this.maxFileBytes) 74+ throw Error("invalid Git scratch file"); 75+ const bytes = new Uint8Array(size); 76+ for (let at = 0; at < size; at += 65536) { 77+ const rows = this.storage.sql 78+ .exec("SELECT data FROM git_fs_chunks WHERE scope = ? AND path = ? AND part = ?", this.scope, path, at / 65536) 79+ .toArray() as { data: ArrayBuffer }[]; 80+ if (rows.length !== 1) throw Error("missing Git scratch chunk"); 81+ const chunk = new Uint8Array(rows[0]!.data); 82+ if (chunk.byteLength !== Math.min(65536, size - at)) throw Error("invalid Git scratch chunk"); 83+ bytes.set(chunk, at); 87+ remove(path: string): void { 89+ this.storage.transactionSync(() => { 90+ const size = this.size(path); 91+ if (size === undefined) throw Error("missing Git scratch file"); 92+ this.storage.sql.exec("DELETE FROM git_fs_chunks WHERE scope = ? AND path = ?", this.scope, path); 93+ this.storage.sql.exec("DELETE FROM git_fs_meta WHERE scope = ? AND path = ?", this.scope, path); 94+ this.storage.sql.exec("UPDATE git_fs_budget SET bytes = bytes - ? WHERE scope = ?", size, this.scope); 97+ [Symbol.dispose](): void { 101+ if (this.closed) return; 102+ this.storage.transactionSync(() => { 103+ for (const table of ["git_fs_chunks", "git_fs_meta", "git_fs_budget"]) 104+ this.storage.sql.exec(`DELETE FROM ${table} WHERE scope = ?`, this.scope); --- /dev/null
+++ b/server/src/git-intake-limit.ts
@@ -0,0 +1,8 @@
1+/** An admission refusal that is stable for the same remote head and limit policy. */ 2+export class GitIntakeLimitError extends Error { 3+ readonly kind: "pack" | "object" | "decoded" | "delta"; 4+ constructor(kind: GitIntakeLimitError["kind"], message: string) { --- a/server/src/git-object-bytes.ts
+++ b/server/src/git-object-bytes.ts
@@ -1,6 +1,7 @@
11import { createHash } from "node:crypto"; 22import type { SqliteStorage } from "./engine-project.ts"; 33import type { GitByteRanges } from "./git-delta-stream.ts"; 4+import { GitIntakeLimitError } from "./git-intake-limit.ts"; 56export type StoredGitBytes = GitByteRanges & { @@ -30,14 +31,21 @@
3031 private active(): void { 3132 if (this.closed) throw Error("Git object store is closed"); 33− put(type: string, produce: (write: (bytes: Uint8Array) => void) => void, maxBytes: number): StoredGitBytes {
36+ produce: (write: (bytes: Uint8Array) => void) => void, 3541 if (!["blob", "tree", "commit", "tag"].includes(type) || !Number.isSafeInteger(maxBytes) || maxBytes < 0) 3642 throw Error("invalid Git object limits or type"); 3743 const id = crypto.randomUUID(); 3844 this.storage.transactionSync(() => { 45+ const budgetScope = rawDelta ? `${this.scope}:raw` : this.scope; 46+ if (rawDelta) this.storage.sql.exec("INSERT OR IGNORE INTO git_object_budget VALUES (?, 0)", budgetScope); 3947 const budget = this.storage.sql 40− .exec("SELECT decoded FROM git_object_budget WHERE scope = ?", this.scope)
48+ .exec("SELECT decoded FROM git_object_budget WHERE scope = ?", budgetScope) 4149 .toArray() as { decoded: number }[]; 4250 if (budget.length !== 1) throw Error("missing Git decoded budget"); 4351 const remaining = this.maxDecodedBytes - budget[0]!.decoded; @@ -56,8 +64,12 @@
5866 produce((bytes) => { 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");
67+ if (length + bytes.length > maxBytes) throw new GitIntakeLimitError("object", "Git object exceeds byte limit"); 68+ if (length + bytes.length > remaining) 69+ throw new GitIntakeLimitError( 70+ rawDelta ? "delta" : "decoded", 71+ rawDelta ? "Git pack exceeds total delta byte limit" : "Git pack exceeds total decoded byte limit", 6173 length += bytes.length; 6274 for (let at = 0; at < bytes.length; ) { 6375 const count = Math.min(pending.length - used, bytes.length - at); @@ -78,7 +90,7 @@
81− this.storage.sql.exec("UPDATE git_object_budget SET decoded = decoded + ? WHERE scope = ?", length, this.scope);
93+ this.storage.sql.exec("UPDATE git_object_budget SET decoded = decoded + ? WHERE scope = ?", length, budgetScope); 8395 return this.get(id); @@ -140,7 +152,7 @@
140152 this.storage.transactionSync(() => { 141153 this.storage.sql.exec("DELETE FROM git_object_bytes WHERE scope = ?", this.scope); 142154 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);
155+ this.storage.sql.exec("DELETE FROM git_object_budget WHERE scope IN (?, ?)", this.scope, `${this.scope}:raw`); --- a/server/src/git-pack-resolver.ts
+++ b/server/src/git-pack-resolver.ts
@@ -46,7 +46,7 @@
4646 throw Error("invalid delta base reference"); 4747 } else if (base !== undefined) throw Error("ordinary object has delta base"); 4848 this.storage.transactionSync(() => { 49− const stored = this.objects.put(type === "delta" ? "blob" : type, produce, this.maxObjectBytes);
49+ const stored = this.objects.put(type === "delta" ? "blob" : type, produce, this.maxObjectBytes, type === "delta"); 5050 this.storage.sql.exec( 5151 "INSERT INTO git_pack_resolve VALUES (?, ?, ?, ?, ?, ?, ?, ?)", --- a/server/src/git-pack-spool.ts
+++ b/server/src/git-pack-spool.ts
@@ -49,7 +49,7 @@
4949 if (!(chunk instanceof Uint8Array)) throw Error("invalid pack chunk"); 5050 for (let at = 0; at < chunk.length; ) { 5151 const count = Math.min(GitPackSpool.chunkBytes - used, chunk.length - at); 52− if (this.size + count > maxBytes) throw Error("pack exceeds byte limit");
52+ if (this.size + count > maxBytes) throw new GitIntakeLimitError("pack", "pack exceeds byte limit"); 5353 const piece = chunk.subarray(at, at + count); 5454 const joined = new Uint8Array(tail.length + piece.length); @@ -117,3 +117,5 @@
117117 this.storage.sql.exec("DELETE FROM git_pack_spool WHERE id = ?", this.id); 121+import { GitIntakeLimitError } from "./git-intake-limit.ts"; --- a/server/src/memory-fs.ts
+++ b/server/src/memory-fs.ts
@@ -9,11 +9,18 @@
1111 | { kind: "dir"; children: Set<string>; mtimeMs: number } 12− | { kind: "file"; data: Uint8Array; exec: boolean; mtimeMs: number }
12+ | { kind: "file"; data: Uint8Array; byteLength?: number; exec: boolean; mtimeMs: number } 1313 | { kind: "link"; target: string; mtimeMs: number }; 1515const enc = new TextEncoder(); 17+/** Optional scratch storage for file contents; directory metadata remains in memory. */ 18+export interface FileContents { 19+ write(path: string, bytes: Uint8Array): void; 20+ read(path: string): Uint8Array; 21+ remove(path: string): void; 1724/** Plain fields, not getters: isomorphic-git writes to them when it normalizes stats. */ @@ -25,7 +32,11 @@
2532 constructor(entry: Entry) { 2633 this.kind = entry.kind; 28− entry.kind === "file" ? entry.data.byteLength : entry.kind === "link" ? enc.encode(entry.target).byteLength : 0;
35+ entry.kind === "file" 36+ ? (entry.byteLength ?? entry.data.byteLength) 37+ : entry.kind === "link" 38+ ? enc.encode(entry.target).byteLength 2940 this.mtimeMs = entry.mtimeMs; 3041 this.ctimeMs = entry.mtimeMs; 3142 this.mode = entry.kind === "dir" ? 0o040000 : entry.kind === "link" ? 0o120000 : entry.exec ? 0o100755 : 0o100644; @@ -45,6 +56,10 @@
4758export class MemoryFS { 59+ private readonly contents?: FileContents; 60+ constructor(contents?: FileContents) { 61+ this.contents = contents; 4863 encoder = new TextEncoder(); 4964 decoder = new TextDecoder(); 5065 entries = new Map<string, Entry>([["/", { kind: "dir", children: new Set(), mtimeMs: Date.now() }]]); @@ -157,10 +172,12 @@
158173 typeof data === "string" ? this.encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data); 159174 const mode = typeof options === "object" && options !== null ? options.mode : undefined; 175+ this.contents?.write(target, bytes); 161177 this.entries.set(target, { 163− data: bytes,
179+ data: this.contents ? new Uint8Array(0) : bytes, 180+ ...(this.contents ? { byteLength: bytes.byteLength } : {}), 164181 exec: mode !== undefined && (mode & 0o111) !== 0, 165182 mtimeMs: Date.now(), @@ -174,7 +191,12 @@
174191 throw fsError("EISDIR", path); 177− const data = entry.kind === "link" ? this.encoder.encode(entry.target) : entry.data;
195+ entry.kind === "link" 196+ ? this.encoder.encode(entry.target) 198+ ? this.contents.read(this.normalize(path)) 178200 const encoding = typeof options === "string" ? options : options?.encoding; 179201 return encoding ? this.decoder.decode(data) : data; @@ -190,6 +212,7 @@
190212 throw fsError("EISDIR", path); 215+ if (entry.kind === "file") this.contents?.remove(target); 193216 this.entries.delete(target); 194217 this.requireDir(this.parent(target)).children.delete(this.basename(target)); --- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -13,6 +13,8 @@
1313import { EngineProject, SqliteLog } from "./engine-project.ts"; 1414import { artifactsOf, type Env } from "./env.ts"; 1515import { GitDiskIntake } from "./git-disk-intake.ts"; 16+import { GitFileContents } from "./git-file-contents.ts"; 17+import { GitIntakeLimitError } from "./git-intake-limit.ts"; 1618import { GitIntakeTrees } from "./git-intake-trees.ts"; 1719import { pushedSince, remoteHead } from "./ingest.ts"; @@ -65,6 +67,7 @@
6567const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024; 6668const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024; 6769const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024; 70+const GIT_LIMIT_POLICY = `expanded-v2:${GIT_PACK_MAX_BYTES}:${GIT_OBJECT_MAX_BYTES}:${GIT_DECODED_MAX_BYTES}`; 7073 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim @@ -127,6 +130,7 @@
127130 this.blobs = new BlobStore(ctx.storage); 128131 if (env.ABSO_DISK_FIRST === "on") { 129132 GitDiskIntake.recover(ctx.storage); 133+ GitFileContents.recover(ctx.storage); 130134 GitIntakeTrees.recover(ctx.storage); @@ -541,6 +545,22 @@
541545 const seen = await this.ctx.storage.get<string>("git:head"); 542546 const pushed = await this.ctx.storage.get<PushResult>("pushed"); 543547 const head = await remoteHead(artifacts, name); 548+ const refusal = this.diskRuntime() 549+ ? await this.ctx.storage.get<{ head: string; policy: string; kind: GitIntakeLimitError["kind"]; error: string }>( 557+ head !== pushed?.commit && 558+ refusal.head === head && 559+ refusal.policy === GIT_LIMIT_POLICY 561+ throw new GitIntakeLimitError(refusal.kind, refusal.error); 562+ await this.ctx.storage.delete("git:size-refusal"); 544564 if (!head || head === seen || head === pushed?.commit) return null; 545565 const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {}); 546566 using trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined; @@ -560,7 +580,19 @@
560580 retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid), 563− );
583+ ).catch(async (error: unknown) => { 584+ if (trees && error instanceof GitIntakeLimitError) { 587+ policy: GIT_LIMIT_POLICY, 589+ error: error.message, 590+ at: new Date().toISOString(), 592+ await this.ctx.storage.put({ "git:size-refusal": refusal, "git:error": refusal }); 564596 if (!found || found.commits.length === 0) { 565597 if (found) await this.ctx.storage.put("git:head", found.head); @@ -619,14 +651,25 @@
619651 if (!artifacts) return; 620652 const name = await this.ctx.storage.get<string>("name"); 621653 if (!name || !this.useProject((p) => p.exists())) return; 654+ let intakeFailed = false; 622655 await this.gitSync().then( 623− () => this.ctx.storage.delete("git:error"),
624− (e) =>
625− this.ctx.storage.put("git:error", {
657+ await this.ctx.storage.delete("git:error"); 658+ await this.ctx.storage.delete("git:retry-attempts"); 661+ intakeFailed = true; 662+ const attempts = ((await this.ctx.storage.get<number>("git:retry-attempts")) ?? 0) + 1; 663+ await this.ctx.storage.put("git:retry-attempts", attempts); 664+ await this.ctx.storage.put("git:error", { 626665 at: new Date().toISOString(), 627666 error: e instanceof Error ? e.message : String(e), 628− }),
668+ await this.soon(Date.now() + (attempts === 1 ? 1 : attempts === 2 ? 5 : 15) * 60_000); 671+ // Never export over a remote head whose changes could not be taken in. 672+ if (intakeFailed) return; 630673 const shared = pushSnapshot( 631674 this.useProject((p) => p.sharedPushMetadata()), 632675 (version, path) => this.useProject((current) => current.fileTextAt(version, path)), @@ -641,7 +684,20 @@
642685 let result: PushResult; 644− result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha));
687+ result = await pushShared( 691+ (sha) => this.blobs.read(sha), 692+ this.env.ABSO_DISK_FIRST === "on" 694+ storage: this.ctx.storage, 695+ maxPackBytes: GIT_PACK_MAX_BYTES, 696+ maxObjectBytes: GIT_OBJECT_MAX_BYTES, 697+ maxDecodedBytes: GIT_DECODED_MAX_BYTES, 646702 // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times). 647703 const was = await this.ctx.storage.get<{ attempts?: number }>("pushError"); --- a/server/src/push.ts
+++ b/server/src/push.ts
@@ -3,9 +3,14 @@
33// is created on first use. isomorphic-git works in an in-memory filesystem: 44// a depth-1 clone of main with nothing checked out, then a new tree from 55// shared's files that compresses and writes only what changed (abso issue 293). 6+import { createHash } from "node:crypto"; 67import git from "isomorphic-git"; 78import http from "isomorphic-git/http/web"; 89import type { FileModes } from "../../worker/project/project-api.ts"; 10+import type { SqliteStorage } from "./engine-project.ts"; 11+import { GitDiskIntake } from "./git-disk-intake.ts"; 12+import { GitFileContents } from "./git-file-contents.ts"; 13+import { gitHttp } from "./git-http.ts"; 914import { MemoryFS } from "./memory-fs.ts"; 1116export interface PushResult { @@ -33,28 +38,23 @@
3439 files = new Map<string, TreeFile>(), 3540 trees = new Map<string, string>(), 3642): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> { 3743 trees.set(prefix, oid); 38− const { tree } = await git.readTree({ fs, dir, oid });
44+ const { tree } = await git.readTree({ fs, dir, oid, cache }); 3945 for (const e of tree) { 4046 const path = prefix === "" ? e.path : `${prefix}/${e.path}`; 41− if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees);
47+ if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees, cache); 4248 else if (e.type === "blob") files.set(path, { oid: e.oid, mode: e.mode }); 4450 return { files, trees }; 48− * A blob's git oid, with the platform's SHA-1 (abso issue 293): native and awaited, so hashing every file of a big
49− * project neither burns the object's CPU in JavaScript nor holds its other requests back for long.
54+ * Hash the Git header and content separately so export does not allocate a second whole-file buffer. 5156export async function blobOid(bytes: Uint8Array): Promise<string> { 52− const head = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
53− const all = new Uint8Array(head.byteLength + bytes.byteLength);
54− all.set(head);
55− all.set(bytes, head.byteLength);
56− const d = new Uint8Array(await crypto.subtle.digest("SHA-1", all));
57− return [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
57+ return createHash("sha1").update(`blob ${bytes.byteLength}\0`).update(bytes).digest("hex"); 6060const parentOf = (path: string) => { @@ -152,9 +152,18 @@
152152 shared: SharedFiles, 153153 readBlob: (sha256: string) => Uint8Array | null, 154154 part: (commit: string) => Promise<void> = async () => {}, 155156): Promise<{ commit: string; changed: number }> { 157− ? await readTreeFiles(fs, dir, (await git.readCommit({ fs, dir, oid: head })).commit.tree)
158+ ? await readTreeFiles( 161+ (await git.readCommit({ fs, dir, oid: head, cache })).commit.tree, 158167 : { files: new Map<string, TreeFile>(), trees: new Map<string, string>() }; 159168 const blobs = shared.blobs ?? {}; 160169 const now = new Map<string, TreeFile>(); @@ -187,6 +196,7 @@
187196 for (const [path, f] of old.files) if (!files.has(path) && path in blobs) files.set(path, f); 188197 const tree = await writeTrees(fs, dir, files, old.trees, changed); 189198 parent = await git.commit({ @@ -226,27 +236,59 @@
226236 shared: SharedFiles, 227237 /** A binary file's bytes by SHA-256 (#27), from the project's blob store. */ 228238 readBlob: (sha256: string) => Uint8Array | null = () => null, 239+ disk?: { storage: SqliteStorage; maxPackBytes: number; maxObjectBytes: number; maxDecodedBytes: number }, 229240): Promise<PushResult> { 230241 const t0 = Date.now(); 231242 const name = repoName(project); 232243 const { remote, secret } = await writeAccess(artifacts, name); 233244 const onAuth = () => ({ username: "x", password: secret }); 234− let fs = new MemoryFS();
245+ using contents = disk ? new GitFileContents(disk.storage, disk.maxObjectBytes, disk.maxDecodedBytes) : undefined; 247+ ? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes) 249+ const cache = disk ? {} : undefined; 250+ if (intake && cache) intake.attach(cache); 251+ const transport = disk ? gitHttp() : http; 252+ let fs = new MemoryFS(contents); 235253 const dir = "/repo"; 236254 // A new repo has no main yet. isomorphic-git "clones" an empty repo without 237255 // an error but leaves HEAD on master, so check for main and start clean. 238256 // Nothing is checked out: the new tree is built from tree objects (293). 239− const head = await git
240− .clone({ fs, http, dir, url: remote, ref: "main", singleBranch: true, depth: 1, noCheckout: true, onAuth })
241− .then(() => git.resolveRef({ fs, dir, ref: "main" }))
242− .catch(() => null);
257+ // Only an explicitly absent main is an empty repository. Transport, decode, 258+ // and size failures must never become permission to replace remote history. 259+ const refs = await git.listServerRefs({ http: transport, url: remote, onAuth, prefix: "refs/heads/main" }); 260+ let head: string | null = null; 261+ if (refs.some((ref) => ref.ref === "refs/heads/main")) { 274+ intake?.assertReady(); 275+ head = await git.resolveRef({ fs, dir, ref: "main" }); 243277 if (head === null) { 244− fs = new MemoryFS();
278+ fs = new MemoryFS(contents); 245279 await git.init({ fs, dir, defaultBranch: "main" }); 247281 const t1 = Date.now(); 248− const push = () => git.push({ fs, http, dir, url: remote, ref: "main", remoteRef: "main", onAuth });
249− const { commit, changed } = await commitShared(fs, dir, head, shared, readBlob, async () => void (await push()));
282+ const push = () => git.push({ fs, http: transport, cache, dir, url: remote, ref: "main", remoteRef: "main", onAuth }); 283+ const { commit, changed } = await commitShared( 289+ async () => void (await push()), 250292 const t2 = Date.now(); --- a/server/test/git-disk-clone.test.ts
+++ b/server/test/git-disk-clone.test.ts
@@ -3,9 +3,11 @@
33import { test } from "node:test"; 44import git, { type HttpClient } from "isomorphic-git"; 55import { GitDiskIntake } from "../src/git-disk-intake.ts"; 6+import { GitFileContents } from "../src/git-file-contents.ts"; 67import { GitIntakeTrees } from "../src/git-intake-trees.ts"; 78import { pushedSince } from "../src/ingest.ts"; 89import { MemoryFS } from "../src/memory-fs.ts"; 10+import { commitShared } from "../src/push.ts"; 911import { memoryStorage } from "./helpers.ts"; 1113const packet = (text: string | Uint8Array) => { @@ -117,7 +119,8 @@
119121 intake.attach(cache); 120− const fs = new MemoryFS();
122+ const contents = new GitFileContents(storage, 1000000, 2000000); 123+ const fs = new MemoryFS(contents); 121124 const write = fs.promises.writeFile; 122125 fs.promises.writeFile = async (path, ...args) => { 123126 assert.ok(!/\.(pack|idx)$/.test(path), "clone must not persist a collected pack or index"); @@ -206,7 +209,34 @@
206209 assert.equal(await git.resolveRef({ fs, dir, ref: "main" }), head); 207210 assert.equal((await git.readCommit({ fs, dir, cache, oid: head })).commit.tree, tree); 208211 assert.deepEqual(Buffer.from((await git.readBlob({ fs, dir, cache, oid: blobOid })).blob), blob); 212+ const exported = await commitShared( 218+ files: { "new.txt": "Disk export fixture" }, 219+ blobs: { "large.bin": "fixture-blob" }, 225+ const next = await git.readCommit({ fs, dir, cache, oid: exported.commit }); 226+ assert.deepEqual(next.commit.parent, [head]); 228+ Buffer.from((await git.readBlob({ fs, dir, cache, oid: exported.commit, filepath: "large.bin" })).blob), 233+ (await git.readBlob({ fs, dir, cache, oid: exported.commit, filepath: "new.txt" })).blob, 235+ "Disk export fixture", 237+ for (const entry of fs.entries.values()) if (entry.kind === "file") assert.equal(entry.data.byteLength, 0); 211241 storage.db.close(); --- /dev/null
+++ b/server/test/git-export-http.test.ts
@@ -0,0 +1,128 @@
1+import assert from "node:assert/strict"; 2+import { execFileSync, spawn } from "node:child_process"; 3+import { randomBytes } from "node:crypto"; 4+import { mkdtempSync, rmSync } from "node:fs"; 5+import { createServer } from "node:http"; 6+import { tmpdir } from "node:os"; 7+import { join } from "node:path"; 8+import { test } from "node:test"; 9+import { pushShared } from "../src/push.ts"; 10+import { memoryStorage } from "./helpers.ts"; 12+test("disk export streams to real Git receive-pack and preserves remote ancestry", async (t) => { 13+ const root = mkdtempSync(join(tmpdir(), "abso-export-")); 14+ t.after(() => rmSync(root, { recursive: true, force: true })); 15+ const repo = join(root, "fixture.git"); 16+ const command = (...args: string[]) => execFileSync("git", args); 17+ command("init", "--bare", "--initial-branch=main", repo); 18+ command("--git-dir", repo, "config", "http.receivepack", "true"); 20+ let rejectClone = false; 21+ const server = createServer((request, response) => { 22+ const url = new URL(request.url!, "http://fixture.invalid"); 23+ if (rejectClone && url.pathname.endsWith("git-upload-pack")) { 24+ response.writeHead(503).end("injected upload-pack failure"); 27+ if (url.pathname.endsWith("git-receive-pack")) uploads++; 28+ const child = spawn("git", ["http-backend"], { 31+ GIT_PROJECT_ROOT: root, 32+ GIT_HTTP_EXPORT_ALL: "1", 33+ PATH_INFO: url.pathname, 34+ QUERY_STRING: url.search.slice(1), 35+ REQUEST_METHOD: request.method!, 36+ CONTENT_TYPE: request.headers["content-type"] ?? "", 37+ REMOTE_USER: "fixture", 38+ SERVER_PROTOCOL: "HTTP/1.1", 41+ request.pipe(child.stdin); 42+ let headers = Buffer.alloc(0), 44+ child.stdout.on("data", (chunk: Buffer) => { 46+ response.write(chunk); 49+ headers = Buffer.concat([headers, chunk]); 50+ const boundary = headers.indexOf("\r\n\r\n"); 51+ if (boundary < 0) return; 52+ for (const line of headers.subarray(0, boundary).toString().split("\r\n")) { 53+ const colon = line.indexOf(":"); 54+ const key = line.slice(0, colon), 55+ value = line.slice(colon + 1).trim(); 56+ if (key.toLowerCase() === "status") response.statusCode = Number(value.split(" ")[0]); 57+ else response.setHeader(key, value); 60+ response.write(headers.subarray(boundary + 4)); 61+ headers = Buffer.alloc(0); 63+ child.stdout.on("end", () => response.end()); 64+ child.on("error", (error) => response.destroy(error)); 65+ child.stderr.resume(); 67+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); 69+ server.closeAllConnections(); 70+ return new Promise<void>((resolve) => server.close(() => resolve())); 72+ const address = server.address() as { port: number }; 73+ const remote = `http://127.0.0.1:${address.port}/fixture.git`; 76+ info: async () => ({ remote }), 77+ createToken: async () => ({ plaintext: "synthetic-token" }), 78+ [Symbol.dispose]() {}, 81+ const storage = memoryStorage(); 82+ t.after(() => storage.db.close()); 83+ const disk = { storage, maxPackBytes: 8000000, maxObjectBytes: 4000000, maxDecodedBytes: 16000000 }; 84+ const binary = randomBytes(1500000); 85+ const first = await pushShared( 90+ files: { "a.txt": "first\n" }, 91+ blobs: { "large.bin": "binary" }, 96+ const second = await pushShared( 101+ files: { "a.txt": "second\n", "new.txt": "new\n" }, 102+ blobs: { "large.bin": "binary" }, 107+ assert.equal(command("--git-dir", repo, "rev-parse", "main^").toString().trim(), first.commit); 108+ assert.equal(command("--git-dir", repo, "rev-parse", "main").toString().trim(), second.commit); 109+ assert.equal(command("--git-dir", repo, "show", "main:a.txt").toString(), "second\n"); 110+ assert.deepEqual(execFileSync("git", ["--git-dir", repo, "show", "main:large.bin"], { maxBuffer: 4000000 }), binary); 111+ assert.equal(uploads, 2); 113+ await assert.rejects(() => 114+ pushShared(artifacts as never, "fixture", { version: 3, files: { "bad.txt": "must not push" } }, undefined, disk), 116+ assert.equal(uploads, 2, "failed clone must never become an empty-repository push"); 117+ for (const table of [ 125+ "git_object_budget", 127+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table); --- /dev/null
+++ b/server/test/git-file-contents.test.ts
@@ -0,0 +1,88 @@
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 { GitFileContents } from "../src/git-file-contents.ts"; 6+import { MemoryFS } from "../src/memory-fs.ts"; 7+import { memoryStorage } from "./helpers.ts"; 9+test("Git writes and reads exact objects while filesystem entries retain no content bytes", async (t) => { 10+ const storage = memoryStorage(); 11+ t.after(() => storage.db.close()); 12+ using contents = new GitFileContents(storage, 1000000, 10000000); 13+ const fs = new MemoryFS(contents), 15+ await git.init({ fs, dir, defaultBranch: "main" }); 17+ bodies: Uint8Array[] = []; 18+ for (let index = 0; index < 20; index++) { 19+ const body = randomBytes(70000); 23+ path: `file-${index}`, 24+ oid: await git.writeBlob({ fs, dir, blob: body }), 25+ type: "blob" as const, 28+ const tree = await git.writeTree({ fs, dir, tree: entries }); 29+ const commit = await git.commit({ 34+ message: "Scratch fixture", 35+ author: { name: "Fixture", email: "fixture@example.invalid" }, 37+ for (let index = 0; index < 20; index++) { 38+ const blob = await git.readBlob({ fs, dir, oid: commit, filepath: `file-${index}` }); 39+ assert.deepEqual(new Uint8Array(blob.blob), new Uint8Array(bodies[index]!)); 41+ for (const entry of fs.entries.values()) if (entry.kind === "file") assert.equal(entry.data.byteLength, 0); 42+ assert.ok(Number(storage.db.prepare("SELECT MAX(length(data)) AS n FROM git_fs_chunks").get()!.n) <= 65536); 43+ const reference = "/repo/.git/refs/heads/main"; 44+ assert.equal((await fs.stat(reference)).size, ((await fs.readFile(reference)) as Uint8Array).byteLength); 47+test("Git scratch replacement failure preserves old contents, metadata and budget", async (t) => { 48+ const storage = memoryStorage(); 49+ t.after(() => storage.db.close()); 50+ using contents = new GitFileContents(storage, 100000, 150000); 51+ const fs = new MemoryFS(contents); 52+ await fs.writeFile("/file", new Uint8Array([7])); 53+ const exec = storage.sql.exec.bind(storage.sql); 54+ const failure = t.mock.method(storage.sql, "exec", (query: string, ...bindings: unknown[]) => { 55+ if (query.startsWith("INSERT INTO git_fs_chunks") && bindings[2] === 1) throw Error("injected chunk failure"); 56+ return exec(query, ...bindings); 58+ await assert.rejects(() => fs.writeFile("/file", new Uint8Array(70000)), /injected chunk failure/); 59+ assert.deepEqual(await fs.readFile("/file"), new Uint8Array([7])); 60+ assert.equal((await fs.stat("/file")).size, 1); 61+ assert.equal(storage.db.prepare("SELECT bytes FROM git_fs_budget").get()!.bytes, 1); 62+ failure.mock.restore(); 63+ await fs.writeFile("/file", new Uint8Array(70000)); 64+ await assert.rejects(() => fs.writeFile("/other", new Uint8Array(90000)), /total byte limit/); 65+ await assert.rejects(() => fs.stat("/other"), /ENOENT/); 66+ await fs.unlink("/file"); 67+ assert.equal(storage.db.prepare("SELECT bytes FROM git_fs_budget").get()!.bytes, 0); 70+test("cold Git file recovery preserves canonical rows and active scopes dispose independently", (t) => { 71+ const storage = memoryStorage(); 72+ t.after(() => storage.db.close()); 73+ storage.sql.exec("CREATE TABLE canonical_fs_fixture (value TEXT)"); 74+ storage.sql.exec("INSERT INTO canonical_fs_fixture VALUES ('preserved')"); 75+ const first = new GitFileContents(storage, 10, 20), 76+ second = new GitFileContents(storage, 10, 20); 77+ first.write("/a", new Uint8Array([1])); 78+ second.write("/b", new Uint8Array([2])); 80+ assert.deepEqual(second.read("/b"), new Uint8Array([2])); 81+ GitFileContents.recover(storage); 82+ GitFileContents.recover(storage); 83+ for (const table of ["git_fs_meta", "git_fs_chunks", "git_fs_budget"]) 84+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0); 85+ assert.equal(storage.db.prepare("SELECT value FROM canonical_fs_fixture").get()!.value, "preserved"); 86+ assert.throws(() => second.read("/b"), /invalid Git scratch file/); --- a/server/test/git-pack-resolver.test.ts
+++ b/server/test/git-pack-resolver.test.ts
@@ -24,26 +24,34 @@
2424test("delta results consume budget and failed resolution rolls back all accounting", (t) => { 2525 const storage = memoryStorage(); 2626 t.after(() => storage.db.close()); 27− const resolver = new GitPackResolver(storage, 100, 12);
27+ const resolver = new GitPackResolver(storage, 100, 6); 2828 resolver.add(12, "blob", new TextEncoder().encode("abc")); 2929 resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12); 3030 assert.throws(() => resolver.resolve(), /total decoded byte limit/); 31− assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 9);
32+ storage.db.prepare("SELECT decoded FROM git_object_budget WHERE scope NOT LIKE '%:raw'").get()!.decoded, 3235 assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, 2); 3336 assert.throws(() => resolver.get(oid("abcd")), /missing/); 37−test("resolved delta instructions are deleted without refunding decoded work", (t) => {
40+test("raw deltas have a separate bounded budget and are not counted as expanded versions", (t) => { 3841 const storage = memoryStorage(); 3942 t.after(() => storage.db.close()); 40− const resolver = new GitPackResolver(storage, 100, 13);
43+ const resolver = new GitPackResolver(storage, 100, 7); 4144 resolver.add(12, "blob", new TextEncoder().encode("abc")); 4245 resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12); 4447 assert.equal(text(resolver.get(oid("abcd"))), "abcd"); 4548 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);
50+ storage.db.prepare("SELECT decoded FROM git_object_budget WHERE scope NOT LIKE '%:raw'").get()!.decoded, 53+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget WHERE scope LIKE '%:raw'").get()!.decoded, 6); 54+ assert.throws(() => resolver.add(45, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12), /total delta byte limit/); 4755 assert.throws(() => resolver.add(50, "blob", new Uint8Array(1)), /total decoded byte limit/); --- a/server/test/project-object-disk-first.test.ts
+++ b/server/test/project-object-disk-first.test.ts
@@ -5,6 +5,7 @@
55import { Project } from "../../worker/project/project.ts"; 66import { EngineProject } from "../src/engine-project.ts"; 77import { GitDiskIntake } from "../src/git-disk-intake.ts"; 8+import { GitIntakeLimitError } from "../src/git-intake-limit.ts"; 89import { MemoryFS } from "../src/memory-fs.ts"; 910import { memoryStorage } from "./helpers.ts"; @@ -21,6 +22,160 @@
2122const { ProjectObject } = await import("../src/project-object.ts"); 25+for (const disk of [false, true]) 26+ test(`failed intake retries across cold objects with disk mode ${disk}`, async (t) => { 27+ const storage = memoryStorage(); 28+ t.after(() => storage.db.close()); 29+ const values = new Map<string, unknown>(); 30+ let alarm: number | null = null; 32+ id: { toString: () => "retry" }, 35+ get: async (key: string) => values.get(key), 36+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 37+ if (typeof key === "string") values.set(key, value); 38+ else for (const [name, item] of Object.entries(key)) values.set(name, item); 40+ delete: async (key: string) => values.delete(key), 41+ getAlarm: async () => alarm, 42+ setAlarm: async (value: number) => { 47+ const object = (enabled: boolean) => 51+ ABSO_DISK_FIRST: disk ? "on" : "off", 52+ ABSO_ARTIFACTS: enabled ? "on" : "off", 56+ assert.equal((await object(false).call("retry", "init", undefined, { files: { "a.txt": "first\n" } })).status, 200); 58+ for (let page = 0; page < 100; page++) { 59+ if ((await object(false).call("retry", "status", undefined, {})).status === 200) { 64+ assert.equal(ready, true); 66+ t.mock.method(ProjectObject.prototype, "gitSync", async () => { 67+ if (fails) throw Error("transient intake failure"); 70+ for (const [index, minutes] of [1, 5, 15, 15].entries()) { 72+ const before = Date.now(); 73+ await object(true).alarm(); 74+ assert.equal(values.get("git:retry-attempts"), index + 1); 75+ assert.ok(alarm !== null && alarm >= before + minutes * 60000 && alarm <= Date.now() + minutes * 60000); 76+ assert.equal(values.get("pushed"), undefined); 79+ values.set("pushed", { version: Number.MAX_SAFE_INTEGER }); 81+ await object(true).alarm(); 82+ assert.equal(values.has("git:retry-attempts"), false); 83+ assert.equal(values.has("git:error"), false); 86+test("size refusals survive cold objects, retry changed heads or policy, and prevent outgoing pushes", async (t) => { 88+ const storage = memoryStorage(); 89+ t.after(() => storage.db.close()); 90+ const values = new Map<string, unknown>(); 92+ id: { toString: () => "size-refusal" }, 95+ get: async (key: string) => values.get(key), 96+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 97+ if (typeof key === "string") values.set(key, value); 98+ else for (const [name, item] of Object.entries(key)) values.set(name, item); 100+ delete: async (key: string) => values.delete(key), 101+ getAlarm: async () => null, 102+ setAlarm: async (value: number) => { 109+ info: async () => ({ remote: "https://artifacts.invalid/size" }), 110+ createToken: async () => ({ plaintext: "invented-test-token" }), 111+ [Symbol.dispose]() {}, 114+ const object = (enabled = true) => 118+ ABSO_DISK_FIRST: "on", 119+ ABSO_ARTIFACTS: enabled ? "on" : "off", 120+ ARTIFACTS: artifacts, 124+ (await object(false).call("size-refusal", "init", undefined, { files: { "a.txt": "original\n" } })).status, 128+ for (let page = 0; page < 100; page++) { 129+ const result = await object(false).call("size-refusal", "status", undefined, {}); 130+ if (result.status === 200) { 134+ assert.equal(result.status, 503); 136+ assert.equal(ready, true, "project indexing must finish before testing intake refusals"); 137+ let head = "a".repeat(40), 141+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]); 142+ t.mock.method(git, "clone", async () => { 144+ if (transient) throw Error("temporary network failure"); 145+ throw new GitIntakeLimitError("decoded", "Git pack exceeds total decoded byte limit"); 147+ t.mock.method(git, "push", async () => { 149+ return { ok: true }; 151+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 152+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 153+ assert.equal(downloads, 1); 154+ assert.equal(values.get("git:head"), undefined); 155+ assert.equal((await object().out()).version, 0); 156+ assert.match(JSON.stringify((await object().out()).git.error), /decoded byte limit/); 157+ await object().alarm(); 158+ assert.ok(scheduled >= Date.now() + 59_000); 159+ assert.equal(values.get("git:retry-attempts"), 1); 160+ assert.equal(downloads, 1); 161+ assert.equal(pushes, 0); 162+ head = "b".repeat(40); 163+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 164+ assert.equal(downloads, 2); 165+ values.set("git:size-refusal", { ...(values.get("git:size-refusal") as object), policy: "old-policy" }); 166+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 167+ assert.equal(downloads, 3); 168+ head = "c".repeat(40); 170+ await assert.rejects(() => object().gitSync(), /temporary network failure/); 171+ await assert.rejects(() => object().gitSync(), /temporary network failure/); 172+ assert.equal(downloads, 5); 173+ assert.equal(values.has("git:size-refusal"), false); 174+ await object().alarm(); 175+ assert.equal(pushes, 0); 176+ assertGitScratchEmpty(storage); 24179function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) { 25180 for (const table of [ @@ -333,7 +488,16 @@
333488 const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" }); 334489 assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n"); 336− remoteFiles = options.fs as MemoryFS;
491+ // The remote owns its copy; the export's scratch files expire when push returns. 492+ remoteFiles = new MemoryFS(); 493+ for (const [path, entry] of (options.fs as MemoryFS).entries) { 494+ remoteFiles.entries.set( 496+ entry.kind === "file" 497+ ? { ...entry, data: new Uint8Array((await (options.fs as MemoryFS).readFile(path)) as Uint8Array) } 337501 return { ok: true }; 339503 const artifacts = { --- a/server/test/push.test.ts
+++ b/server/test/push.test.ts
@@ -3,8 +3,14 @@
33import git from "isomorphic-git"; 44import { absoVersion } from "../src/ingest.ts"; 55import { MemoryFS } from "../src/memory-fs.ts"; 6−import { commitShared, projectOfRepo, readTreeFiles, repoName } from "../src/push.ts";
6+import { blobOid, commitShared, projectOfRepo, readTreeFiles, repoName } from "../src/push.ts"; 8+it("hashes exact Git blob bytes including a nonzero buffer offset", async () => { 9+ assert.equal(await blobOid(new Uint8Array()), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"); 10+ const bytes = new TextEncoder().encode("prefixhello\nsuffix"); 11+ assert.equal(await blobOid(bytes.subarray(6, 12)), "ce013625030ba8dba906f756967f9e9ca394464a"); 814describe("repo names", () => { 915 it("names a project's Artifacts repo abso-<project>, and back", () => { 1016 assert.equal(repoName("game"), "abso-game");