{"draft":null,"from":116,"to":318,"files":[{"path":"server/src/blobs.ts","added":237,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/blobs.ts\n@@ -0,0 +1,237 @@\n+// Binary files' bytes (#27), content-addressed by SHA-256, kept in the\n+// project's own Durable Object SQLite: 1 MB rows, so a blob is never larger\n+// than a row allows, and hasBlob is a synchronous lookup the engine can call.\n+// Uploads stream in (a Durable Object RPC message stops at 32 MiB) and are\n+// hashed as they arrive; a blob whose bytes don't match its name isn't kept.\n+import { createHash } from \"node:crypto\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+\n+/** Per file. The push out to Artifacts holds a tree in memory, and a Durable Object has 128 MB. */\n+export const BLOB_MAX = 20 * 1024 * 1024;\n+const PART = 1024 * 1024;\n+const SHA = /^[0-9a-f]{64}$/;\n+const SCHEMA =\n+\t\"CREATE TABLE blobs (sha TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (sha, part))\";\n+\n+const normalizedSchema = (sql: string) => sql.replace(/\\s+/g, \" \").trim().toUpperCase();\n+\n+export type PutBlob =\n+\t| { status: 200; body: { sha256: string; size: number; stored: boolean } }\n+\t| { status: 400 | 413; body: { error: string } };\n+\n+export class BlobStore {\n+\tprivate storage: SqliteStorage;\n+\n+\tconstructor(storage: SqliteStorage) {\n+\t\tthis.storage = storage;\n+\t}\n+\n+\t/** Reads must not create storage, including when a cold object has no blobs. */\n+\tprivate hasSchema(): boolean {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT type, sql FROM sqlite_master WHERE name = 'blobs'\").toArray() as {\n+\t\t\ttype: string;\n+\t\t\tsql: string | null;\n+\t\t}[];\n+\t\tif (rows.length === 0) return false;\n+\t\tif (\n+\t\t\trows.length !== 1 ||\n+\t\t\trows[0]?.type !== \"table\" ||\n+\t\t\ttypeof rows[0].sql !== \"string\" ||\n+\t\t\tnormalizedSchema(rows[0].sql) !== normalizedSchema(SCHEMA)\n+\t\t)\n+\t\t\tthrow new Error(\"unsupported blob storage schema\");\n+\t\treturn true;\n+\t}\n+\n+\t/** Only mutation paths may initialize the exact supported table. Never repair a mismatch. */\n+\tprivate ensureSchema(): void {\n+\t\tif (!this.hasSchema()) this.storage.sql.exec(SCHEMA);\n+\t}\n+\n+\t/** Blobs in sha order after `after`, with their sizes (temporary uploads left out). */\n+\tlist(after: string, limit: number): { blobs: { sha: string; size: number }[]; next: string | null } {\n+\t\tif (!this.hasSchema()) return { blobs: [], next: null };\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT sha, SUM(LENGTH(data)) AS size FROM blobs WHERE sha > ? AND sha NOT LIKE 'tmp-%' GROUP BY sha ORDER BY sha LIMIT ?\",\n+\t\t\t\tafter,\n+\t\t\t\tlimit + 1,\n+\t\t\t)\n+\t\t\t.toArray() as { sha: string; size: number }[];\n+\t\tconst more = rows.length > limit;\n+\t\tconst blobs = rows.slice(0, limit);\n+\t\treturn { blobs, next: more ? blobs.at(-1)!.sha : null };\n+\t}\n+\n+\thas(sha: string): boolean {\n+\t\treturn (\n+\t\t\tthis.hasSchema() &&\n+\t\t\tSHA.test(sha) &&\n+\t\t\tthis.storage.sql.exec(\"SELECT 1 FROM blobs WHERE sha = ? LIMIT 1\", sha).toArray().length > 0\n+\t\t);\n+\t}\n+\n+\t/** Every byte, for the push out. Blobs are at most BLOB_MAX. */\n+\tread(sha: string): Uint8Array | null {\n+\t\tif (!this.hasSchema()) return null;\n+\t\tconst rows = this.storage.sql.exec(\"SELECT data FROM blobs WHERE sha = ? ORDER BY part\", sha).toArray() as {\n+\t\t\tdata: ArrayBuffer;\n+\t\t}[];\n+\t\tif (rows.length === 0) return null;\n+\t\tconst out = new Uint8Array(rows.reduce((n, r) => n + r.data.byteLength, 0));\n+\t\tlet at = 0;\n+\t\tfor (const r of rows) {\n+\t\t\tout.set(new Uint8Array(r.data), at);\n+\t\t\tat += r.data.byteLength;\n+\t\t}\n+\t\treturn out;\n+\t}\n+\n+\t/** The bytes as a stream, one row at a time, or null. */\n+\tstream(sha: string): ReadableStream<Uint8Array> | null {\n+\t\tif (!this.has(sha)) return null;\n+\t\tconst parts = (\n+\t\t\tthis.storage.sql.exec(\"SELECT part FROM blobs WHERE sha = ? ORDER BY part\", sha).toArray() as { part: number }[]\n+\t\t).map((r) => r.part);\n+\t\tlet i = 0;\n+\t\treturn new ReadableStream<Uint8Array>({\n+\t\t\tpull: (c) => {\n+\t\t\t\tif (i >= parts.length) return c.close();\n+\t\t\t\tconst [row] = this.storage.sql\n+\t\t\t\t\t.exec(\"SELECT data FROM blobs WHERE sha = ? AND part = ?\", sha, parts[i++]!)\n+\t\t\t\t\t.toArray() as { data: ArrayBuffer }[];\n+\t\t\t\tc.enqueue(new Uint8Array(row!.data));\n+\t\t\t},\n+\t\t});\n+\t}\n+\n+\t/**\n+\t * A whole file's text (#46), stored as UTF-8 under its SHA-256. Synchronous,\n+\t * so the engine can call it while it records.\n+\t */\n+\tputText(text: string): string {\n+\t\tconst bytes = new TextEncoder().encode(text);\n+\t\tconst sha = createHash(\"sha256\").update(bytes).digest(\"hex\");\n+\t\tif (!this.has(sha)) this.write(sha, bytes, 0);\n+\t\treturn sha;\n+\t}\n+\n+\t/** A whole file's text back, or null. */\n+\ttextOf(sha: string): string | null {\n+\t\tconst bytes = this.read(sha);\n+\t\treturn bytes ? new TextDecoder().decode(bytes) : null;\n+\t}\n+\n+\t/** Stores bytes already in memory (plain-git intake), under their own hash. */\n+\tasync putBytes(bytes: Uint8Array): Promise<string> {\n+\t\tconst sha = hex(await crypto.subtle.digest(\"SHA-256\", bytes));\n+\t\tif (!this.has(sha)) this.write(sha, bytes, 0);\n+\t\treturn sha;\n+\t}\n+\n+\t/** Streams an upload in, checking its size and that its SHA-256 is `sha`. */\n+\t/** `max` lowers BLOB_MAX for this put (a capped project's file cap, abso issue 249). */\n+\tasync put(sha: string, body: ReadableStream<Uint8Array>, max: number = BLOB_MAX): Promise<PutBlob> {\n+\t\tif (!SHA.test(sha)) return { status: 400, body: { error: \"a blob's name is its SHA-256 in lowercase hex\" } };\n+\t\tif (this.has(sha)) {\n+\t\t\tawait body.cancel().catch(() => {});\n+\t\t\treturn { status: 200, body: { sha256: sha, size: this.size(sha), stored: false } };\n+\t\t}\n+\t\tconst temp = `tmp-${crypto.randomUUID()}`;\n+\t\tconst digest = new crypto.DigestStream(\"SHA-256\");\n+\t\tconst hashing = digest.getWriter();\n+\t\tlet size = 0;\n+\t\tlet part = 0;\n+\t\tlet pending: Uint8Array[] = [];\n+\t\tlet pendingSize = 0;\n+\t\tconst flush = () => {\n+\t\t\tif (pendingSize === 0) return;\n+\t\t\tpart = this.write(temp, concat(pending, pendingSize), part);\n+\t\t\tpending = [];\n+\t\t\tpendingSize = 0;\n+\t\t};\n+\t\ttry {\n+\t\t\tfor await (const chunk of body) {\n+\t\t\t\tsize += chunk.byteLength;\n+\t\t\t\tif (size > max) {\n+\t\t\t\t\tthis.drop(temp);\n+\t\t\t\t\treturn { status: 413, body: { error: `blobs are at most ${max / 1024 / 1024} MB` } };\n+\t\t\t\t}\n+\t\t\t\tawait hashing.write(chunk);\n+\t\t\t\tpending.push(chunk);\n+\t\t\t\tpendingSize += chunk.byteLength;\n+\t\t\t\tif (pendingSize >= PART) flush();\n+\t\t\t}\n+\t\t\tflush();\n+\t\t\tif (part === 0) part = this.write(temp, new Uint8Array(), 0); // an empty file is a blob too\n+\t\t\tawait hashing.close();\n+\t\t\tconst got = hex(await digest.digest);\n+\t\t\tif (got !== sha) {\n+\t\t\t\tthis.drop(temp);\n+\t\t\t\treturn { status: 400, body: { error: `the bytes hash to ${got}, not ${sha}` } };\n+\t\t\t}\n+\t\t\t// Another upload of the same bytes may have finished meanwhile.\n+\t\t\tif (this.has(sha)) this.drop(temp);\n+\t\t\telse {\n+\t\t\t\tthis.ensureSchema();\n+\t\t\t\tthis.storage.sql.exec(\"UPDATE blobs SET sha = ? WHERE sha = ?\", sha, temp);\n+\t\t\t}\n+\t\t\treturn { status: 200, body: { sha256: sha, size, stored: true } };\n+\t\t} catch (e) {\n+\t\t\tthis.drop(temp);\n+\t\t\tthrow e;\n+\t\t}\n+\t}\n+\n+\t/** Every blob's bytes together, referenced or not (a capped project's total, 249). Uploads in progress don't count. */\n+\ttotal(): number {\n+\t\tif (!this.hasSchema()) return 0;\n+\t\tconst [row] = this.storage.sql\n+\t\t\t.exec(\"SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha NOT LIKE 'tmp-%'\")\n+\t\t\t.toArray() as { n: number }[];\n+\t\treturn row?.n ?? 0;\n+\t}\n+\n+\t/** A blob's size in bytes: 0 when the project doesn't hold it. */\n+\tsize(sha: string): number {\n+\t\tif (!this.hasSchema()) return 0;\n+\t\tconst [row] = this.storage.sql\n+\t\t\t.exec(\"SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha = ?\", sha)\n+\t\t\t.toArray() as { n: number }[];\n+\t\treturn row?.n ?? 0;\n+\t}\n+\n+\t/** Writes bytes as rows of at most PART from part `first` on; answers the next part. An empty blob is one empty row. */\n+\tprivate write(sha: string, bytes: Uint8Array, first: number): number {\n+\t\tthis.ensureSchema();\n+\t\tlet part = first;\n+\t\tfor (let at = 0; at < bytes.byteLength || (at === 0 && part === 0); at += PART) {\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT INTO blobs (sha, part, data) VALUES (?, ?, ?)\",\n+\t\t\t\tsha,\n+\t\t\t\tpart++,\n+\t\t\t\tbytes.slice(at, at + PART),\n+\t\t\t);\n+\t\t\tif (bytes.byteLength === 0) break;\n+\t\t}\n+\t\treturn part;\n+\t}\n+\n+\tprivate drop(sha: string) {\n+\t\tthis.ensureSchema();\n+\t\tthis.storage.sql.exec(\"DELETE FROM blobs WHERE sha = ?\", sha);\n+\t}\n+}\n+\n+function concat(chunks: Uint8Array[], size: number): Uint8Array {\n+\tif (chunks.length === 1) return chunks[0]!;\n+\tconst out = new Uint8Array(size);\n+\tlet at = 0;\n+\tfor (const c of chunks) {\n+\t\tout.set(c, at);\n+\t\tat += c.byteLength;\n+\t}\n+\treturn out;\n+}\n+\n+const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");"}],"unmatched":[]}