import { DurableObject } from "cloudflare:workers"; import * as decoding from "lib0/decoding"; import * as encoding from "lib0/encoding"; import * as syncProtocol from "y-protocols/sync"; import * as Y from "yjs"; import { HttpError } from "../errors"; import { canWrite, resolveEditorToken } from "./session"; import { applyCommitted, conflicts, filesMap, getMeta, MAX_ROOM_FILES, MAX_TEXT_BYTES, pendingChanges, readAtCommit, rebaseRoom, resolveConflict, setBase, setMeta, textOf, } from "./room-files"; import { agentClientId, awarenessFrame, base64, decodeAwareness, encodeAwareness, removalFrame, unbase64 } from "./room-awareness"; import { CLOSE_DOWNGRADED, CLOSE_REAUTH, EDITOR_WS_PROTOCOL, CLOSE_REVOKED, MESSAGE_AWARENESS, MESSAGE_SYNC, } from "~/lib/editor-protocol"; import type { ClientControl, RoomControl } from "~/lib/editor-protocol"; const MAX_SOCKETS = 50; const MAX_FRAME_BYTES = 1024 * 1024; const MAX_CACHED_AWARENESS = 1200; const RECHECK_MS = 60 * 1000; const AGENT_PRESENCE_MS = 30 * 1000; const STATUS_DEBOUNCE_MS = 300; const COMPACT_AFTER = 300; /** Per-socket state; it survives hibernation, so it must stay small (attachments are capped at 2 KiB). */ type Attachment = { token: string; userId: string; name: string; kind: "human" | "agent"; writable: boolean; checkedAt: number; expiresAt: number; aw?: string; awClient?: number; awClock?: number; }; export type RoomJoin = Omit & { repoId: string; branch: string; head: string; }; export type Participant = { id: string; name: string; kind: "human" | "agent"; path: string | null }; export type TextEdit = { from: number; to: number; insert: string }; export type ApplyResult = { ok: true; version: number; text: string } | { ok: false; error: "stale" | string; version: number; text: string }; /** * One room per (repo, branch). A single Y.Doc holds every open file as `file:` plus a `files` * metadata map. Updates are appended to SQLite and compacted, so the room survives eviction and * hibernation. Sockets carry their editor token and are re-authorized every minute. */ export class EditorRoom extends DurableObject { private doc = new Y.Doc(); private versions = new Map(); private seeding = new Map>(); private statusTimer: ReturnType | null = null; private sql: SqlStorage; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; ctx.blockConcurrencyWhile(async () => this.load()); } private load(): void { this.sql.exec(`CREATE TABLE IF NOT EXISTS updates (id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB NOT NULL); CREATE TABLE IF NOT EXISTS bases (path TEXT PRIMARY KEY, text TEXT); CREATE TABLE IF NOT EXISTS upstream (path TEXT PRIMARY KEY, text TEXT); CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS versions (path TEXT PRIMARY KEY, version INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS agents (name TEXT PRIMARY KEY, user_name TEXT NOT NULL, path TEXT, clock INTEGER NOT NULL, expires_at INTEGER NOT NULL);`); for (const row of this.sql.exec<{ data: ArrayBuffer }>("SELECT data FROM updates ORDER BY id")) { Y.applyUpdate(this.doc, new Uint8Array(row.data), "load"); } for (const row of this.sql.exec<{ path: string; version: number }>("SELECT path, version FROM versions")) { this.versions.set(row.path, row.version); } this.doc.on("update", (update: Uint8Array, origin: unknown) => this.onUpdate(update, origin)); this.doc.on("afterTransaction", (transaction: Y.Transaction) => this.bumpVersions(transaction)); } // --- Sockets ------------------------------------------------------------------------------------- /** The Worker authorizes the upgrade and passes the resolved session in `x-editor-join`. */ async fetch(request: Request): Promise { if (request.headers.get("upgrade") !== "websocket") return new Response("Expected websocket", { status: 426 }); const join: RoomJoin = JSON.parse(request.headers.get("x-editor-join") ?? "null"); if (!join) return new Response("Missing session", { status: 400 }); if (this.ctx.getWebSockets().length >= MAX_SOCKETS) return new Response("Room is full", { status: 503 }); await this.adopt(join.repoId, join.branch, join.head); const pair = new WebSocketPair(); const socket = pair[1]; this.ctx.acceptWebSocket(socket, [join.userId]); const attachment: Attachment = { token: join.token, userId: join.userId, name: join.name, kind: join.kind, writable: join.writable, checkedAt: Date.now(), expiresAt: join.expiresAt, }; socket.serializeAttachment(attachment); this.control(socket, { type: "welcome", head: getMeta(this.sql, "head") ?? join.head, branch: join.branch, writable: join.writable, user: join.name, clientLimit: MAX_SOCKETS, }); const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, MESSAGE_SYNC); syncProtocol.writeSyncStep1(encoder, this.doc); socket.send(encoding.toUint8Array(encoder)); for (const frame of this.presenceFrames(socket)) socket.send(frame); this.control(socket, this.statusMessage()); await this.ensureAlarm(); return new Response(null, { status: 101, webSocket: pair[0], headers: { "sec-websocket-protocol": EDITOR_WS_PROTOCOL }, }); } async webSocketMessage(socket: WebSocket, message: string | ArrayBuffer): Promise { let attachment = this.attachment(socket); if (!attachment) return socket.close(CLOSE_REAUTH, "Reconnect"); if (Date.now() - attachment.checkedAt > RECHECK_MS) { attachment = await this.reauthorize(socket, attachment); if (!attachment) return; } if (typeof message === "string") return this.onControl(socket, attachment, message); if (message.byteLength > MAX_FRAME_BYTES) return this.control(socket, { type: "error", message: "Update too large" }); const decoder = decoding.createDecoder(new Uint8Array(message)); const type = decoding.readVarUint(decoder); if (type === MESSAGE_SYNC) { const subtype = decoding.peekVarUint(decoder); if (subtype !== syncProtocol.messageYjsSyncStep1 && !attachment.writable) return; const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, MESSAGE_SYNC); syncProtocol.readSyncMessage(decoder, encoder, this.doc, socket); if (encoding.length(encoder) > 1) socket.send(encoding.toUint8Array(encoder)); } else if (type === MESSAGE_AWARENESS) { this.onAwareness(socket, attachment, decoding.readVarUint8Array(decoder)); } } async webSocketClose(socket: WebSocket): Promise { this.dropPresence(socket); socket.close(); } async webSocketError(socket: WebSocket): Promise { this.dropPresence(socket); } private async onControl(socket: WebSocket, attachment: Attachment, raw: string): Promise { let message: ClientControl; try { message = JSON.parse(raw); } catch { return; } if (message.type === "ping") return this.control(socket, { type: "pong" }); if (message.type === "open") { await this.seed(message.path).catch((error: unknown) => this.control(socket, { type: "error", path: message.path, message: errorText(error) }), ); return; } if (!attachment.writable) return this.control(socket, { type: "error", message: "This session is read-only" }); const files = filesMap(this.doc); if (message.type === "create") { if (files.size >= MAX_ROOM_FILES) return this.control(socket, { type: "error", message: "Too many open files" }); const existing = files.get(message.path); if (existing?.state === "deleted") files.set(message.path, { ...existing, state: "seeded" }); else if (!existing) { await this.seed(message.path).catch(() => undefined); if (!files.get(message.path)) files.set(message.path, { state: "created", kind: "text", size: 0 }); } } else if (message.type === "delete") { const existing = files.get(message.path); if (existing?.state === "created") { this.doc.transact(() => { files.delete(message.path); const text = textOf(this.doc, message.path); text.delete(0, text.length); }, socket); } else if (existing) files.set(message.path, { ...existing, state: "deleted" }); } else if (message.type === "resolve") { resolveConflict(this.doc, this.sql, message.path); this.scheduleStatus(); } } // --- Awareness ----------------------------------------------------------------------------------- /** Relays cursors; identity fields are overwritten with the authenticated user so nobody can impersonate. */ private onAwareness(socket: WebSocket, attachment: Attachment, update: Uint8Array): void { let entries; try { entries = decodeAwareness(update); } catch { return; } if (entries.length !== 1) return; const [entry] = entries; if (entry.state && typeof entry.state === "object") { const state = entry.state as Record; const user = typeof state.user === "object" && state.user ? (state.user as Record) : {}; state.user = { ...user, name: attachment.name, id: attachment.userId, kind: attachment.kind }; } const sanitized = encodeAwareness([entry]); const cached = sanitized.byteLength <= MAX_CACHED_AWARENESS && entry.state !== null; socket.serializeAttachment({ ...attachment, aw: cached ? base64(sanitized) : undefined, awClient: entry.clientId, awClock: entry.clock, } satisfies Attachment); this.broadcast(awarenessFrame(sanitized), socket); } private presenceFrames(except: WebSocket): Uint8Array[] { const frames: Uint8Array[] = []; for (const socket of this.ctx.getWebSockets()) { if (socket === except) continue; const attachment = this.attachment(socket); if (attachment?.aw) frames.push(awarenessFrame(unbase64(attachment.aw))); } for (const agent of this.liveAgents()) frames.push(awarenessFrame(this.agentUpdate(agent))); return frames; } private dropPresence(socket: WebSocket): void { const attachment = this.attachment(socket); if (attachment?.awClient !== undefined) { this.broadcast(removalFrame(attachment.awClient, attachment.awClock ?? 0), socket); } } // --- Document ------------------------------------------------------------------------------------ private onUpdate(update: Uint8Array, origin: unknown): void { if (origin === "load") return; this.sql.exec("INSERT INTO updates (data) VALUES (?)", update); const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, MESSAGE_SYNC); syncProtocol.writeUpdate(encoder, update); this.broadcast(encoding.toUint8Array(encoder), origin instanceof WebSocket ? origin : null); this.scheduleStatus(); } private bumpVersions(transaction: Y.Transaction): void { if (transaction.origin === "load") return; for (const [name, type] of this.doc.share) { if (!name.startsWith("file:") || !transaction.changed.has(type)) continue; const path = name.slice("file:".length); const version = (this.versions.get(path) ?? 0) + 1; this.versions.set(path, version); this.sql.exec( "INSERT INTO versions (path, version) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET version = excluded.version", path, version, ); } } /** Loads a file from the branch head into the shared doc once; concurrent openers wait on the same read. */ private async seed(path: string): Promise { if (filesMap(this.doc).has(path)) return; const pending = this.seeding.get(path); if (pending) return pending; const task = (async () => { if (filesMap(this.doc).size >= MAX_ROOM_FILES) throw new HttpError(429, "Too many open files in this room"); const repoId = getMeta(this.sql, "repoId"); const head = getMeta(this.sql, "head"); if (!repoId || !head) throw new HttpError(409, "Room not initialized"); const file = (await readAtCommit(repoId, head, [path])).get(path); if (!file) throw new HttpError(404, `${path} doesn't exist on this branch`); if (filesMap(this.doc).has(path)) return; this.doc.transact(() => { setBase(this.sql, path, file.text); if (file.text !== null) textOf(this.doc, path).insert(0, file.text); filesMap(this.doc).set(path, { state: "seeded", kind: file.kind, size: file.size }); }, "seed"); })(); this.seeding.set(path, task); try { await task; } finally { this.seeding.delete(path); } } /** Binds a fresh room to its repo and branch, and follows the branch head when it moved. */ private async adopt(repoId: string, branch: string, head: string): Promise { if (!getMeta(this.sql, "repoId")) { setMeta(this.sql, "repoId", repoId); setMeta(this.sql, "branch", branch); setMeta(this.sql, "head", head); return; } if (getMeta(this.sql, "repoId") !== repoId || getMeta(this.sql, "branch") !== branch) { throw new HttpError(409, "Room key mismatch"); } if (getMeta(this.sql, "head") !== head) { await rebaseRoom(this.doc, this.sql, repoId, head); this.scheduleStatus(); } } // --- RPC (callers authorize) --------------------------------------------------------------------- /** Called by the commit endpoint: what to commit, against which head, and what blocks it. */ async pending(repoId: string, branch: string, head: string) { await this.adopt(repoId, branch, head); return { head: getMeta(this.sql, "head") ?? head, changes: pendingChanges(this.doc, this.sql), conflicts: conflicts(this.doc) }; } async committed(input: { sha: string; branch: string; pullUrl: string | null; by: string; changes: Array<{ path: string; content: string | null }>; }): Promise { const sameBranch = input.branch === getMeta(this.sql, "branch"); applyCommitted(this.doc, this.sql, input.changes, sameBranch); if (sameBranch) setMeta(this.sql, "head", input.sha); this.broadcastControl({ type: "committed", sha: input.sha, branch: input.branch, pullUrl: input.pullUrl, by: input.by }); this.scheduleStatus(); } async snapshot(repoId: string, branch: string, head: string, path: string) { await this.adopt(repoId, branch, head); await this.seed(path); const meta = filesMap(this.doc).get(path) ?? null; return { path, text: meta && meta.kind !== "binary" && meta.kind !== "too-large" ? textOf(this.doc, path).toString() : null, kind: meta?.kind ?? null, state: meta?.state ?? null, version: this.versions.get(path) ?? 0, participants: this.participants(), }; } /** Applies agent edits as one Yjs transaction; offsets are UTF-16 against the text at `baseVersion`. */ async applyText( target: { repoId: string; branch: string; head: string; path: string }, edits: TextEdit[], origin: { agent: string; user: string; userId: string }, baseVersion?: number, ): Promise { await this.adopt(target.repoId, target.branch, target.head); const { path } = target; if (!filesMap(this.doc).has(path)) await this.seed(path).catch(() => undefined); if (!filesMap(this.doc).has(path)) filesMap(this.doc).set(path, { state: "created", kind: "text", size: 0 }); const meta = filesMap(this.doc).get(path); const text = textOf(this.doc, path); const version = this.versions.get(path) ?? 0; if (!meta || meta.kind !== "text" || meta.state === "deleted") { return { ok: false, error: `${path} isn't an editable text file`, version, text: text.toString() }; } if (baseVersion !== undefined && baseVersion !== version) { return { ok: false, error: "stale", version, text: text.toString() }; } const sorted = [...edits].sort((left, right) => right.from - left.from); let length = text.length; for (const edit of sorted) { if (edit.from < 0 || edit.to < edit.from || edit.to > length) { return { ok: false, error: "Edit range out of bounds", version, text: text.toString() }; } length += edit.insert.length - (edit.to - edit.from); } if (length > MAX_TEXT_BYTES) return { ok: false, error: "File too large", version, text: text.toString() }; this.doc.transact(() => { for (const edit of sorted) { if (edit.to > edit.from) text.delete(edit.from, edit.to - edit.from); if (edit.insert) text.insert(edit.from, edit.insert); } }, `agent:${origin.agent}`); const cursor = sorted.length ? sorted[sorted.length - 1].from + sorted[sorted.length - 1].insert.length : 0; this.touchAgent(origin.agent, origin.user, path, cursor); await this.ensureAlarm(); return { ok: true, version: this.versions.get(path) ?? version, text: text.toString() }; } async leave(agent: string): Promise { const row = this.sql.exec<{ clock: number }>("SELECT clock FROM agents WHERE name = ?", agent).toArray()[0]; if (!row) return; this.sql.exec("DELETE FROM agents WHERE name = ?", agent); this.broadcast(removalFrame(agentClientId(agent), row.clock), null); } // --- Agents -------------------------------------------------------------------------------------- private touchAgent(agent: string, user: string, path: string, cursor: number): void { const row = this.sql.exec<{ clock: number }>("SELECT clock FROM agents WHERE name = ?", agent).toArray()[0]; const clock = (row?.clock ?? 0) + 1; this.sql.exec( `INSERT INTO agents (name, user_name, path, clock, expires_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET user_name = excluded.user_name, path = excluded.path, clock = excluded.clock, expires_at = excluded.expires_at`, agent, user, path, clock, Date.now() + AGENT_PRESENCE_MS, ); this.broadcast(awarenessFrame(this.agentUpdate({ name: agent, user_name: user, path, clock, cursor })), null); } private liveAgents() { return this.sql .exec<{ name: string; user_name: string; path: string | null; clock: number }>( "SELECT name, user_name, path, clock FROM agents WHERE expires_at > ?", Date.now(), ) .toArray(); } private agentUpdate(agent: { name: string; user_name: string; path: string | null; clock: number; cursor?: number }): Uint8Array { const state = { user: { name: `${agent.name} (agent for ${agent.user_name})`, id: `agent:${agent.name}`, kind: "agent", color: "#a371f7" }, path: agent.path, selections: agent.cursor === undefined ? [] : [{ anchor: agent.cursor, head: agent.cursor }], }; return encodeAwareness([{ clientId: agentClientId(agent.name), clock: agent.clock, state }]); } private participants(): Array<{ id: string; name: string; kind: "human" | "agent"; path: string | null }> { const out = new Map(); for (const socket of this.ctx.getWebSockets()) { const attachment = this.attachment(socket); if (!attachment) continue; let path: string | null = null; if (attachment.aw) { const state = decodeAwareness(unbase64(attachment.aw))[0]?.state as { path?: unknown } | null; path = typeof state?.path === "string" ? state.path : null; } out.set(`${attachment.userId}:${path}`, { id: attachment.userId, name: attachment.name, kind: attachment.kind, path }); } for (const agent of this.liveAgents()) { out.set(`agent:${agent.name}`, { id: `agent:${agent.name}`, name: agent.name, kind: "agent", path: agent.path }); } return [...out.values()]; } // --- Authorization, alarms and fan-out ----------------------------------------------------------- private async reauthorize(socket: WebSocket, attachment: Attachment): Promise { if (attachment.expiresAt <= Date.now()) { socket.close(CLOSE_REAUTH, "Session token expired"); return null; } try { const session = await resolveEditorToken(attachment.token); if (session.repo.id !== getMeta(this.sql, "repoId") || session.revision.name !== getMeta(this.sql, "branch")) { socket.close(CLOSE_REVOKED, "Session no longer matches this room"); return null; } if (attachment.writable && !canWrite(session)) { socket.close(CLOSE_DOWNGRADED, "Write access was removed"); return null; } const next = { ...attachment, checkedAt: Date.now() }; socket.serializeAttachment(next); return next; } catch (error) { socket.close(CLOSE_REVOKED, error instanceof HttpError ? error.message.slice(0, 100) : "Access revoked"); return null; } } async alarm(): Promise { const sockets = this.ctx.getWebSockets(); await Promise.all( sockets.map(async (socket) => { const attachment = this.attachment(socket); if (attachment) await this.reauthorize(socket, attachment); }), ); for (const agent of this.sql .exec<{ name: string; clock: number }>("SELECT name, clock FROM agents WHERE expires_at <= ?", Date.now()) .toArray()) { this.sql.exec("DELETE FROM agents WHERE name = ?", agent.name); this.broadcast(removalFrame(agentClientId(agent.name), agent.clock), null); } this.compact(); await this.ensureAlarm(); } private async ensureAlarm(): Promise { const agents = this.sql.exec<{ count: number }>("SELECT COUNT(*) AS count FROM agents").one().count; if (this.ctx.getWebSockets().length === 0 && agents === 0) return; if ((await this.ctx.storage.getAlarm()) === null) await this.ctx.storage.setAlarm(Date.now() + RECHECK_MS); } private compact(): void { const count = this.sql.exec<{ count: number }>("SELECT COUNT(*) AS count FROM updates").one().count; if (count < COMPACT_AFTER) return; const state = Y.encodeStateAsUpdate(this.doc); this.ctx.storage.transactionSync(() => { this.sql.exec("DELETE FROM updates"); this.sql.exec("INSERT INTO updates (data) VALUES (?)", state); }); } private scheduleStatus(): void { if (this.statusTimer) return; this.statusTimer = setTimeout(() => { this.statusTimer = null; this.broadcastControl(this.statusMessage()); }, STATUS_DEBOUNCE_MS); } private statusMessage(): RoomControl { return { type: "status", head: getMeta(this.sql, "head") ?? "", changes: pendingChanges(this.doc, this.sql).map(({ path, status }) => ({ path, status })), conflicts: conflicts(this.doc), }; } private attachment(socket: WebSocket): Attachment | null { return socket.deserializeAttachment() as Attachment | null; } private control(socket: WebSocket, message: RoomControl): void { try { socket.send(JSON.stringify(message)); } catch { socket.close(); } } private broadcastControl(message: RoomControl): void { const payload = JSON.stringify(message); for (const socket of this.ctx.getWebSockets()) { try { socket.send(payload); } catch { continue; } } } private broadcast(frame: Uint8Array, except: WebSocket | null): void { for (const socket of this.ctx.getWebSockets()) { if (socket === except || socket.readyState !== WebSocket.OPEN) continue; try { socket.send(frame); } catch { continue; } } } } function errorText(error: unknown): string { return error instanceof Error ? error.message : "Couldn't open the file"; }