// THE BLOB SEAM (runtime contract R11) — byte storage behind every handler that touches // raw bytes (slack file uploads, jira attachments), so a serverless namespace can put its // bytes in object storage while local Worlds use files. // // Why bytes get their OWN seam instead of riding WorldStore: WorldStore is string-typed by // design (JSONL rows, JSON sidecars — the hydrate/flush snapshot is a path→string map), and // blob bytes must never enter that snapshot: they can be large, they never participate in // preconditions or projection, and they are served/accepted at the edge. Blob KEYS live in // string state; bytes live here. That separation is what keeps namespace snapshots small // enough for a Durable Object's memory (runtime contract R11–R14). // // ASYNC-NATIVE, unlike WorldStore: the sync kernel never reads blobs mid-projection — bytes // are read/written at the request edge (upload accept, download serve), which is already // async in every server. So there is no hydrate-whole-namespace step for blobs and no sync // constraint to honor: an R2/S3 adapter implements this interface directly, per request. // // Keys are PATHS (the FsWorldStore convention): the fs backend uses them verbatim on disk, // so packs compute the layout (…/resources/blobs/sha256//) that local backup and inspection read. // A remote adapter maps the path to an object key (namespace prefix + path). import { createHash, randomUUID } from 'node:crypto'; import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { volterHome } from './volter-home.ts'; import { sharedBlobIndex } from './shared-blob-index.ts'; import { refuseReadOnlyWrite, writesRefused } from './request-scope.ts'; export interface BlobStore { /** Bytes at `key`, or null when absent. Never throws for a missing key. */ get(key: string): Promise; /** Store bytes at `key`, atomically (a reader never observes a torn blob). Creating * parent "directories" is the store's job; idempotent overwrite is allowed (content- * addressed callers never rewrite different bytes under one key). */ put(key: string, bytes: Uint8Array): Promise; exists(key: string): Promise; /** Remove the blob (or, for a prefix ending in '/', everything under it — namespace * reset uses this). A missing key is not an error. */ remove(key: string): Promise; /** Keys currently stored under `prefix` (full keys, sorted). Lifecycle/reset tooling * only — the serve path addresses blobs by exact key. */ list(prefix: string): Promise; /** Byte size at `key`, or null when absent. */ size(key: string): Promise; /** Bytes `start`..`endInclusive` at `key` (clamped to the blob), or null when absent — a native * ranged read, so serving a range of a large blob (a video a player seeks in) does not load it * whole. Optional: `readBlobRange` falls back to `get` (a whole read) for a backend without it — * the hosted World's R2 store today. */ getRange?(key: string, start: number, endInclusive: number): Promise; /** A body's chunks written to `key` as they arrive and hashed as they are written, kept (atomically, as `put`) * only when `accept` holds for their size and SHA-256; otherwise nothing is kept. True when kept. So an upload * of a large object (a model's weights) never holds more than a chunk. Optional: `writeBlobStream` collects * the chunks and `put`s them for a backend without it. */ putStream?(key: string, chunks: AsyncIterable, accept: (written: BlobWritten) => boolean): Promise; } /** What a streamed write wrote: its byte length and its SHA-256 (hex). */ export type BlobWritten = { size: number; sha256: string }; /** A body's chunks to `key` through the active store, kept when `accept` holds for what was written (the store's * own streamed write where it has one, else the chunks collected and `put`). True when kept. */ export async function writeBlobStream(key: string, chunks: AsyncIterable, accept: (written: BlobWritten) => boolean): Promise { const store = getActiveBlobStore(); if (store.putStream) return store.putStream(key, chunks, accept); const parts: Uint8Array[] = []; let size = 0; for await (const chunk of chunks) { parts.push(chunk); size += chunk.byteLength; } const bytes = new Uint8Array(size); let at = 0; for (const part of parts) { bytes.set(part, at); at += part.byteLength; } if (!accept({ size, sha256: blobDigest(bytes) })) return false; await store.put(key, bytes); return true; } /** A web stream's chunks, read by its reader (a browser's ReadableStream need not be async-iterable). */ export async function* streamChunks(body: ReadableStream): AsyncGenerator { const reader = body.getReader(); try { for (;;) { const { done, value } = await reader.read(); if (done) return; if (value) yield value; } } finally { reader.releaseLock(); } } /** A range of the blob at `key` through the active store: native when the store has it, else sliced. */ export async function readBlobRange(key: string, start: number, endInclusive: number): Promise { // one clamping for every backend: a negative or non-finite start reads from 0, a range that ends // before it begins is empty (subarray alone would count negatives from the end) const from = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0; const to = Number.isFinite(endInclusive) ? Math.floor(endInclusive) : -1; const store = getActiveBlobStore(); if (to < from) return (await store.exists(key)) ? new Uint8Array(0) : null; if (store.getRange) return store.getRange(key, from, to); const whole = await store.get(key); return whole === null ? null : whole.subarray(from, to + 1); } /** Today's layout, verbatim: keys are filesystem paths. */ export class FsBlobStore implements BlobStore { constructor(private options: { sharedIndexRoot?: string | false } = {}) {} async get(key: string): Promise { if (!existsSync(key)) return null; return new Uint8Array(readFileSync(key)); } async put(key: string, bytes: Uint8Array): Promise { mkdirSync(dirname(key), { recursive: true }); // Write-then-rename so a crash mid-write never leaves a truncated blob that a // content-addressed caller would forever report as present (the slack-blobs rule, // now the seam's rule). const tmp = `${key}.tmp.${randomUUID()}`; let index: ReturnType | undefined; try { if (this.options.sharedIndexRoot !== false) { try { index = sharedBlobIndex(this.options.sharedIndexRoot ?? join(volterHome(), 'blob-index-v1'), statSync(dirname(key)).dev, blobDigest(bytes)); } catch { /* The index is an optimization, never a prerequisite for a blob write. */ } } if (!index?.reuse(tmp, bytes.byteLength)) writeFileSync(tmp, bytes, { flag: 'wx' }); renameSync(tmp, key); index?.record(key); } finally { rmSync(tmp, { force: true }); } } async putStream(key: string, chunks: AsyncIterable, accept: (written: BlobWritten) => boolean): Promise { mkdirSync(dirname(key), { recursive: true }); const tmp = `${key}.tmp.${randomUUID()}`; const hash = createHash('sha256'); let size = 0; try { const fd = openSync(tmp, 'wx'); try { for await (const chunk of chunks) { hash.update(chunk); size += chunk.byteLength; for (let at = 0; at < chunk.byteLength;) at += writeSync(fd, chunk, at, chunk.byteLength - at); } } finally { closeSync(fd); } const sha256 = hash.digest('hex'); if (!accept({ size, sha256 })) return false; renameSync(tmp, key); if (this.options.sharedIndexRoot !== false) { try { sharedBlobIndex(this.options.sharedIndexRoot ?? join(volterHome(), 'blob-index-v1'), statSync(dirname(key)).dev, sha256).record(key); } catch { /* The index is an optimization, never a prerequisite for a blob write. */ } } return true; } finally { rmSync(tmp, { force: true }); } } async exists(key: string): Promise { return existsSync(key); } async remove(key: string): Promise { rmSync(key, { force: true, recursive: key.endsWith('/') }); } async list(prefix: string): Promise { const out: string[] = []; const walk = (dir: string): void => { if (!existsSync(dir)) return; for (const name of readdirSync(dir, { withFileTypes: true })) { const child = join(dir, name.name); if (name.isDirectory()) walk(child); else if (!name.name.includes('.tmp.')) out.push(child); } }; walk(prefix.replace(/\/$/, '')); return out.sort(); } async size(key: string): Promise { if (!existsSync(key)) return null; return statSync(key).size; } async getRange(key: string, start: number, endInclusive: number): Promise { if (!existsSync(key)) return null; const total = statSync(key).size; const from = Math.max(0, start), to = Math.min(endInclusive, total - 1); if (to < from) return new Uint8Array(0); const out = new Uint8Array(to - from + 1); const fd = openSync(key, 'r'); let read = 0; try { while (read < out.length) { const n = readSync(fd, out, read, out.length - read, from + read); if (n === 0) break; read += n; } } finally { closeSync(fd); } return read === out.length ? out : out.subarray(0, read); } } /** In-memory backend — tests and hydration rehearsals; also the shape an R2/S3 adapter * implements (same interface, object keys instead of paths). */ export class MemoryBlobStore implements BlobStore { private blobs = new Map(); async get(key: string): Promise { const bytes = this.blobs.get(key); return bytes === undefined ? null : new Uint8Array(bytes); } async put(key: string, bytes: Uint8Array): Promise { this.blobs.set(key, new Uint8Array(bytes)); } async exists(key: string): Promise { return this.blobs.has(key); } async remove(key: string): Promise { if (key.endsWith('/')) { for (const k of [...this.blobs.keys()]) if (k.startsWith(key)) this.blobs.delete(k); } else this.blobs.delete(key); } async list(prefix: string): Promise { return [...this.blobs.keys()].filter((k) => k.startsWith(prefix.replace(/\/$/, ''))).sort(); } async size(key: string): Promise { return this.blobs.get(key)?.length ?? null; } async getRange(key: string, start: number, endInclusive: number): Promise { const bytes = this.blobs.get(key); if (bytes === undefined) return null; const from = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0; const to = Number.isFinite(endInclusive) ? Math.floor(endInclusive) : -1; return to < from ? new Uint8Array(0) : new Uint8Array(bytes.subarray(from, to + 1)); } } /** Content-address helper shared by byte-carrying packs: sha256 hex of the bytes. */ export function blobDigest(bytes: Uint8Array): string { return createHash('sha256').update(bytes).digest('hex'); } // Active-store scoping, the world-store.ts pattern exactly: default fs; a serverless entry // (or a test) swaps in its adapter for the scope of a request. let activeBlobStore: BlobStore = new FsBlobStore(); /** The active store; under a read-only request's refusing scope (request-scope.ts), one that refuses * to store or remove bytes before any reach it, as the log's appenders refuse (a git push's objects, * an upload's body), while reads pass. */ export function getActiveBlobStore(): BlobStore { return writesRefused() ? readOnlyBlobs(activeBlobStore) : activeBlobStore; } function readOnlyBlobs(store: BlobStore): BlobStore { return { get: (key) => store.get(key), exists: (key) => store.exists(key), list: (prefix) => store.list(prefix), size: (key) => store.size(key), ...(store.getRange ? { getRange: (key: string, start: number, endInclusive: number) => store.getRange!(key, start, endInclusive) } : {}), put: async () => { refuseReadOnlyWrite('blobs'); }, putStream: async () => { refuseReadOnlyWrite('blobs'); return false; }, remove: async () => { refuseReadOnlyWrite('blobs'); }, }; } export function setActiveBlobStore(store: BlobStore): BlobStore { const previous = activeBlobStore; activeBlobStore = store; return previous; } export async function withBlobStore(store: BlobStore, fn: () => Promise | T): Promise { const previous = setActiveBlobStore(store); try { return await fn(); } finally { setActiveBlobStore(previous); } }