gitflarePublicPartly agent-ready50
cf-durable-whiteboard
Realtime collaborative whiteboard on Cloudflare Durable Objects: presence cursors, WebSocket hibernation, SQLite storage, undo, PNG export.
- LicenseApache-2.0
- LanguageTypeScript
- Last landed
6eb4fbdOct 20, 2026
Keep board zoom and pan stable across reloads
6eb4fbdimport { DurableObject } from "cloudflare:workers";import { applyOp, UndoStacks, MAX_OPS, type Shapes } from "./lib/ops";import { parseClientMessage, type Op, type Shape } from "./lib/validate";import { TokenBucket } from "./lib/ratelimit"; type Att = { userId: string; name: string; colour: string };const COLOURS = ["#ff6b6b", "#ffd166", "#06d6a0", "#4cc9f0", "#b794f6", "#ff9f1c", "#f15bb5", "#e9ecef"]; export class Board extends DurableObject<Env> { private buckets = new Map<WebSocket, { b: TokenBucket; strikes: number }>(); private undo = new UndoStacks(); constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS shapes(id TEXT PRIMARY KEY, kind TEXT, data TEXT, z INTEGER, author TEXT, updated_at INTEGER)`); ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS ops(seq INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT, op TEXT, inverse TEXT, at INTEGER)`); } private load(): Shapes { const m: Shapes = new Map(); for (const r of this.ctx.storage.sql.exec("SELECT id, data FROM shapes ORDER BY z")) m.set(r.id as string, JSON.parse(r.data as string)); return m; } private seq(): number { return (this.ctx.storage.sql.exec("SELECT COALESCE(MAX(seq),0) AS s FROM ops").one().s as number) ?? 0; } private persist(before: Shapes, after: Shapes, author: string) { const sql = this.ctx.storage.sql, now = Date.now(); for (const id of before.keys()) if (!after.has(id)) sql.exec("DELETE FROM shapes WHERE id=?", id); let z = 0; for (const s of after.values()) { if (before.get(s.id) !== s) sql.exec("INSERT OR REPLACE INTO shapes VALUES(?,?,?,?,?,?)", s.id, s.kind, JSON.stringify(s), z, author, now); z++; } } async fetch(req: Request): Promise<Response> { const url = new URL(req.url); if (url.pathname.endsWith("/info")) { const r = this.ctx.storage.sql.exec("SELECT COUNT(*) AS c, COALESCE(MAX(updated_at),0) AS u FROM shapes").one(); return Response.json({ shapes: r.c, lastUpdate: r.u }); } if (req.headers.get("Upgrade") !== "websocket") return new Response("Expected websocket", { status: 426 }); const pair = new WebSocketPair(); const [client, server] = Object.values(pair); const userId = crypto.randomUUID(); const att: Att = { userId, name: "Guest", colour: COLOURS[Math.floor(Math.random() * COLOURS.length)] }; this.ctx.acceptWebSocket(server); server.serializeAttachment(att); const peers = this.ctx.getWebSockets().filter((w) => w !== server).map((w) => w.deserializeAttachment() as Att); server.send(JSON.stringify({ type: "welcome", you: att, shapes: [...this.load().values()], peers, seq: this.seq() })); this.broadcast({ type: "peer-join", peer: att }, server); return new Response(null, { status: 101, webSocket: client }); } private broadcast(msg: unknown, except?: WebSocket) { const s = JSON.stringify(msg); for (const w of this.ctx.getWebSockets()) if (w !== except) { try { w.send(s); } catch {} } } private commit(userId: string, op: Op, inverse: Op | null, before: Shapes, after: Shapes) { this.persist(before, after, userId); const sql = this.ctx.storage.sql; const c = sql.exec("INSERT INTO ops(user_id, op, inverse, at) VALUES(?,?,?,?) RETURNING seq", userId, JSON.stringify(op), JSON.stringify(inverse), Date.now()).one(); sql.exec("DELETE FROM ops WHERE seq <= ?", (c.seq as number) - MAX_OPS); this.broadcast({ type: "op", seq: c.seq, op, by: userId }); } private run(userId: string, op: Op, record: boolean) { const before = this.load(), after = new Map(before); const inv = applyOp(after, op); if (!inv) return; if (record) this.undo.record(userId, { op, inverse: inv }); this.commit(userId, op, inv, before, after); } webSocketMessage(ws: WebSocket, data: string | ArrayBuffer) { let st = this.buckets.get(ws); if (!st) this.buckets.set(ws, (st = { b: new TokenBucket(60, 120), strikes: 0 })); if (!st.b.take()) { if (++st.strikes > 20) ws.close(1008, "rate limit"); return; } const att = ws.deserializeAttachment() as Att; const msg = typeof data === "string" ? parseClientMessage(data) : null; if (!msg) { if (++st.strikes > 20) ws.close(1008, "abuse"); else ws.send(JSON.stringify({ type: "error", message: "invalid message" })); return; } switch (msg.type) { case "hello": att.name = msg.name; ws.serializeAttachment(att); this.broadcast({ type: "peer-join", peer: att }, ws); break; case "cursor": this.broadcast({ type: "cursor", userId: att.userId, x: msg.x, y: msg.y }, ws); break; case "op": this.run(att.userId, msg.op, true); break; case "undo": case "redo": { const e = msg.type === "undo" ? this.undo.popUndo(att.userId) : this.undo.popRedo(att.userId); if (e) this.run(att.userId, e.op, false); break; } } } webSocketClose(ws: WebSocket, code: number) { this.buckets.delete(ws); const att = ws.deserializeAttachment() as Att | null; try { ws.close(code === 1005 ? 1000 : code); } catch {} if (att) this.broadcast({ type: "peer-leave", userId: att.userId }, ws); } webSocketError(ws: WebSocket) { this.webSocketClose(ws, 1011); }}