Lines 3–15 at 318 (were 3–13 at 156)
33// 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the 44// writer-adoption and R2 version parts are left out. 6+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts"; 67import { blame, folderBlame, why } from "../../worker/project/blame.ts"; 78import { feedEvents } from "../../worker/project/feed.ts"; 89import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts"; 910import type { EditBody, ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 1011import { where } from "../../worker/project/where.ts"; 12+import type { PushSnapshotMetadata } from "./push-snapshot.ts"; 1214/** The parts of a Durable Object's storage the log and blob store use, declared structurally so tests can stand in. */ 1315export interface SqliteStorage { Lines 19–32 at 318 (were 17–30 at 156)
1820// Characters per row. SQLite's 2 MB cap is in bytes, and a character is at 1921// most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it. 20−const PART = 600_000;
22+export const LOG_PART_CHARACTERS = 600_000; 22−/** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */
24+/** An entry's JSON in rows of at most LOG_PART_CHARACTERS characters, never cutting an emoji's two halves apart. */ 2325export function logParts(text: string): string[] { 2426 const parts: string[] = []; 27− let end = Math.min(at + PART, text.length);
29+ let end = Math.min(at + LOG_PART_CHARACTERS, text.length); 2830 const c = text.charCodeAt(end - 1); 2931 if (end < text.length && c >= 0xd800 && c <= 0xdbff) end--; 3032 parts.push(text.slice(at, end)); Lines 35–56 at 318 (were 33–38 at 156)
38+/** Retains one log row plus an encoder fragment, preserving legacy row boundaries. */ 39+export function* streamedLogParts(value: unknown): IterableIterator<string> { 41+ for (const chunk of jsonValueChunks(value)) { 43+ while (pending.length > LOG_PART_CHARACTERS) { 44+ let end = LOG_PART_CHARACTERS; 45+ const last = pending.charCodeAt(end - 1); 46+ if (last >= 0xd800 && last <= 0xdbff) end--; 47+ yield pending.slice(0, end); 48+ pending = pending.slice(end); 51+ if (pending) yield pending; 3654/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */ 3755function linesIn(entry: Entry): number { Lines 113–190 at 318 (were 95–100 at 156)
116+ /** Reject an oversized canonical frame before loading its text into JavaScript. */ 117+ frameBytes(seq: number): number { 118+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position"); 119+ const size = this.storage.sql 121+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?", 124+ .toArray()[0] as { parts: number; bytes: number }; 125+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes < 1 || !Number.isSafeInteger(size.bytes)) 126+ throw Error("canonical frame exceeds hard decoding bound or is missing"); 129+ /** A larger first frame gets its own budget; later frames are deferred. */ 130+ adoptionPageBytes(from: number): number { 131+ return Math.max(1_048_576, this.frameBytes(from)); 134+ boundedFrame(seq: number, maxBytes: number): string { 136+ !Number.isSafeInteger(seq) || 138+ !Number.isSafeInteger(maxBytes) || 140+ maxBytes > 8_000_000 142+ throw new Error("invalid canonical frame bound"); 143+ const size = this.storage.sql 145+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?", 148+ .toArray()[0] as { parts: number; bytes: number }; 149+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes > maxBytes) 150+ throw new Error("canonical frame exceeds adoption bound or is missing"); 151+ const rows = this.storage.sql.exec("SELECT part, text FROM log WHERE seq = ? ORDER BY part", seq).toArray() as { 155+ if (rows.length !== size.parts || rows.some((row, part) => row.part !== part)) 156+ throw new Error("canonical frame parts are incomplete"); 157+ return rows.map((row) => row.text).join(""); 160+ /** Stream one canonical frame without retaining its complete JSON text. */ 161+ *frameChunks(seq: number): IterableIterator<string> { 162+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position"); 165+ const rows = this.storage.sql 166+ .exec("SELECT part, text FROM log WHERE seq = ? AND part >= ? ORDER BY part LIMIT 1", seq, expected) 167+ .toArray() as { part: number; text: string }[]; 169+ if (!expected) throw Error("canonical frame is missing"); 172+ const row = rows[0]!; 173+ if (row.part !== expected || row.text.length > LOG_PART_CHARACTERS) 174+ throw Error("canonical frame parts are incomplete or oversized"); 180+ /** Refreshes the in-memory cursor after an enclosing transaction rolls back. */ 181+ refreshSequence(): void { 182+ const rows = this.storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as { 185+ this.next = (rows[0]?.last ?? -1) + 1; 98188 /** Monotonic cache invalidation epoch for every canonical log mutation. */ 99189 generation(): number { 100190 const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as { Lines 442–452 at 318 (were 352–362 at 156)
352442 if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys); 354444 for (const entry of entries) { 355− const json = JSON.stringify(entry);
356− logParts(json).forEach((text, part) => {
446+ for (const text of streamedLogParts(entry)) { 357447 chars += text.length; 358− this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part, text);
359− });
448+ this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part++, text); 362452 // Chars are only added to once counted: a log from before the count is summed whole first (logSize). Lines 496–507 at 318 (were 406–413 at 156)
406496 ...(folder !== undefined ? { folder } : {}), 409− why(file: string, line: number, draft?: string, agent?: string) {
410− return why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
499+ why(file: string, line: number, draft?: string, agent?: string, version?: number) { 500+ return why(this.project, file, line, { 501+ ...(draft ? { draft } : {}), 502+ ...(agent ? { agent } : {}), 503+ ...(version !== undefined ? { version } : {}), 413507 return where(this.project); Lines 523–535 at 318 (were 429–437 at 156)
429523 fileAt(path: string, version: number, draft: string | null, agent?: string) { 430524 return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) }); 432− compare(from: number, to: number, draft: string | null, agent?: string) {
433− return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });
526+ compare(from: number, to: number, draft: string | null, agent?: string, summary?: boolean) { 527+ const where = { draft, ...(agent ? { agent } : {}) }; 528+ return summary ? this.project.compareSummary(from, to, where) : this.project.compare(from, to, where); 530+ without(version: number, versions: readonly number[]) { 531+ return this.project.without(version, versions); 435533 show(version: number, draft: string | null, agent?: string) { 436534 return this.project.show(version, { draft, ...(agent ? { agent } : {}) }); Lines 572–581 at 318 (were 474–479 at 156)
474572 announcePerson(person: { id: string; name: string }, text: string, to?: string[]) { 475573 return this.project.announcePerson(person, text, to, Date.now()); 575+ /** A seat's earlier chat hears that another chat used the seat (277, groups); as abso's worker has it. */ 576+ seatNotice(agent: string, place: string, key: string) { 577+ return this.project.seatNotice(agent, place, key); 477579 starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) { 478580 return this.project.starting(agent, text, files, Date.now(), options); Lines 591–608 at 318 (were 489–499 at 156)
489591 /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */ 490592 private readonly read: ((from: number, limit: number) => Entry[]) | undefined; 491593 private readonly store: SqliteLog | undefined; 594+ private readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined; 493− constructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {
598+ read?: (from: number, limit: number) => Entry[], 600+ historical?: <T>(at: number, operation: (project: Project) => T) => T, 494602 this.project = project; 496604 this.store = store; 605+ this.historical = historical; 499608 /** The project's events from log position `from` (#41): reading consumes nothing. */ Lines 610–632 at 318 (were 501–514 at 156)
501610 if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" }); 502611 const end = this.project.logLength; 503612 const start = Math.max(0, Math.min(from, end)); 504− const entries = start < end ? this.read(start, Math.min(limit, end - start)) : [];
613+ // Discard each canonical payload after extracting its event. A feed page must 614+ // not retain every historical file payload in the requested range. 617+ while (next < end && next - start < limit) { 618+ const entries = this.read(next, 1); 619+ if (entries.length === 0) break; 620+ events.push(...feedEvents(entries, next)); 621+ next += entries.length; 505623 // A drop event names the files it took out (#41), so a timeline needs no read per drop. 506− const events = feedEvents(entries, start).map((e) => {
624+ const enriched = events.map((e) => { 507625 if (e.type !== "drop" || e.version === undefined) return e; 508626 const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0]; 509627 return v && v.version === e.version ? { ...e, dropped: v.files } : e; 511− return { next: start + entries.length, end, events };
629+ return { next, end, events: enriched }; 514632 /** The log position for a time (ms since 1970) or a version of shared (#41). */ Lines 712–722 at 318 (were 594–599 at 156)
594712 return this.replica; 596714 statusAt(at: number) { 715+ if (this.historical) 716+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({ 717+ at: Math.min(at, this.project.logLength), 718+ ...(p.initialized ? p.status() : { version: -1, agents: [] }), 597720 const p = this.at(at); 599722 at: Math.min(at, this.project.logLength), Lines 726–736 at 318 (were 603–608 at 156)
605728 whereAt(at: number) { 729+ if (this.historical) 730+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({ 731+ at: Math.min(at, this.project.logLength), 732+ ...(p.initialized ? where(p) : { version: -1, files: {} }), 606734 const p = this.at(at); 608736 at: Math.min(at, this.project.logLength), Lines 820–857 at 318 (were 692–697 at 156)
692820 filesAt(version: number) { 693821 return this.project.viewAt(version).files(); 823+ fileTextAt(version: number, path: string): string { 824+ return this.project.viewAt(version).text(path); 826+ /** One scoped batch: at most 64 files and 64 Ki characters plus one whole file. */ 827+ fileTextsAt(version: number, paths: readonly string[]): Record<string, string> { 828+ const view = this.project.viewAt(version); 829+ const files: Record<string, string> = Object.create(null); 831+ for (const path of paths.slice(0, 64)) { 832+ const text = view.attrs(path).link !== null ? "" : view.text(path); 834+ characters += text.length; 835+ if (characters >= 65536) break; 839+ /** Capture metadata now; each text read reopens the captured version in a fresh host scope. */ 840+ sharedPushMetadata(): PushSnapshotMetadata { 841+ const version = this.project.version; 842+ const view = this.project.viewAt(version); 843+ const paths: string[] = []; 844+ const modes: PushSnapshotMetadata["modes"] = Object.create(null); 845+ const blobs: Record<string, string> = Object.create(null); 846+ for (const path of view.paths()) { 847+ const attrs = view.attrs(path); 848+ modes[path] = { exec: attrs.exec, link: attrs.link }; 849+ if (attrs.blob !== null) blobs[path] = attrs.blob; 850+ else paths.push(path); 852+ const by = version > 0 ? this.project.published(version) : undefined; 853+ return { version, paths, modes, blobs, ...(by ? { last: { agent: by.agent, message: by.message } } : {}) }; 695855 blobsAt(version: number) { 696856 return this.project.viewAt(version).blobs();