Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190// Loro doc registry: opens each doc from IndexedDB (snapshot + pending// updates), persists local commits incrementally, and compacts once enough// updates pile up. Loro import is idempotent, so a crash between an append// and a compaction can at worst replay updates the snapshot already covers.
import { LoroDoc } from 'loro-crdt';import * as db from './db';import { bumpDocVersion } from './stores.svelte';import { tagDocWithDevice } from './identity';
export const WORKSPACE_DOC = 'workspace';export const ATTEMPTS_DOC = 'attempts';export const annDocId = (documentId: string) => `ann:${documentId}`;
const FLUSH_DELAY_MS = 400;const COMPACT_AFTER_UPDATES = 64;
interface OpenState { doc: LoroDoc; pending: Uint8Array[]; flushTimer: ReturnType<typeof setTimeout> | null; // Rows in doc_updates plus what's still buffered, to decide compaction. updateCount: number; lastSeq: number;}
const registry = new Map<string, Promise<OpenState>>();// Loaded docs, synchronously readable (pagehide handlers cannot await).const resolved = new Map<string, OpenState>();let lifecycleHooked = false;
export function openedDocs(): { docId: string; doc: LoroDoc }[] { return [...resolved.entries()].map(([docId, st]) => ({ docId, doc: st.doc }));}
// The sync engine registers here to learn about freshly persisted local// updates (callback registry rather than an import, to avoid a cycle).let onPersist: (() => void) | null = null;export function setOnPersist(cb: (() => void) | null): void { onPersist = cb;}
export async function openDoc(docId: string): Promise<LoroDoc> { return (await state(docId)).doc;}
function state(docId: string): Promise<OpenState> { let st = registry.get(docId); if (!st) { st = load(docId); registry.set(docId, st); } return st;}
async function load(docId: string): Promise<OpenState> { const doc = new LoroDoc(); const stored = await db.getDoc(docId); if (stored) doc.import(stored.snapshot); const updates = await db.updatesFor(docId); for (const u of updates) doc.import(u.bytes);
// Attribute this replica's changes to this device (stable peer id) and // record timestamps, so the history view can say what changed, when, and // where. Imported history keeps whatever peer ids it already carried. await tagDocWithDevice(doc);
const st: OpenState = { doc, pending: [], flushTimer: null, updateCount: updates.length, lastSeq: updates.reduce((max, u) => Math.max(max, u.seq ?? 0), 0), };
doc.subscribeLocalUpdates((bytes) => { st.pending.push(bytes); scheduleFlush(docId, st); }); doc.subscribe(() => bumpDocVersion(docId));
resolved.set(docId, st); hookLifecycle(); return st;}
function scheduleFlush(docId: string, st: OpenState): void { if (st.flushTimer) return; st.flushTimer = setTimeout(() => { flush(docId, st).catch((e) => { console.error('Persisting the workspace failed, retrying', e); if (st.pending.length) scheduleFlush(docId, st); }); }, FLUSH_DELAY_MS);}
async function flush(docId: string, st: OpenState): Promise<void> { if (st.flushTimer) { clearTimeout(st.flushTimer); st.flushTimer = null; } const batch = st.pending; if (!batch.length) return; st.pending = []; const savedAt = Date.now(); for (let i = 0; i < batch.length; i++) { try { st.lastSeq = await db.appendUpdate({ docId, bytes: batch[i], savedAt }); } catch (e) { // Persisting failed (quota, eviction). The updates that never landed go // back at the front, in order, so the next flush retries them instead of // dropping edits the user already saw applied. st.pending = [...batch.slice(i), ...st.pending]; throw e; } st.updateCount += 1; } if (st.updateCount >= COMPACT_AFTER_UPDATES) await compact(docId, st); onPersist?.();}
// Fold snapshot + updates into a fresh snapshot row. Guarded by a web lock so// two tabs never compact the same doc at once. Another tab may have appended a// row this tab's in-memory doc never imported; deleting it against a snapshot// that predates it would lose that edit. So, under the lock, re-read every// persisted update and fold it in first, and only delete rows up to the max// seq actually imported - never a sibling tab's un-imported tail.async function compact(docId: string, st: OpenState): Promise<void> { const run = async () => { const persisted = await db.updatesFor(docId); let coveredSeq = 0; for (const u of persisted) { st.doc.import(u.bytes); coveredSeq = Math.max(coveredSeq, u.seq ?? 0); } const snapshot = st.doc.export({ mode: 'snapshot' }); await db.replaceDoc({ docId, snapshot, savedAt: Date.now() }, coveredSeq); st.lastSeq = Math.max(st.lastSeq, coveredSeq); st.updateCount = 0; }; const locks = (navigator as { locks?: LockManager }).locks; if (locks?.request) await locks.request(`synapse:compact:${docId}`, run); else await run();}
// Remote updates (sync pulls, file imports) change the doc without going// through subscribeLocalUpdates, so they are persisted here explicitly -// otherwise a reload would lose them while the sync cursor has already moved// past them.export async function importRemote(docId: string, updates: Uint8Array[]): Promise<void> { if (!updates.length) return; const st = await state(docId); for (const bytes of updates) st.doc.import(bytes); const savedAt = Date.now(); for (const bytes of updates) { st.lastSeq = await db.appendUpdate({ docId, bytes, savedAt }); st.updateCount += 1; } if (st.updateCount >= COMPACT_AFTER_UPDATES) await compact(docId, st);}
// Force-write everything buffered (page hide, before sync, tests).export async function persistNow(docId?: string): Promise<void> { const entries = docId ? ([[docId, registry.get(docId)]] as const) : ([...registry.entries()] as const); for (const [id, pending] of entries) { if (!pending) continue; await flush(id, await pending); }}
function hookLifecycle(): void { if (lifecycleHooked || typeof window === 'undefined') return; lifecycleHooked = true; window.addEventListener('pagehide', () => { void persistNow(); }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') void persistNow(); });}
// Tests reset the fake IndexedDB between cases; the doc cache goes with it.export function resetLoroForTests(): void { registry.clear(); resolved.clear(); db.resetDbForTests();}