- MCP
- blame on this site's /mcp
- CLI
- abso blame server/src/blobs.ts --json
- JSON
- /christopher/abso-core/blame/server/src/blobs.ts?format=json
237 linesspeed 100%Last change speed in version 150,
237 lines from 1 change in 1 version.
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare1// Binary files' bytes (#27), content-addressed by SHA-256, kept in the
2// project's own Durable Object SQLite: 1 MB rows, so a blob is never larger
3// than a row allows, and hasBlob is a synchronous lookup the engine can call.
4// Uploads stream in (a Durable Object RPC message stops at 32 MiB) and are
5// hashed as they arrive; a blob whose bytes don't match its name isn't kept.
6import { createHash } from "node:crypto";
7import type { SqliteStorage } from "./engine-project.ts";
9/** Per file. The push out to Artifacts holds a tree in memory, and a Durable Object has 128 MB. */
10export const BLOB_MAX = 20 * 1024 * 1024;
11const PART = 1024 * 1024;
12const SHA = /^[0-9a-f]{64}$/;
13const SCHEMA =
14 "CREATE TABLE blobs (sha TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (sha, part))";
16const normalizedSchema = (sql: string) => sql.replace(/\s+/g, " ").trim().toUpperCase();
18export type PutBlob =
19 | { status: 200; body: { sha256: string; size: number; stored: boolean } }
20 | { status: 400 | 413; body: { error: string } };
22export class BlobStore {
23 private storage: SqliteStorage;
25 constructor(storage: SqliteStorage) {
26 this.storage = storage;
27 }
29 /** Reads must not create storage, including when a cold object has no blobs. */
30 private hasSchema(): boolean {
31 const rows = this.storage.sql.exec("SELECT type, sql FROM sqlite_master WHERE name = 'blobs'").toArray() as {
32 type: string;
33 sql: string | null;
34 }[];
35 if (rows.length === 0) return false;
36 if (
37 rows.length !== 1 ||
38 rows[0]?.type !== "table" ||
39 typeof rows[0].sql !== "string" ||
40 normalizedSchema(rows[0].sql) !== normalizedSchema(SCHEMA)
41 )
42 throw new Error("unsupported blob storage schema");
43 return true;
44 }
46 /** Only mutation paths may initialize the exact supported table. Never repair a mismatch. */
47 private ensureSchema(): void {
48 if (!this.hasSchema()) this.storage.sql.exec(SCHEMA);
49 }
51 /** Blobs in sha order after `after`, with their sizes (temporary uploads left out). */
52 list(after: string, limit: number): { blobs: { sha: string; size: number }[]; next: string | null } {
53 if (!this.hasSchema()) return { blobs: [], next: null };
54 const rows = this.storage.sql
55 .exec(
56 "SELECT sha, SUM(LENGTH(data)) AS size FROM blobs WHERE sha > ? AND sha NOT LIKE 'tmp-%' GROUP BY sha ORDER BY sha LIMIT ?",
57 after,
58 limit + 1,
59 )
60 .toArray() as { sha: string; size: number }[];
61 const more = rows.length > limit;
62 const blobs = rows.slice(0, limit);
63 return { blobs, next: more ? blobs.at(-1)!.sha : null };
64 }
66 has(sha: string): boolean {
67 return (
68 this.hasSchema() &&
69 SHA.test(sha) &&
70 this.storage.sql.exec("SELECT 1 FROM blobs WHERE sha = ? LIMIT 1", sha).toArray().length > 0
71 );
72 }
74 /** Every byte, for the push out. Blobs are at most BLOB_MAX. */
75 read(sha: string): Uint8Array | null {
76 if (!this.hasSchema()) return null;
77 const rows = this.storage.sql.exec("SELECT data FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as {
78 data: ArrayBuffer;
79 }[];
80 if (rows.length === 0) return null;
81 const out = new Uint8Array(rows.reduce((n, r) => n + r.data.byteLength, 0));
82 let at = 0;
83 for (const r of rows) {
84 out.set(new Uint8Array(r.data), at);
85 at += r.data.byteLength;
86 }
87 return out;
88 }
90 /** The bytes as a stream, one row at a time, or null. */
91 stream(sha: string): ReadableStream<Uint8Array> | null {
92 if (!this.has(sha)) return null;
93 const parts = (
94 this.storage.sql.exec("SELECT part FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as { part: number }[]
95 ).map((r) => r.part);
96 let i = 0;
97 return new ReadableStream<Uint8Array>({
98 pull: (c) => {
99 if (i >= parts.length) return c.close();
100 const [row] = this.storage.sql
101 .exec("SELECT data FROM blobs WHERE sha = ? AND part = ?", sha, parts[i++]!)
102 .toArray() as { data: ArrayBuffer }[];
103 c.enqueue(new Uint8Array(row!.data));
104 },
105 });
106 }
108 /**
109 * A whole file's text (#46), stored as UTF-8 under its SHA-256. Synchronous,
110 * so the engine can call it while it records.
111 */
112 putText(text: string): string {
113 const bytes = new TextEncoder().encode(text);
114 const sha = createHash("sha256").update(bytes).digest("hex");
115 if (!this.has(sha)) this.write(sha, bytes, 0);
116 return sha;
117 }
119 /** A whole file's text back, or null. */
120 textOf(sha: string): string | null {
121 const bytes = this.read(sha);
122 return bytes ? new TextDecoder().decode(bytes) : null;
123 }
125 /** Stores bytes already in memory (plain-git intake), under their own hash. */
126 async putBytes(bytes: Uint8Array): Promise<string> {
127 const sha = hex(await crypto.subtle.digest("SHA-256", bytes));
128 if (!this.has(sha)) this.write(sha, bytes, 0);
129 return sha;
130 }
132 /** Streams an upload in, checking its size and that its SHA-256 is `sha`. */
133 /** `max` lowers BLOB_MAX for this put (a capped project's file cap, abso issue 249). */
134 async put(sha: string, body: ReadableStream<Uint8Array>, max: number = BLOB_MAX): Promise<PutBlob> {
135 if (!SHA.test(sha)) return { status: 400, body: { error: "a blob's name is its SHA-256 in lowercase hex" } };
136 if (this.has(sha)) {
137 await body.cancel().catch(() => {});
138 return { status: 200, body: { sha256: sha, size: this.size(sha), stored: false } };
139 }
140 const temp = `tmp-${crypto.randomUUID()}`;
141 const digest = new crypto.DigestStream("SHA-256");
142 const hashing = digest.getWriter();
143 let size = 0;
144 let part = 0;
145 let pending: Uint8Array[] = [];
146 let pendingSize = 0;
147 const flush = () => {
148 if (pendingSize === 0) return;
149 part = this.write(temp, concat(pending, pendingSize), part);
150 pending = [];
151 pendingSize = 0;
152 };
153 try {
154 for await (const chunk of body) {
155 size += chunk.byteLength;
156 if (size > max) {
157 this.drop(temp);
158 return { status: 413, body: { error: `blobs are at most ${max / 1024 / 1024} MB` } };
159 }
160 await hashing.write(chunk);
161 pending.push(chunk);
162 pendingSize += chunk.byteLength;
163 if (pendingSize >= PART) flush();
164 }
165 flush();
166 if (part === 0) part = this.write(temp, new Uint8Array(), 0); // an empty file is a blob too
167 await hashing.close();
168 const got = hex(await digest.digest);
169 if (got !== sha) {
170 this.drop(temp);
171 return { status: 400, body: { error: `the bytes hash to ${got}, not ${sha}` } };
172 }
173 // Another upload of the same bytes may have finished meanwhile.
174 if (this.has(sha)) this.drop(temp);
175 else {
176 this.ensureSchema();
177 this.storage.sql.exec("UPDATE blobs SET sha = ? WHERE sha = ?", sha, temp);
178 }
179 return { status: 200, body: { sha256: sha, size, stored: true } };
180 } catch (e) {
181 this.drop(temp);
182 throw e;
183 }
184 }
186 /** Every blob's bytes together, referenced or not (a capped project's total, 249). Uploads in progress don't count. */
187 total(): number {
188 if (!this.hasSchema()) return 0;
189 const [row] = this.storage.sql
190 .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha NOT LIKE 'tmp-%'")
191 .toArray() as { n: number }[];
192 return row?.n ?? 0;
193 }
195 /** A blob's size in bytes: 0 when the project doesn't hold it. */
196 size(sha: string): number {
197 if (!this.hasSchema()) return 0;
198 const [row] = this.storage.sql
199 .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha = ?", sha)
200 .toArray() as { n: number }[];
201 return row?.n ?? 0;
202 }
204 /** Writes bytes as rows of at most PART from part `first` on; answers the next part. An empty blob is one empty row. */
205 private write(sha: string, bytes: Uint8Array, first: number): number {
206 this.ensureSchema();
207 let part = first;
208 for (let at = 0; at < bytes.byteLength || (at === 0 && part === 0); at += PART) {
209 this.storage.sql.exec(
210 "INSERT INTO blobs (sha, part, data) VALUES (?, ?, ?)",
211 sha,
212 part++,
213 bytes.slice(at, at + PART),
214 );
215 if (bytes.byteLength === 0) break;
216 }
217 return part;
218 }
220 private drop(sha: string) {
221 this.ensureSchema();
222 this.storage.sql.exec("DELETE FROM blobs WHERE sha = ?", sha);
223 }
224}
226function concat(chunks: Uint8Array[], size: number): Uint8Array {
227 if (chunks.length === 1) return chunks[0]!;
228 const out = new Uint8Array(size);
229 let at = 0;
230 for (const c of chunks) {
231 out.set(c, at);
232 at += c.byteLength;
233 }
234 return out;
235}
237const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");