Something went wrong. Try again.
🌿 Collaborative wiki on ATProto forked from juprodh.me/lichen.wiki
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import { Awareness, applyAwarenessUpdate, removeAwarenessStates,} from "y-protocols/awareness";import * as Y from "yjs";import * as protocol from "../../shared/collab-protocol.ts";import { deleteDraft, getCurrentNoteContent, loadDraft, saveDraftState,} from "../db/queries/index.ts";
/** * In-memory registry of live collaborative documents, one Y.Doc per note that * currently has at least one editor connected. The server is a relay hub: it * applies every client's sync/awareness messages to its own Y.Doc and rebroadcasts * to peers, and batches the Y.Doc state to SQLite (the `drafts` table) so an * in-progress draft survives disconnects and appview restarts. * * This holds drafts only — never the canonical record. Saving goes through the * normal edit route (PDS first), after which `clearAfterSave` drops the draft. */
const PERSIST_DEBOUNCE_MS = 5000;const WS_OPEN = 1;
/** Minimal view of a Bun ServerWebSocket — identity-keyed, used to push frames. */interface CollabSocket { send(data: Uint8Array): unknown; readonly readyState: number;}
interface Conn { did: string; /** Awareness client ids announced over this socket, removed on disconnect. */ controlledIds: Set<number>;}
interface LiveDoc { noteAtUri: string; wikiAtUri: string; ydoc: Y.Doc; awareness: Awareness; conns: Map<CollabSocket, Conn>; persistTimer: ReturnType<typeof setTimeout> | null; lastModifierDid: string | null;}
const docs = new Map<string, LiveDoc>();
// --- Seed / persist (exported so the load/seed/persist logic is testable// without a socket) ---
/** * Populate a fresh Y.Doc for a note: load an existing draft if one is stored, * otherwise seed the "content" text from the note's last saved revision. * Both paths use a non-client origin so the registry's update handler does not * treat seeding as an edit to persist. */export function seedDoc(ydoc: Y.Doc, noteAtUri: string): void { const draft = loadDraft(noteAtUri); if (draft) { Y.applyUpdate(ydoc, draft.yjs_state, "load"); return; } const content = getCurrentNoteContent(noteAtUri); if (content) { ydoc.transact(() => { ydoc.getText("content").insert(0, content); }, "seed"); }}
/** Encode and store the current Y.Doc state to the drafts table. */export function persistDoc( ydoc: Y.Doc, noteAtUri: string, wikiAtUri: string, modifierDid: string | null,): void { saveDraftState( noteAtUri, wikiAtUri, Y.encodeStateAsUpdate(ydoc), modifierDid, );}
// --- Registry lifecycle ---
function getOrLoad(noteAtUri: string, wikiAtUri: string): LiveDoc { const existing = docs.get(noteAtUri); if (existing) return existing;
const ydoc = new Y.Doc(); const awareness = new Awareness(ydoc); awareness.setLocalState(null); // the server is a relay, not a participant
const live: LiveDoc = { noteAtUri, wikiAtUri, ydoc, awareness, conns: new Map(), persistTimer: null, lastModifierDid: null, };
// Seed before attaching handlers so the seed/load doesn't broadcast or persist. seedDoc(ydoc, noteAtUri);
ydoc.on("update", (update: Uint8Array, origin: unknown) => { broadcast(live, protocol.encodeUpdate(update)); if (origin && live.conns.has(origin as CollabSocket)) { live.lastModifierDid = live.conns.get(origin as CollabSocket)?.did ?? live.lastModifierDid; } schedulePersist(live); });
awareness.on( "update", ( changes: { added: number[]; updated: number[]; removed: number[] }, origin: unknown, ) => { const conn = origin ? live.conns.get(origin as CollabSocket) : undefined; if (conn) { for (const id of changes.added) conn.controlledIds.add(id); for (const id of changes.removed) conn.controlledIds.delete(id); } const changed = changes.added.concat(changes.updated, changes.removed); broadcast(live, protocol.encodeAwareness(awareness, changed)); }, );
docs.set(noteAtUri, live); return live;}
function broadcast(live: LiveDoc, frame: Uint8Array): void { for (const sock of live.conns.keys()) { if (sock.readyState !== WS_OPEN) continue; try { sock.send(frame); } catch { // A dead socket is reaped on its own close event; ignore send failures. } }}
function schedulePersist(live: LiveDoc): void { if (live.persistTimer) return; // batch: first edit opens a window, flush at its end live.persistTimer = setTimeout(() => { live.persistTimer = null; persistDoc(live.ydoc, live.noteAtUri, live.wikiAtUri, live.lastModifierDid); }, PERSIST_DEBOUNCE_MS);}
function dispose(live: LiveDoc): void { if (live.persistTimer) { clearTimeout(live.persistTimer); live.persistTimer = null; } live.awareness.destroy(); live.ydoc.destroy(); docs.delete(live.noteAtUri);}
// --- Connection handlers (called from the WebSocket route) ---
/** Register a socket, then send it sync step 1 and the current awareness states. */export function openConn( noteAtUri: string, wikiAtUri: string, sock: CollabSocket, did: string,): void { const live = getOrLoad(noteAtUri, wikiAtUri); live.conns.set(sock, { did, controlledIds: new Set() });
if (sock.readyState === WS_OPEN) { sock.send(protocol.encodeSyncStep1(live.ydoc)); const states = live.awareness.getStates(); if (states.size > 0) { sock.send(protocol.encodeAwareness(live.awareness, [...states.keys()])); } }}
/** Handle one inbound frame from a client socket. */export function recvMessage( noteAtUri: string, sock: CollabSocket, data: Uint8Array,): void { const live = docs.get(noteAtUri); if (!live) return;
const { type, decoder } = protocol.readFrameType(data); switch (type) { case protocol.MSG_SYNC: { const reply = protocol.readSyncFrame(decoder, live.ydoc, sock); if (reply && sock.readyState === WS_OPEN) sock.send(reply); break; } case protocol.MSG_AWARENESS: applyAwarenessUpdate( live.awareness, protocol.readAwarenessFrame(decoder), sock, ); break; case protocol.MSG_CONTROL: handleControl(live, protocol.readControlFrame(decoder)); break; }}
function handleControl(live: LiveDoc, msg: protocol.ControlMessage): void { // A save or discard ends the shared draft. Clear it, then tell ALL editors // (including the initiator) to reload to the saved note. Broadcasting back to // the initiator lets it navigate only once the server has confirmed the draft // was cleared — no navigate-before-flush race on the WS. if (msg.t === "saved" || msg.t === "discard") { const all = [...live.conns.keys()]; clearAfterSave(live.noteAtUri); const frame = protocol.encodeControl({ t: "reload" }); for (const peer of all) { if (peer.readyState !== WS_OPEN) continue; try { peer.send(frame); } catch {} } }}
/** Remove a socket; flush + dispose the doc once the last editor leaves. */export function closeConn(noteAtUri: string, sock: CollabSocket): void { const live = docs.get(noteAtUri); if (!live) return;
const conn = live.conns.get(sock); live.conns.delete(sock); if (conn && conn.controlledIds.size > 0) { // Broadcasts the removal to remaining peers so their cursors clear. removeAwarenessStates(live.awareness, [...conn.controlledIds], null); }
if (live.conns.size === 0) { if (live.persistTimer) { clearTimeout(live.persistTimer); live.persistTimer = null; persistDoc( live.ydoc, live.noteAtUri, live.wikiAtUri, live.lastModifierDid, ); } dispose(live); }}
/** Drop the draft (DB + memory) after a save or discard. */export function clearAfterSave(noteAtUri: string): void { const live = docs.get(noteAtUri); deleteDraft(noteAtUri); if (live) dispose(live);}