// SQL WORLD STORE — the WorldStore primitives over a SYNCHRONOUS SQLite handle. // // A Cloudflare Durable Object's `ctx.storage.sql` is synchronous, so the kernel's synchronous // store seam maps onto it directly: no hydrate-the-world-then-flush boundary, no snapshot cap, and // a request touches only the rows it reads. The handle is injected (`SqlExec` is the one method the // store calls), so this module imports nothing and stays safe in every bundle. // // Layout: `ws_files` holds one row per file (byte size, version); `ws_chunks` holds its content in // order. An append adds a chunk; a write replaces them. Content is split so no row nears SQLite's // per-row limit on the Durable Object backend (2 MB). Directories are implicit in the path set, as // in MemoryWorldStore, whose semantics this store matches method for method. // // Versions: `stat().mtimeMs` is the file's version, drawn from a counter persisted in the database. // storage.ts's append-dedupe cache lives across requests in an isolate and is validated by // (size, mtimeMs), so a version may never repeat for a path — not across requests, not across a // restarted object. import type { WorldStat, WorldStore } from './world-store.ts'; type SqlValue = string | number | null | ArrayBuffer; /** The slice of a SQLite handle the store uses — Durable Objects' `SqlStorage` satisfies it. */ export type SqlExec = { exec(query: string, ...bindings: unknown[]): { toArray(): Record[] } }; /** Characters per stored chunk: at most 4 UTF-8 bytes each, well under a 2 MB row. */ const CHUNK = 256 * 1024; const encoder = new TextEncoder(); /** `[low, high)` bounds selecting every path strictly under `dir`. */ function under(dir: string): [string, string] { const base = dir.endsWith('/') ? dir.slice(0, -1) : dir; return [`${base}/`, `${base}0`]; // '0' is the code point after '/' } export class SqlWorldStore implements WorldStore { private version: number; constructor(private readonly sql: SqlExec) { sql.exec('CREATE TABLE IF NOT EXISTS ws_files (path TEXT PRIMARY KEY, size INTEGER NOT NULL, version INTEGER NOT NULL, chunks INTEGER NOT NULL)'); sql.exec('CREATE TABLE IF NOT EXISTS ws_chunks (path TEXT NOT NULL, seq INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (path, seq))'); this.version = Number(sql.exec('SELECT COALESCE(MAX(version), 0) AS v FROM ws_files').toArray()[0]?.v ?? 0); } private file(path: string): { size: number; version: number; chunks: number } | null { const row = this.sql.exec('SELECT size, version, chunks FROM ws_files WHERE path = ?', path).toArray()[0]; return row ? { size: Number(row.size), version: Number(row.version), chunks: Number(row.chunks) } : null; } private put(path: string, data: string, from: number, size: number): void { let seq = from; for (let i = 0; i < data.length; i += CHUNK) this.sql.exec('INSERT INTO ws_chunks (path, seq, data) VALUES (?, ?, ?)', path, seq++, data.slice(i, i + CHUNK)); this.version += 1; this.sql.exec('INSERT INTO ws_files (path, size, version, chunks) VALUES (?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET size = excluded.size, version = excluded.version, chunks = excluded.chunks', path, size, this.version, seq); } read(path: string): string | null { if (!this.file(path)) return null; return this.sql.exec('SELECT data FROM ws_chunks WHERE path = ? ORDER BY seq', path).toArray().map((r) => String(r.data)).join(''); } readLines(path: string): string[] { const content = this.read(path); return content === null ? [] : content.split('\n'); } append(path: string, data: string): void { const existing = this.file(path); this.put(path, data, existing?.chunks ?? 0, (existing?.size ?? 0) + encoder.encode(data).length); } write(path: string, data: string): void { this.sql.exec('DELETE FROM ws_chunks WHERE path = ?', path); this.put(path, data, 0, encoder.encode(data).length); } writeAtomic(path: string, data: string): void { // One synchronous run of SQL with no await inside: no reader interleaves, and the object's // output gate holds the response until the write is durable. this.write(path, data); } exists(path: string): boolean { if (this.file(path)) return true; const [low, high] = under(path); return this.sql.exec('SELECT 1 FROM ws_files WHERE path >= ? AND path < ? LIMIT 1', low, high).toArray().length > 0; } remove(path: string): void { const [low, high] = under(path); this.sql.exec('DELETE FROM ws_chunks WHERE path = ? OR (path >= ? AND path < ?)', path, low, high); this.sql.exec('DELETE FROM ws_files WHERE path = ? OR (path >= ? AND path < ?)', path, low, high); } mkdir(_dirPath: string): void { // Directories are implicit in the path set. } list(dirPath: string): string[] { const [low, high] = under(dirPath); const children = new Set(); for (const row of this.sql.exec('SELECT path FROM ws_files WHERE path >= ? AND path < ?', low, high).toArray()) { const rest = String(row.path).slice(low.length); const slash = rest.indexOf('/'); children.add(slash === -1 ? rest : rest.slice(0, slash)); } return [...children]; } stat(path: string): WorldStat | null { const file = this.file(path); if (file) return { size: file.size, mtimeMs: file.version, isDirectory: false }; return this.exists(path) ? { size: 0, mtimeMs: 0, isDirectory: true } : null; } withLock(_lockPath: string, fn: () => T): T { // A Durable Object runs one synchronous stretch of JavaScript at a time and `fn` is synchronous, // so the kernel's read-then-append critical sections are already exclusive. return fn(); } }