From 3268dcd7e18d089fe7aa4cbacb321bedca4aace9 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Sat, 5 Dec 2026 22:12:19 +0900 Subject: [PATCH] feat(web): scope cloud IndexedDB by account and load documents on demand - Give a cloud space with an account a database of its own for each canonical server origin and user. Local spaces keep the 0.27.5 name `local:${type}:${id}`. The canonical origin rejects a URL with a user name or password. - Keep `local_seq` acknowledgements in `peerClocks` for each account. The pushed watermark moves only across a gap-free run of acknowledgements. - Add `getTier1DocsRaw`, `getDocsByIdsRaw`, and `listDocIds`. Key cursors find the records. A cold read reads no other page frames and no blob bytes. Key cursors also read the stored times of all documents. A write of an unloaded page then sorts after its stored updates. - Add the `lazyTier1` mode to `openDesktopStore`, with `loadDocFrames`, `loadBlob`, and `listStoredDocIds`. These reads apply the changes that have not committed yet on top of the stored data. The storage reports each committed op in the `complete` event of its write transaction. - Add `createReplicatorLease`. It elects one replicator tab per database with the Web Locks API. Without that API, it uses a heartbeat lease on a `BroadcastChannel`, then a single tab. The lock holder answers lease probes and leads after the lease tab yields. A lease candidate withdraws for a lower tab ID. - Post a `changes` message with document and blob IDs after each committed write, compaction, blob change, and watermark move. Add `deleteBlob`. --- packages/frontend/hosts/web/desktop/start.js | 187 ++- .../frontend/hosts/web/src/idb-storage.js | 962 +++++++++++++++- .../frontend/hosts/web/tests/desktop.test.mjs | 501 ++++++++ .../hosts/web/tests/idb-storage.test.mjs | 1023 +++++++++++++++++ 4 files changed, 2617 insertions(+), 56 deletions(-) diff --git a/packages/frontend/hosts/web/desktop/start.js b/packages/frontend/hosts/web/desktop/start.js index 56a33ea416..9ed28bb9e1 100644 --- a/packages/frontend/hosts/web/desktop/start.js +++ b/packages/frontend/hosts/web/desktop/start.js @@ -51,6 +51,14 @@ async function fetchFont(url) { * document. Returns `null` when the browser gives no IndexedDB, so the desktop * runs in memory only. * + * With `lazyTier1`, the store reads at startup only the frames that the first + * screen needs (`getTier1DocsRaw`): the workspace root, the `db$*` and + * `userdata$*` tables, and the documents of `initialDocIdsByWorkspace`. It + * reads no media at startup. `loadDocFrames`, `loadBlob`, and + * `listStoredDocIds` read the other documents and media on demand, in both + * modes. They apply the changes that this store holds and that have not + * committed yet on top of the stored data, so a read never loses a change. + * * The media, updates, and deletions queued in one task go to IndexedDB in one * transaction per workspace that issues every request at once * (`writeDocOpsNow`), so media and the document updates that refer to it @@ -69,6 +77,8 @@ async function fetchFont(url) { * now?: () => number, * setTimeout?: typeof setTimeout, * clearTimeout?: typeof clearTimeout, + * lazyTier1?: boolean, + * initialDocIdsByWorkspace?: Record, * }} [env] */ export async function openDesktopStore(workspaceIds, env = globalThis) { @@ -77,6 +87,15 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { /** @type {() => void} */ let markSeeded = () => {}; /** @typedef {{ docId: string, bin: Uint8Array } | { docId: string, delete: true }} DocOp */ + /** @typedef {{ blobKey: string, data: Uint8Array }} BlobOp */ + /** + * A change of a workspace from the call that queued it until it and every + * earlier change commit. `committed` turns true in the `complete` event of + * the transaction that writes the change, or when a later committed change + * replaces it. + * + * @typedef {{ op: DocOp | BlobOp, committed: boolean }} PendingChange + */ /** * @typedef {{ * id: string, @@ -84,7 +103,8 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { * opening: Promise | null | undefined, * cancelOpen?: () => void, * ops: DocOp[], - * blobs: Map, + * blobs: Map, + * pending: PendingChange[], * deleted: boolean, * }} WorkspaceSlot */ @@ -113,11 +133,13 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { onDocWriteFailure: () => { if (isCurrent(slot)) markSeeded(); }, + onDocOpsCommitted: ops => commitPending(slot, ops), }), // Undefined before the first open and null after the open succeeds. opening: undefined, ops: [], blobs: new Map(), + pending: [], deleted: false, }; slots.set(id, slot); @@ -157,17 +179,22 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { const frames = new Map(); /** @type {Map>} */ const initialBlobs = new Map(); + const lazy = env.lazyTier1 === true; try { for (const id of new Set(workspaceIds)) { const slot = getSlot(id); await openSlot(slot); const { storage } = slot; - const docs = await storage.getAllDocsRaw(); + const docs = lazy + ? await storage.getTier1DocsRaw({ + includeDocIds: env.initialDocIdsByWorkspace?.[id] ?? [], + }) + : await storage.getAllDocsRaw(); frames.set(id, docs); // No document of an empty workspace refers to the stored media. initialBlobs.set( id, - docs.size ? await storage.getAllBlobsRaw() : new Map() + !lazy && docs.size ? await storage.getAllBlobsRaw() : new Map() ); } } catch (error) { @@ -218,9 +245,90 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { const enqueue = (workspaceId, op) => { const slot = getSlot(workspaceId); slot.ops.push(op); + slot.pending.push({ op, committed: false }); changed(slot); }; + /** + * Marks the changes of `ops` committed, with each earlier change that a + * committed deletion of its document or a committed blob of its key + * replaces, and drops the committed changes at the start of the list. The + * storage calls it in the `complete` event of the write transaction, so a + * read transaction that completes later sees each change that it marks. + * + * @param {WorkspaceSlot} slot + * @param {Array} ops + */ + const commitPending = (slot, ops) => { + const sent = new Set(ops); + for (const [index, change] of slot.pending.entries()) { + if (!sent.has(change.op)) continue; + change.committed = true; + const { op } = change; + if (!('delete' in op) && !('blobKey' in op)) continue; + for (const earlier of slot.pending.slice(0, index)) { + if ( + 'blobKey' in op + ? 'blobKey' in earlier.op && earlier.op.blobKey === op.blobKey + : 'docId' in earlier.op && earlier.op.docId === op.docId + ) { + earlier.committed = true; + } + } + } + let start = 0; + while (slot.pending[start]?.committed) start += 1; + slot.pending.splice(0, start); + }; + + /** + * Reads stored data with `read` and returns it with the changes that were + * pending when the read completed. A write transaction that completes + * before the read transaction completes started before it, so its changes + * are in the stored data and are marked committed. + * + * A workspace that this store has not opened has no data to read. + * + * @template T + * @param {string} workspaceId + * @param {(storage: WorkspaceSlot['storage']) => Promise} read + * @returns {Promise<{ stored: T | null, pending: PendingChange[] }>} + */ + const readWithPending = async (workspaceId, read) => { + const slot = slots.get(workspaceId); + if (!slot) return { stored: null, pending: [] }; + const stored = await read(slot.storage); + return { stored, pending: slot.pending.slice() }; + }; + + /** + * Applies the pending changes of a document to its stored frames. Without + * an uncommitted deletion, the uncommitted updates follow the stored + * frames. A failed deletion is written again with the updates that + * committed after it, so from the first uncommitted deletion on, every + * change of the document applies to empty frames. + * + * @param {PendingChange[]} pending + * @param {string} docId + * @param {Uint8Array[]} stored + * @returns {Uint8Array[]} + */ + const applyPending = (pending, docId, stored) => { + const changes = pending.filter( + change => 'docId' in change.op && change.op.docId === docId + ); + const start = changes.findIndex( + change => !change.committed && 'delete' in change.op + ); + let frames = start < 0 ? [...stored] : []; + for (const [index, { op, committed }] of changes.entries()) { + if (start < 0 ? committed : index < start) continue; + if ('delete' in op) frames = []; + else if ('bin' in op) frames.push(op.bin); + } + return frames; + }; + const finishSeed = id => { if (unseeded.delete(id) && !unseeded.size) markSeeded(); }; @@ -251,10 +359,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { ready.delete(slot); if (!isCurrent(slot)) continue; - const ops = [ - ...[...slot.blobs].map(([blobKey, data]) => ({ blobKey, data })), - ...slot.ops, - ]; + const ops = [...slot.blobs.values(), ...slot.ops]; slot.blobs.clear(); slot.ops.length = 0; const { id, storage } = slot; @@ -347,6 +452,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { ready.delete(slot); slot.ops.length = 0; slot.blobs.clear(); + slot.pending.length = 0; slot.storage.close(); slot.cancelOpen?.(); slot.cancelOpen = undefined; @@ -371,9 +477,74 @@ export async function openDesktopStore(workspaceIds, env = globalThis) { }, putBlob(workspaceId, blobId, bytes) { const slot = getSlot(workspaceId); - slot.blobs.set(blobId, bytes); + const replaced = slot.blobs.get(blobId); + const op = { blobKey: blobId, data: bytes }; + slot.blobs.set(blobId, op); + // The replaced bytes were never sent, so they never commit. + const stale = slot.pending.find(change => change.op === replaced); + if (stale) stale.committed = true; + slot.pending.push({ op, committed: false }); changed(slot); }, + /** + * Reads the frames of one document: the stored frames with the changes + * that have not committed (`applyPending`). + * + * @param {string} workspaceId + * @param {string} docId + * @returns {Promise} + */ + async loadDocFrames(workspaceId, docId) { + const { stored, pending } = await readWithPending(workspaceId, storage => + storage.getDocsByIdsRaw([docId]) + ); + return applyPending(pending, docId, stored?.get(docId) ?? []); + }, + /** + * Reads the bytes of one blob: the newest uncommitted bytes, else the + * stored bytes, else `null` for a missing or deleted blob. + * + * @param {string} workspaceId + * @param {string} blobId + * @returns {Promise} + */ + async loadBlob(workspaceId, blobId) { + const { stored, pending } = await readWithPending(workspaceId, storage => + storage.getBlob(blobId) + ); + const change = pending.findLast( + ({ op, committed }) => + !committed && 'blobKey' in op && op.blobKey === blobId + ); + if (change && 'data' in change.op) return change.op.data; + return stored?.data ?? null; + }, + /** + * Lists the documents of a workspace from stored keys, with the changes + * that have not committed (`applyPending`). It reads no frames. + * + * @param {string} workspaceId + * @returns {Promise} + */ + async listStoredDocIds(workspaceId) { + const { stored, pending } = await readWithPending(workspaceId, storage => + storage.listDocIds() + ); + const storedIds = new Set(stored); + const ids = new Set(stored); + const marker = [new Uint8Array(0)]; + for (const { op } of pending) { + if (!('docId' in op)) continue; + const frames = applyPending( + pending, + op.docId, + storedIds.has(op.docId) ? marker : [] + ); + if (frames.length) ids.add(op.docId); + else ids.delete(op.docId); + } + return [...ids]; + }, retryBlobWrites() { void flush(); }, diff --git a/packages/frontend/hosts/web/src/idb-storage.js b/packages/frontend/hosts/web/src/idb-storage.js index aa922c6531..698fd2e236 100644 --- a/packages/frontend/hosts/web/src/idb-storage.js +++ b/packages/frontend/hosts/web/src/idb-storage.js @@ -9,6 +9,9 @@ * `localStorage['affine-local-workspace']` semantics match AFFiNE 0.27.5 * (`packages/common/nbstore/src/impls/idb/**` and * `packages/frontend/core/src/modules/workspace-engine/impls/local.ts`). + * A cloud space with an account adds the account scope to the database name + * (`formatIdbName`), so each server origin and user gets a database of its + * own. */ export const IDB_SCHEMA_VERSION = 3; @@ -33,11 +36,22 @@ export const LOCAL_WORKSPACE_CHANGED_CHANNEL = 'affine-local-workspace-changed'; export const V1_DOC_DB_NAME = 'affine-local'; export const V1_CONST_TIMESTAMP = new Date(1893456000000); +/** + * The signed-in account of a cloud space: the server origin and the user ID. + * + * @typedef {Object} AccountScope + * @property {string} origin + * @property {string} userId + */ + /** * @typedef {Object} IdbSpaceOptions * @property {string} flavour * @property {'workspace' | 'userspace'} type * @property {string} id + * @property {AccountScope} [account] The account of a cloud space. A cloud + * space with an account gets a database of its own for each server origin + * and user. Local spaces have no account. */ /** @@ -63,7 +77,62 @@ export const V1_CONST_TIMESTAMP = new Date(1893456000000); */ /** - * Formats the canonical 0.27.5 IndexedDB database name. + * IDs of what one committed transaction changed, as the `changes` message on + * the `idb:${dbName}` channel carries them. + * + * @typedef {Object} StorageChanges + * @property {string[]} docsUpdated + * @property {string[]} docsDeleted + * @property {string[]} blobsUpdated + * @property {string[]} blobsDeleted + * @property {boolean} watermarksUpdated + */ + +/** + * Returns the canonical origin of a server URL: the lower-case scheme and + * host, and the port only when it is not the default port of the scheme. The + * path, query, and fragment do not change the result. A URL with a user name + * or password is not a server origin. + * + * @param {string} origin An `http:` or `https:` URL. + * @returns {string} + */ +export function canonicalizeOrigin(origin) { + let url; + try { + url = new URL(String(origin)); + } catch { + throw new TypeError(`Server origin ${origin} is not a valid URL`); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new TypeError(`Server origin ${origin} must use http or https`); + } + if (url.username || url.password) { + throw new TypeError('A server origin must not contain credentials'); + } + return url.origin; +} + +/** + * Formats the key of an account: the canonical server origin and the user + * ID, each URI-encoded and joined with `@`. Two accounts have the same key + * only when they have the same canonical origin and the same user ID. + * + * @param {AccountScope} account + * @returns {string} + */ +export function formatAccountScope(account) { + if (!account || typeof account.userId !== 'string' || !account.userId) { + throw new TypeError('An account scope needs a user ID'); + } + return `${encodeURIComponent(canonicalizeOrigin(account.origin))}@${encodeURIComponent(account.userId)}`; +} + +/** + * Formats the IndexedDB database name of a space. Without an account it is + * the 0.27.5 name `${flavour}:${type}:${id}`. A cloud space with an account + * gets `${flavour}@${accountScope}:${type}:${id}`, so two servers or two + * users never share a database. * * @param {IdbSpaceOptions} opts * @returns {string} @@ -72,7 +141,24 @@ export function formatIdbName(opts) { if (!opts || !opts.flavour || !opts.type || !opts.id) { throw new TypeError('flavour, type, and id are required for IDB name'); } - return `${opts.flavour}:${opts.type}:${opts.id}`; + if (!opts.account) { + return `${opts.flavour}:${opts.type}:${opts.id}`; + } + if (opts.flavour === 'local') { + throw new TypeError('A local space has no account scope'); + } + return `${opts.flavour}@${formatAccountScope(opts.account)}:${opts.type}:${opts.id}`; +} + +/** + * Formats the name of the Web Locks API lock and the fallback + * `BroadcastChannel` that elect the replicator tab of a database. + * + * @param {string} dbName + * @returns {string} + */ +export function formatReplicatorLockName(dbName) { + return `affine:replicator:${dbName}`; } /** @@ -395,6 +481,93 @@ function docKeys(docId) { return globalThis.IDBKeyRange.bound([docId], [docId, []]); } +/** + * Document ID prefixes of the tables that the first screen needs: the + * workspace tables (`db$*`) and the user tables (`userdata$*`). + */ +const TABLE_DOC_PREFIXES = Object.freeze(['db$', 'userdata$']); + +/** The account table of a userspace that holds the editor settings. */ +const EDITOR_SETTING_DOC_ID = 'editorSetting'; + +/** Peer name prefix of the `peerClocks` records that keep `local_seq` acknowledgements. */ +const LOCAL_SEQ_PEER_PREFIX = 'local-seq:'; + +/** + * Builds the frames of each document from stored `clocks`, `snapshots`, and + * `updates` records: the snapshot first, then the non-empty updates in time + * order. Keeps only the documents with a positive time and calls `note` with + * the time of each record. + * + * @param {Array<{ docId: string, timestamp: unknown }>} clocks + * @param {Array<{ docId: string, updatedAt: unknown, bin?: Uint8Array }>} snapshots + * @param {Array<{ docId: string, createdAt: unknown, bin?: Uint8Array }>} updates + * Updates in primary key order. + * @param {(docId: string, ms: number) => void} note + * @returns {Map} + */ +function assembleDocFrames(clocks, snapshots, updates, note) { + /** @type {Map} */ + const docs = new Map(); + /** @param {string} docId @param {ArrayBuffer | ArrayBufferView | null | undefined} bin */ + function appendFrame(docId, bin) { + if (!bin?.byteLength) return; + const frame = + bin instanceof Uint8Array + ? bin + : ArrayBuffer.isView(bin) + ? new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength) + : new Uint8Array(bin); + const frames = docs.get(docId); + if (frames) frames.push(frame); + else docs.set(docId, [frame]); + } + + const positiveDocs = new Set(); + /** @param {string} docId @param {number} ms */ + function noteTime(docId, ms) { + note(docId, ms); + if (typeof docId === 'string' && Number.isFinite(ms) && ms > 0) { + positiveDocs.add(docId); + } + } + + for (const clock of clocks) { + noteTime( + clock.docId, + toDate(/** @type {Date} */ (clock.timestamp)).getTime() + ); + } + for (const snapshot of snapshots) { + noteTime( + snapshot.docId, + toDate(/** @type {Date} */ (snapshot.updatedAt)).getTime() + ); + appendFrame(snapshot.docId, snapshot.bin); + } + /** @type {Map>} */ + const updatesByDoc = new Map(); + for (const update of updates) { + const ms = toDate(/** @type {Date} */ (update.createdAt)).getTime(); + noteTime(update.docId, ms); + if (!update.bin?.byteLength) continue; + const frames = updatesByDoc.get(update.docId); + const entry = { ms, bin: update.bin }; + if (frames) frames.push(entry); + else updatesByDoc.set(update.docId, [entry]); + } + // Updates arrive in primary key order. A stable sort keeps that order + // when a numeric key and a Date key have the same time in milliseconds. + for (const [docId, frames] of updatesByDoc) { + frames.sort((a, b) => a.ms - b.ms); + for (const { bin } of frames) appendFrame(docId, bin); + } + for (const docId of docs.keys()) { + if (!positiveDocs.has(docId)) docs.delete(docId); + } + return docs; +} + /** * Resolves when an IndexedDB transaction commits, or rejects when it aborts. * @@ -520,6 +693,7 @@ function bytesEqual(a, b) { * setTimeout?: typeof globalThis.setTimeout, * clearTimeout?: typeof globalThis.clearTimeout, * onDocWriteFailure?: (error: Error) => void, + * onDocOpsCommitted?: (ops: Array<{ docId: string, bin: Uint8Array } | { docId: string, delete: true } | { blobKey: string, data: Uint8Array }>) => void, * }} options */ export function createIdbWorkspaceStorage(options) { @@ -546,6 +720,8 @@ export function createIdbWorkspaceStorage(options) { const updateListeners = new Set(); /** @type {Set<(docId: string) => void>} */ const deleteListeners = new Set(); + /** @type {Set<(changes: StorageChanges) => void>} */ + const changeListeners = new Set(); /** * Newest time (ms) that a connection of this page read or wrote for each * document of the database, shared by every storage object of `dbName`. @@ -597,6 +773,57 @@ export function createIdbWorkspaceStorage(options) { noteClock(docId, ms); } } + } else if (data.type === 'changes') { + /** @param {unknown} list */ + const ids = list => + Array.isArray(list) ? list.filter(id => typeof id === 'string') : []; + /** @type {StorageChanges} */ + const changes = { + docsUpdated: ids(data.docsUpdated), + docsDeleted: ids(data.docsDeleted), + blobsUpdated: ids(data.blobsUpdated), + blobsDeleted: ids(data.blobsDeleted), + watermarksUpdated: data.watermarksUpdated === true, + }; + for (const listener of changeListeners) { + try { + listener(changes); + } catch (error) { + console.error('A storage change listener failed', error); + } + } + } + } + + /** + * Tells the other connections of the database which documents, blobs, and + * watermarks a committed transaction changed. The message holds IDs only, + * never frames or blob bytes. Readers load the changed data on demand. + * + * @param {Partial} changes + */ + function postChanges(changes) { + /** @type {StorageChanges} */ + const message = { + docsUpdated: [...new Set(changes.docsUpdated ?? [])], + docsDeleted: [...new Set(changes.docsDeleted ?? [])], + blobsUpdated: [...new Set(changes.blobsUpdated ?? [])], + blobsDeleted: [...new Set(changes.blobsDeleted ?? [])], + watermarksUpdated: changes.watermarksUpdated === true, + }; + if ( + !message.docsUpdated.length && + !message.docsDeleted.length && + !message.blobsUpdated.length && + !message.blobsDeleted.length && + !message.watermarksUpdated + ) { + return; + } + try { + channel?.postMessage({ type: 'changes', ...message }); + } catch { + // Broadcast errors must not fail a committed transaction. } } @@ -852,6 +1079,7 @@ export function createIdbWorkspaceStorage(options) { } } + postChanges({ docsUpdated: committed.map(({ update }) => update.docId) }); return committed.map(({ update, timestamp }) => ({ docId: update.docId, timestamp, @@ -873,7 +1101,8 @@ export function createIdbWorkspaceStorage(options) { * reads before a write again), the times it wrote, and the times that * other connections post to the `BroadcastChannel` after their writes * commit. The clock of the document moves to that time, and the object - * posts it. A delete removes the stored updates, snapshot, and clock of its + * posts it. A delete keeps the known time, so an update after it still + * sorts after the old updates. A delete removes the stored updates, snapshot, and clock of its * document. A blob op stores the blob record and its bytes, so a blob and * the document updates that refer to it commit or roll back together. * @@ -890,6 +1119,11 @@ export function createIdbWorkspaceStorage(options) { * starts no transaction until a call with a delete or an explicit retry * (`retryPausedWrites`) writes all of them in one transaction. * + * In the `complete` event of each transaction, before the returned promise + * settles, the object calls `options.onDocOpsCommitted` with the op objects + * that the transaction wrote (the objects of the call, or of an earlier + * call when it writes them again). + * * @param {DocOp[]} ops * @returns {Promise} Resolves when each op or its replacement commits. * Rejects if storage runs out of space, at once while the @@ -941,7 +1175,21 @@ export function createIdbWorkspaceStorage(options) { /** @type {Promise} */ let committed; try { - committed = transactionDone(beginDocWrite(ops, written)); + const tx = beginDocWrite(ops, written); + committed = new Promise((resolve, reject) => { + // Report the ops in the `complete` event itself, before any read + // transaction that started after this one can complete. + tx.oncomplete = () => { + try { + options.onDocOpsCommitted?.(ops); + } catch (error) { + console.error('A commit listener failed', error); + } + resolve(); + }; + tx.onabort = () => + reject(tx.error || new Error('IndexedDB transaction aborted')); + }); } catch (error) { committed = Promise.reject(error); } @@ -957,6 +1205,13 @@ export function createIdbWorkspaceStorage(options) { // Broadcast errors must not cause committed writes to be retried. } } + postChanges({ + docsUpdated: ops.flatMap(op => ('bin' in op ? [op.docId] : [])), + docsDeleted: ops.flatMap(op => ('delete' in op ? [op.docId] : [])), + blobsUpdated: ops.flatMap(op => + 'blobKey' in op ? [op.blobKey] : [] + ), + }); for (const { resolve } of results) resolve(); settleDocWrites(); }, @@ -1438,6 +1693,7 @@ export function createIdbWorkspaceStorage(options) { // Broadcast errors must not fail committed initialization. } } + postChanges({ docsUpdated: [update.docId] }); } return outcome; } @@ -1502,8 +1758,7 @@ export function createIdbWorkspaceStorage(options) { */ async function getAllDocsRaw() { const conn = await openIfExists(); - const docs = new Map(); - if (!conn) return docs; + if (!conn) return new Map(); const tx = conn.transaction(['clocks', 'snapshots', 'updates'], 'readonly'); const [clocks, snapshots, updates] = await Promise.all([ @@ -1512,59 +1767,214 @@ export function createIdbWorkspaceStorage(options) { requestToPromise(tx.objectStore('updates').getAll()), transactionDone(tx), ]); + return assembleDocFrames(clocks, snapshots, updates, noteClock); + } - /** @param {string} docId @param {ArrayBuffer | ArrayBufferView | null} bin */ - function appendFrame(docId, bin) { - if (!bin?.byteLength) return; - const frame = - bin instanceof Uint8Array - ? bin - : ArrayBuffer.isView(bin) - ? new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength) - : new Uint8Array(bin); - const frames = docs.get(docId); - if (frames) frames.push(frame); - else docs.set(docId, [frame]); + /** + * Reads the frames of the documents in `docIds` and of the documents whose + * ID starts with a prefix in `prefixes`, in one read-only transaction. Key + * cursors find the stored records, and the transaction reads the value of + * those records only, so the frames of other documents stay on disk. + * Each read document gets a known time, 0 when nothing is stored for it. + * + * With `prefixes`, the transaction also reads the newest stored time of + * every document without frames: the `clocks` records (a document ID and + * a time), the `updatedAt` index keys of `snapshots`, and the newest + * `updates` key of each document. Then each later write of a document that + * this read did not load still gets a time after its stored times, as + * after `getAllDocsRaw`. + * + * @param {Iterable} docIds + * @param {readonly string[]} [prefixes] + * @returns {Promise>} + */ + async function readDocFramesByKey(docIds, prefixes = []) { + const conn = await openIfExists(); + if (!conn) return new Map(); + const tx = conn.transaction(['clocks', 'snapshots', 'updates'], 'readonly'); + const done = transactionDone(tx); + const clocksStore = tx.objectStore('clocks'); + const snapshotsStore = tx.objectStore('snapshots'); + const updatesStore = tx.objectStore('updates'); + const KeyRange = globalThis.IDBKeyRange; + /** @type {Map} */ + const clocks = new Map(); + /** @type {Map} */ + const snapshots = new Map(); + /** @type {Map} */ + const updates = new Map(); + /** @type {Set} */ + const seen = new Set(); + const readAllClocks = prefixes.length > 0; + if (readAllClocks) { + const all = clocksStore.getAll(); + all.onsuccess = () => { + for (const clock of all.result) clocks.set(clock.docId, clock); + }; + // A connection with a slow clock can put a clock below a stored + // update or snapshot time. Key cursors read those times too, without + // frames: the `updatedAt` index of `snapshots`, and the newest + // `[docId, createdAt]` key of each document in `updates`. + const snapshotTimes = snapshotsStore.index('updatedAt').openKeyCursor(); + snapshotTimes.onsuccess = () => { + const current = snapshotTimes.result; + if (!current) return; + const ms = toDate(/** @type {Date} */ (current.key)).getTime(); + noteClock(String(current.primaryKey), ms); + current.continue(); + }; + const updateTimes = updatesStore.openKeyCursor(null, 'prev'); + updateTimes.onsuccess = () => { + const current = updateTimes.result; + if (!current) return; + const [docId, createdAt] = /** @type {[string, Date | number]} */ ( + current.primaryKey + ); + noteClock(docId, toDate(createdAt).getTime()); + // `[docId]` sorts below every key of `docId`, so the cursor moves + // to the newest key of the document before it. + current.continue([docId]); + }; } - const positiveDocs = new Set(); - /** @param {string} docId @param {number} ms */ - function noteTime(docId, ms) { - noteClock(docId, ms); - if (typeof docId === 'string' && Number.isFinite(ms) && ms > 0) { - positiveDocs.add(docId); + /** @param {string} docId */ + const readDoc = docId => { + if (seen.has(docId)) return; + seen.add(docId); + if (!readAllClocks) { + const clock = clocksStore.get(docId); + clock.onsuccess = () => { + if (clock.result) clocks.set(docId, clock.result); + }; } - } + const snapshot = snapshotsStore.get(docId); + snapshot.onsuccess = () => { + if (snapshot.result) snapshots.set(docId, snapshot.result); + }; + }; + /** + * Reads each update in `range` in key order, and the clock and snapshot + * of its document. + * + * @param {IDBKeyRange} range + */ + const readUpdates = range => { + const cursor = updatesStore.openKeyCursor(range); + cursor.onsuccess = () => { + const current = cursor.result; + if (!current) return; + const key = /** @type {[string, Date | number]} */ (current.primaryKey); + readDoc(key[0]); + const list = updates.get(key[0]) ?? []; + updates.set(key[0], list); + const index = list.push(null) - 1; + const update = updatesStore.get(key); + update.onsuccess = () => { + list[index] = update.result; + }; + current.continue(); + }; + }; - for (const clock of clocks) { - noteTime(clock.docId, toDate(clock.timestamp).getTime()); + for (const docId of new Set(docIds)) { + if (!docId) continue; + // A prefix range below reads a document with that prefix. + if (prefixes.some(prefix => docId.startsWith(prefix))) continue; + readDoc(docId); + readUpdates(docKeys(docId)); } - for (const snapshot of snapshots) { - noteTime(snapshot.docId, toDate(snapshot.updatedAt).getTime()); - appendFrame(snapshot.docId, snapshot.bin); + for (const prefix of prefixes) { + const upper = `${prefix}\uffff`; + const snapshotKeys = snapshotsStore.openKeyCursor( + KeyRange.bound(prefix, upper) + ); + snapshotKeys.onsuccess = () => { + const current = snapshotKeys.result; + if (!current) return; + readDoc(String(current.primaryKey)); + current.continue(); + }; + // `[prefix]` sorts below every `[docId, createdAt]` key whose `docId` + // starts with `prefix`, and `[upper]` sorts above them. + readUpdates(KeyRange.bound([prefix], [upper])); } - const updatesByDoc = new Map(); - for (const update of updates) { - const ms = toDate(update.createdAt).getTime(); - noteTime(update.docId, ms); - if (!update.bin?.byteLength) continue; - const frames = updatesByDoc.get(update.docId); - const entry = { ms, bin: update.bin }; - if (frames) frames.push(entry); - else updatesByDoc.set(update.docId, [entry]); - } - // Both reads start in primary key order. A stable sort keeps that order - // when a numeric key and a Date key have the same time in milliseconds. - for (const [docId, frames] of updatesByDoc) { - frames.sort((a, b) => a.ms - b.ms); - for (const { bin } of frames) appendFrame(docId, bin); - } - for (const docId of docs.keys()) { - if (!positiveDocs.has(docId)) docs.delete(docId); + await done; + const docs = assembleDocFrames( + [...clocks.values()], + [...snapshots.values()], + [...updates.values()].flat().filter(Boolean), + noteClock + ); + for (const docId of seen) { + if (!knownClockMs.has(docId)) knownClockMs.set(docId, 0); } return docs; } + /** + * Reads the frames that the first screen of the space needs, without the + * frames of other pages and without blob bytes: the workspace root + * document, every workspace table (`db$*`), every user table + * (`userdata$*`), the editor settings of a userspace, and the documents in + * `includeDocIds` (for example the documents of the open tabs). It also + * reads the `clocks` records of all documents (see `readDocFramesByKey`). + * + * @param {{ includeDocIds?: Iterable }} [opts] + * @returns {Promise>} + */ + function getTier1DocsRaw({ includeDocIds = [] } = {}) { + const docIds = [options.id]; + if (options.type === 'userspace') docIds.push(EDITOR_SETTING_DOC_ID); + return readDocFramesByKey( + [...docIds, ...includeDocIds], + TABLE_DOC_PREFIXES + ); + } + + /** + * Reads the frames of the documents in `docIds` in one read-only + * transaction. A document without stored frames is not in the result. + * + * @param {Iterable} docIds + * @returns {Promise>} + */ + function getDocsByIdsRaw(docIds) { + return readDocFramesByKey(docIds); + } + + /** + * Lists the ID of each document that has a stored snapshot or update. It + * reads keys only, never frames. + * + * @returns {Promise} + */ + async function listDocIds() { + const conn = await openIfExists(); + if (!conn) return []; + const tx = conn.transaction(['snapshots', 'updates'], 'readonly'); + const done = transactionDone(tx); + /** @type {Set} */ + const ids = new Set(); + for (const name of ['snapshots', 'updates']) { + const cursor = tx.objectStore(name).openKeyCursor(); + cursor.onsuccess = () => { + const current = cursor.result; + if (!current) return; + const key = current.primaryKey; + if (Array.isArray(key)) { + ids.add(String(key[0])); + // Skip the other updates of this document. + current.continue([key[0], []]); + } else { + ids.add(String(key)); + current.continue(); + } + }; + } + await done; + return [...ids]; + } + /** * Reads a document snapshot + pending updates from same-origin IDB v3. * When multiple CRDT frames exist, requires a `mergeUpdates` callback (never @@ -1757,6 +2167,7 @@ export function createIdbWorkspaceStorage(options) { await done.catch(() => {}); throw error; } + if (compacted) postChanges({ docsUpdated: [docId] }); return { compacted }; } @@ -1808,6 +2219,7 @@ export function createIdbWorkspaceStorage(options) { listener(docId); } channel?.postMessage({ type: 'delete', docId }); + postChanges({ docsDeleted: [docId] }); } /** @@ -1940,6 +2352,109 @@ export function createIdbWorkspaceStorage(options) { await done; } + /** @param {AccountScope} account */ + const localSeqPeer = account => + `${LOCAL_SEQ_PEER_PREFIX}${formatAccountScope(account)}`; + + /** + * Returns the pushed `local_seq` watermark of a document for an account: + * every local update with a sequence number at or below it has a durable + * acknowledgement from that account's server. Sequence numbers start at 1, + * so 0 means that no update is acknowledged. + * + * @param {AccountScope} account + * @param {string} docId + * @returns {Promise} + */ + async function getPushedLocalSeq(account, docId) { + const peer = localSeqPeer(account); + const conn = await openIfExists(); + if (!conn) return 0; + const tx = conn.transaction('peerClocks', 'readonly'); + const [record] = await Promise.all([ + requestToPromise(tx.objectStore('peerClocks').get([peer, docId])), + transactionDone(tx), + ]); + return record?.pushedLocalSeq ?? 0; + } + + /** + * Returns the pushed `local_seq` watermark of each document of an account. + * + * @param {AccountScope} account + * @returns {Promise>} + */ + async function getPushedLocalSeqs(account) { + const peer = localSeqPeer(account); + const conn = await openIfExists(); + if (!conn) return {}; + const tx = conn.transaction('peerClocks', 'readonly'); + const [records] = await Promise.all([ + requestToPromise(tx.objectStore('peerClocks').index('peer').getAll(peer)), + transactionDone(tx), + ]); + /** @type {Record} */ + const out = {}; + for (const record of records) { + out[record.docId] = record.pushedLocalSeq ?? 0; + } + return out; + } + + /** + * Records the durable acknowledgement of local update `localSeq` of a + * document by an account's server, in one `readwrite` transaction. The + * watermark moves only across a gap-free run of acknowledged numbers. An + * acknowledgement above a gap stays in the record until the gap fills. An + * acknowledgement at or below the watermark changes nothing. + * + * @param {AccountScope} account + * @param {string} docId + * @param {number} localSeq A positive integer. + * @returns {Promise<{ pushedLocalSeq: number, advanced: boolean }>} + */ + async function ackLocalSeq(account, docId, localSeq) { + if (readonlyMode) { + throw new Error('Cannot write to readonly IDB storage'); + } + if (!Number.isSafeInteger(localSeq) || localSeq < 1) { + throw new TypeError(`local_seq ${localSeq} is not a positive integer`); + } + const peer = localSeqPeer(account); + const conn = await open(); + const tx = conn.transaction('peerClocks', 'readwrite'); + const done = transactionDone(tx); + const store = tx.objectStore('peerClocks'); + const result = { pushedLocalSeq: 0, advanced: false }; + const read = store.get([peer, docId]); + read.onsuccess = () => { + const record = read.result ?? { + ...createPeerClock(peer, docId), + pushedLocalSeq: 0, + ackedAhead: [], + }; + const before = record.pushedLocalSeq ?? 0; + let pushed = before; + const ahead = new Set(/** @type {number[]} */ (record.ackedAhead ?? [])); + const known = localSeq <= pushed || ahead.has(localSeq); + if (!known) { + ahead.add(localSeq); + while (ahead.delete(pushed + 1)) pushed += 1; + store.put({ + ...record, + pushedLocalSeq: pushed, + ackedAhead: [...ahead].sort((a, b) => a - b), + }); + } + result.pushedLocalSeq = pushed; + result.advanced = pushed > before; + tx.commit?.(); + }; + await done; + if (result.advanced) postChanges({ watermarksUpdated: true }); + return result; + } + /** * @param {string} key */ @@ -2011,6 +2526,40 @@ export function createIdbWorkspaceStorage(options) { tx.commit(); } await written; + postChanges({ blobsUpdated: [blob.key] }); + } + + /** + * Deletes a blob like 0.27.5 `IndexedDBBlobStorage.delete`: marks the + * record deleted and keeps the bytes, or removes both when `permanently` + * is true. A read of a deleted blob returns `null`. + * + * @param {string} key + * @param {boolean} [permanently] + */ + async function deleteBlob(key, permanently = false) { + if (readonlyMode) { + throw new Error('Cannot delete from readonly IDB storage'); + } + const conn = await open(); + const tx = conn.transaction(['blobs', 'blobData'], 'readwrite'); + const done = transactionDone(tx); + const blobs = tx.objectStore('blobs'); + if (permanently) { + blobs.delete(key); + tx.objectStore('blobData').delete(key); + tx.commit?.(); + } else { + const meta = blobs.get(key); + meta.onsuccess = () => { + if (meta.result) { + blobs.put({ ...meta.result, deletedAt: new Date(now()) }); + } + tx.commit?.(); + }; + } + await done; + postChanges({ blobsDeleted: [key] }); } /** @@ -2113,6 +2662,19 @@ export function createIdbWorkspaceStorage(options) { }; } + /** + * Calls `callback` with the IDs that each transaction of another + * connection (another tab, or another storage object of this page) changed. + * + * @param {(changes: StorageChanges) => void} callback + */ + function subscribeChanges(callback) { + changeListeners.add(callback); + return () => { + changeListeners.delete(callback); + }; + } + /** * Updates the CRDT `mergeUpdates` callback after Wasm initialization. * @@ -2140,6 +2702,9 @@ export function createIdbWorkspaceStorage(options) { getDoc, getDocRaw, getAllDocsRaw, + getTier1DocsRaw, + getDocsByIdsRaw, + listDocIds, compactDocWithMerged, deleteDoc, getDocTimestamps, @@ -2157,15 +2722,316 @@ export function createIdbWorkspaceStorage(options) { getPeerPushedClocks: peer => getPeerFieldMap(peer, 'pushedClock'), setPeerPushedClock: (peer, clock) => setPeerField(peer, clock, 'pushedClock'), + getPushedLocalSeq, + getPushedLocalSeqs, + ackLocalSeq, getBlob, getAllBlobsRaw, setBlob, + deleteBlob, getBlobUploadedAt, setBlobUploadedAt, getDocIndexedClock, setDocIndexedClock, subscribeDocUpdate, subscribeDocDelete, + subscribeChanges, + }; +} + +/** + * Elects one replicator tab for a database among the same-origin tabs that + * open it. Only the replicator tab syncs the database with the server. The + * other tabs read what it writes and learn about each change from the + * `changes` messages of the `idb:${dbName}` channel. + * + * With the Web Locks API, the tab that holds the lock + * `affine:replicator:${dbName}` is the replicator. When it releases the lock, + * closes, or crashes, the browser gives the lock to the next waiting tab. + * + * Without the Web Locks API, or when a lock request fails, the tab uses a + * lease on the `BroadcastChannel` of the same name. The replicator posts a + * heartbeat every `heartbeatMs`. A tab that sees no heartbeat for `leaseMs`, + * or a resignation of the replicator, becomes a candidate: it posts a probe + * and claims the lease when no heartbeat answers within `heartbeatMs`. A + * candidate withdraws when it gets the probe of a tab with a lower ID, so + * one tab claims even when messages arrive late. + * + * The holder of the lock also listens on the channel, without a timer. When + * it gets the lock, it posts a heartbeat that wins over the lease, and it + * leads after the lease replicator answers that it yielded, or after + * `min(20, heartbeatMs)` when no tab answers. It answers each probe and each + * lease heartbeat, and it posts a resignation when it releases the lock. + * Without either API, the tab is the replicator at once. No path throws or + * waits forever. + * + * @param {{ + * dbName: string, + * onLeadershipChange?: (isLeader: boolean) => void, + * locks?: Pick | null, + * BroadcastChannelImpl?: typeof BroadcastChannel | null, + * now?: () => number, + * setTimeout?: typeof globalThis.setTimeout, + * clearTimeout?: typeof globalThis.clearTimeout, + * tabId?: string, + * heartbeatMs?: number, + * leaseMs?: number, + * }} options + */ +export function createReplicatorLease(options) { + const name = formatReplicatorLockName(options.dbName); + const locks = + options.locks !== undefined ? options.locks : globalThis.navigator?.locks; + const BroadcastChannelCtor = + options.BroadcastChannelImpl !== undefined + ? options.BroadcastChannelImpl + : globalThis.BroadcastChannel; + const now = options.now ?? (() => Date.now()); + const setTimer = options.setTimeout ?? globalThis.setTimeout; + const clearTimer = options.clearTimeout ?? globalThis.clearTimeout; + const heartbeatMs = options.heartbeatMs ?? 1000; + const leaseMs = options.leaseMs ?? 5000; + const tabId = + options.tabId ?? + globalThis.crypto?.randomUUID?.() ?? + `${now()}-${Math.random()}`; + + /** @type {'locks' | 'broadcast' | 'solo'} */ + let mode = 'solo'; + let leader = false; + let released = false; + /** @type {(() => void) | null} */ + let releaseLock = null; + /** @type {AbortController | null} */ + let abortRequest = null; + /** Stops the timers and the channel of this tab, and resigns when it leads. */ + /** @type {(() => void) | null} */ + let stop = null; + + /** @param {boolean} next */ + const setLeader = next => { + if (leader === next) return; + leader = next; + try { + options.onLeadershipChange?.(next); + } catch (error) { + console.error('A replicator leadership listener failed', error); + } + }; + + /** @returns {BroadcastChannel | null} */ + const openChannel = () => { + if (typeof BroadcastChannelCtor !== 'function') return null; + try { + return new BroadcastChannelCtor(name); + } catch { + return null; + } + }; + + /** + * @param {BroadcastChannel} channel + * @param {Record} message + */ + const post = (channel, message) => { + try { + channel.postMessage({ ...message, tabId }); + } catch { + // A lost message only delays the election by one lease. + } + }; + + /** Leads after the lease replicator yields, while this tab holds the lock. */ + const leadWithLock = () => { + const channel = openChannel(); + if (!channel) { + setLeader(true); + return; + } + /** @type {ReturnType | null} */ + let grantTimer = null; + const grant = () => { + if (grantTimer !== null) clearTimer(grantTimer); + grantTimer = null; + if (!released) setLeader(true); + }; + /** @param {MessageEvent} event */ + const onMessage = event => { + const data = event?.data; + if (!data || data.tabId === tabId || data.lockHeld) return; + if (data.type === 'yielded') { + if (grantTimer !== null) grant(); + } else if (data.type === 'probe' || data.type === 'heartbeat') { + post(channel, { type: 'heartbeat', lockHeld: true }); + } + }; + channel.addEventListener('message', onMessage); + stop = () => { + if (grantTimer !== null) clearTimer(grantTimer); + grantTimer = null; + channel.removeEventListener('message', onMessage); + post(channel, { type: 'resign' }); + channel.close(); + }; + post(channel, { type: 'heartbeat', lockHeld: true }); + grantTimer = setTimer(grant, Math.min(20, heartbeatMs)); + }; + + /** @returns {boolean} False when the lock request throws at once. */ + const requestLock = () => { + abortRequest = + typeof AbortController === 'function' ? new AbortController() : null; + let request; + try { + request = /** @type {Pick} */ (locks).request( + name, + abortRequest ? { signal: abortRequest.signal } : {}, + () => { + if (released) return undefined; + const held = new Promise(resolve => { + releaseLock = () => resolve(undefined); + }); + leadWithLock(); + // A listener can call `release()` from `onLeadershipChange`. + return released ? undefined : held; + } + ); + } catch (error) { + console.warn( + 'Web Locks failed, so the tabs elect a replicator by broadcast', + error + ); + return false; + } + mode = 'locks'; + Promise.resolve(request).then( + () => {}, + error => { + if (released || leader || error?.name === 'AbortError') return; + console.warn( + 'Web Locks failed, so the tabs elect a replicator by broadcast', + error + ); + startLease(); + } + ); + return true; + }; + + const startLease = () => { + const channel = openChannel(); + if (!channel) { + mode = 'solo'; + setLeader(true); + return; + } + const leaseChannel = channel; + mode = 'broadcast'; + /** @type {string | null} */ + let leaderId = null; + let seenAt = -Infinity; + /** Time of the probe of this candidate, or `null` when it is not one. */ + /** @type {number | null} */ + let probedAt = null; + /** @type {ReturnType | null} */ + let timer = null; + + /** @param {'probe' | 'heartbeat' | 'resign' | 'yielded'} type */ + const send = type => post(leaseChannel, { type }); + const stand = () => { + probedAt = now(); + send('probe'); + }; + const claim = () => { + leaderId = tabId; + probedAt = null; + setLeader(true); + if (!released) send('heartbeat'); + }; + /** @param {MessageEvent} event */ + const onMessage = event => { + const data = event?.data; + if (!data || typeof data.tabId !== 'string' || data.tabId === tabId) { + return; + } + if (data.type === 'heartbeat') { + if (leader && !data.lockHeld && data.tabId > tabId) { + // Answer at once, so the other tab yields. + send('heartbeat'); + return; + } + const yielded = leader; + leaderId = data.tabId; + seenAt = now(); + probedAt = null; + setLeader(false); + if (yielded && data.lockHeld && !released) send('yielded'); + } else if (data.type === 'probe') { + if (leader) { + send('heartbeat'); + } else if (data.tabId < tabId) { + // A tab with a lower ID stands: withdraw for one lease. + probedAt = null; + seenAt = now(); + } else if (probedAt !== null) { + send('probe'); + } + } else if ( + data.type === 'resign' && + !leader && + (leaderId === null || data.tabId === leaderId) + ) { + leaderId = null; + seenAt = -Infinity; + stand(); + } + }; + const tick = () => { + timer = null; + if (released) return; + const t = now(); + if (leader) { + send('heartbeat'); + } else if (t - seenAt > leaseMs) { + if (probedAt === null) stand(); + else if (t - probedAt >= heartbeatMs) claim(); + } + if (!released) timer = setTimer(tick, heartbeatMs); + }; + leaseChannel.addEventListener('message', onMessage); + stand(); + timer = setTimer(tick, heartbeatMs); + stop = () => { + if (timer !== null) clearTimer(timer); + timer = null; + leaseChannel.removeEventListener('message', onMessage); + if (leader) send('resign'); + leaseChannel.close(); + }; + }; + + if (!(locks && typeof locks.request === 'function' && requestLock())) { + startLease(); + } + + return { + tabId, + /** `locks`, `broadcast`, or `solo`: how this tab takes part in the election. */ + get mode() { + return mode; + }, + isLeader: () => leader, + /** Leaves the election. A replicator tab hands the role to the next tab. */ + release() { + if (released) return; + released = true; + abortRequest?.abort(); + releaseLock?.(); + releaseLock = null; + stop?.(); + stop = null; + setLeader(false); + }, }; } diff --git a/packages/frontend/hosts/web/tests/desktop.test.mjs b/packages/frontend/hosts/web/tests/desktop.test.mjs index e77c717136..0fb9c216ab 100644 --- a/packages/frontend/hosts/web/tests/desktop.test.mjs +++ b/packages/frontend/hosts/web/tests/desktop.test.mjs @@ -1740,3 +1740,504 @@ void test('desktop releases the start lock when the last workspace awaiting a se assert.equal(released, true); assert.equal(await started, store); }); + +/** + * Adds a key cursor to the `updatedAt` index of `snapshots` of the in-memory + * IndexedDB double, which has none. The cursor walks the index keys in + * order. It reads the records with the `getAll` that the double had before + * other test wrappers, so read counters do not see it. + */ +function withSnapshotTimeCursor(factory) { + const patched = new WeakSet(); + const patchDb = db => { + if (patched.has(db)) return; + patched.add(db); + const transaction = db.transaction.bind(db); + db.transaction = (names, mode) => { + const tx = transaction(names, mode); + const objectStore = tx.objectStore.bind(tx); + tx.objectStore = storeName => { + const store = objectStore(storeName); + if (storeName !== 'snapshots') return store; + const getAll = store.getAll.bind(store); + const index = store.index.bind(store); + store.index = indexName => { + const found = index(indexName); + if (indexName !== 'updatedAt') return found; + return { + ...found, + openKeyCursor() { + const req = { result: null, onsuccess: null, onerror: null }; + const all = getAll(); + all.onsuccess = () => { + const entries = all.result + .map(value => ({ + key: value.updatedAt, + primaryKey: value.docId, + })) + .sort( + (a, b) => + +a.key - +b.key || (a.primaryKey < b.primaryKey ? -1 : 1) + ); + for (const entry of entries) { + req.result = { ...entry, continue() {} }; + req.onsuccess?.(); + } + req.result = null; + req.onsuccess?.(); + }; + return req; + }, + }; + }; + return store; + }; + return tx; + }; + }; + return { + ...factory, + open(name, version) { + const req = factory.open(name, version); + return new Proxy(req, { + get(target, prop) { + const value = Reflect.get(target, prop); + if (prop === 'result' && value) patchDb(value); + return value; + }, + }); + }, + }; +} + +/** + * Opens the store of workspace `id` and records each request that reads + * stored values, by store name and key. Key cursors are not recorded. + */ +async function recordDesktopValueReads(t, indexedDB, id) { + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id }, + { indexedDB } + ); + t.after(() => db.close()); + const reads = []; + const transaction = db.transaction.bind(db); + t.mock.method(db, 'transaction', (stores, mode) => { + const tx = transaction(stores, mode); + const objectStore = tx.objectStore.bind(tx); + tx.objectStore = name => { + const store = objectStore(name); + for (const method of ['get', 'getAll']) { + const read = store[method].bind(store); + store[method] = key => { + reads.push({ store: name, method, key }); + return read(key); + }; + } + return store; + }; + return tx; + }); + return { + reads, + indexedDB: { + open(name, version) { + if (name !== `local:workspace:${id}`) { + return indexedDB.open(name, version); + } + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + }; +} + +/** + * Wraps an IndexedDB factory so that a read-only transaction runs its + * requests only after every `readwrite` transaction created before it + * completes, as browsers order transactions with overlapping scopes. The + * in-memory double runs read-only requests at once. + */ +function orderTransactions(indexedDB) { + let writes = Promise.resolve(); + const wrapDb = db => + new Proxy(db, { + get(target, prop) { + if (prop !== 'transaction') return Reflect.get(target, prop); + return (names, mode) => { + if (mode === 'readwrite') { + const tx = target.transaction(names, mode); + let settle; + writes = Promise.all([writes, new Promise(r => (settle = r))]); + return new Proxy(tx, { + set(txTarget, key, value) { + if (key === 'oncomplete' || key === 'onabort') { + txTarget[key] = event => { + settle(); + value?.(event); + }; + return true; + } + return Reflect.set(txTarget, key, value); + }, + }); + } + /** @type {IDBTransaction | null} */ + let real = null; + const queued = []; + const proxyTx = { + error: null, + oncomplete: null, + onabort: null, + commit() {}, + objectStore: name => { + const request = (call, args) => { + const req = { + result: undefined, + error: null, + onsuccess: null, + onerror: null, + }; + const run = () => { + const store = real.objectStore(name); + const r = call(store)(...args); + r.onsuccess = event => { + req.result = r.result; + req.onsuccess?.(event); + }; + r.onerror = event => { + req.error = r.error; + req.onerror?.(event); + }; + }; + if (real) run(); + else queued.push(run); + return req; + }; + return { + get: (...args) => request(store => store.get.bind(store), args), + getAll: (...args) => + request(store => store.getAll.bind(store), args), + openKeyCursor: (...args) => + request(store => store.openKeyCursor.bind(store), args), + index: indexName => ({ + getAll: (...args) => + request(store => { + const index = store.index(indexName); + return index.getAll.bind(index); + }, args), + openKeyCursor: (...args) => + request(store => { + const index = store.index(indexName); + return index.openKeyCursor.bind(index); + }, args), + }), + }; + }, + }; + void writes.then(() => { + real = target.transaction(names, mode); + real.oncomplete = event => proxyTx.oncomplete?.(event); + real.onabort = event => { + proxyTx.error = real.error; + proxyTx.onabort?.(event); + }; + for (const run of queued.splice(0)) run(); + }); + return proxyTx; + }; + }, + }); + return { + open(name, version) { + const req = indexedDB.open(name, version); + return new Proxy(req, { + get(target, prop) { + const value = Reflect.get(target, prop); + return prop === 'result' && value ? wrapDb(value) : value; + }, + }); + }, + }; +} + +void test('a lazy desktop store of a 1,000-page workspace with 50 blobs reads only the first-screen documents at startup and loads pages, media, and IDs on demand with uncommitted changes', async t => { + const memory = withSnapshotTimeCursor(createMemoryIdbFactory()); + const seed = await openDesktopStore(['ws'], { indexedDB: memory }); + for (const docId of [ + 'ws', + 'db$docProperties', + 'userdata$alice$ws$favorite', + ]) { + seed.pushUpdate('ws', docId, Uint8Array.of(1)); + } + for (let i = 0; i < 1000; i += 1) { + seed.pushUpdate('ws', `page-${i}`, Uint8Array.of(10, i & 0xff)); + } + for (let i = 0; i < 50; i += 1) { + const bytes = new Uint8Array(256 * 1024); + bytes[0] = i; + seed.putBlob('ws', `blob-${i}`, bytes); + } + await seed.flush(); + + const { reads, indexedDB } = await recordDesktopValueReads(t, memory, 'ws'); + const store = await openDesktopStore(['ws'], { + indexedDB: orderTransactions(indexedDB), + lazyTier1: true, + initialDocIdsByWorkspace: { ws: ['page-3'] }, + }); + const firstScreen = [ + 'db$docProperties', + 'page-3', + 'userdata$alice$ws$favorite', + 'ws', + ]; + assert.deepEqual(store.docIds('ws').sort(), firstScreen); + assert.deepEqual(store.docFrames('ws', 'page-3'), [Uint8Array.of(10, 3)]); + assert.deepEqual(store.blobIds('ws'), []); + const docOf = read => (read.store === 'updates' ? read.key[0] : read.key); + const frameReads = reads.filter( + read => read.store === 'updates' || read.store === 'snapshots' + ); + assert.deepEqual( + frameReads.filter(read => !firstScreen.includes(docOf(read))), + [] + ); + assert.deepEqual( + reads.filter( + read => + read.store === 'blobData' || + (read.method === 'getAll' && read.store !== 'clocks') + ), + [] + ); + console.log( + `lazy desktop cold start of 1,003 documents and 50 blobs: ${frameReads.length} frame reads, 0 reads of other pages, 0 blob reads` + ); + + assert.deepEqual(await store.loadDocFrames('ws', 'page-900'), [ + Uint8Array.of(10, 900 & 0xff), + ]); + assert.equal((await store.loadBlob('ws', 'blob-7'))[0], 7); + assert.equal(await store.loadBlob('ws', 'missing'), null); + assert.equal(await store.loadBlob('other', 'blob-7'), null); + assert.deepEqual(await store.loadDocFrames('other', 'page-1'), []); + reads.length = 0; + assert.equal((await store.listStoredDocIds('ws')).length, 1003); + assert.deepEqual(reads, []); + + store.pushUpdate('ws', 'page-900', Uint8Array.of(20)); + store.deleteDoc('ws', 'page-901'); + store.pushUpdate('ws', 'page-new', Uint8Array.of(21)); + store.putBlob('ws', 'blob-7', Uint8Array.of(77)); + const [page900, page901, ids, blob7] = await Promise.all([ + store.loadDocFrames('ws', 'page-900'), + store.loadDocFrames('ws', 'page-901'), + store.listStoredDocIds('ws'), + store.loadBlob('ws', 'blob-7'), + ]); + assert.deepEqual(page900, [Uint8Array.of(10, 900 & 0xff), Uint8Array.of(20)]); + assert.deepEqual(page901, []); + assert.ok(ids.includes('page-new') && !ids.includes('page-901')); + assert.equal(ids.length, 1003); + assert.deepEqual(blob7, Uint8Array.of(77)); + + await store.flush(); + assert.deepEqual(await store.loadDocFrames('ws', 'page-900'), [ + Uint8Array.of(10, 900 & 0xff), + Uint8Array.of(20), + ]); + assert.deepEqual(await store.loadDocFrames('ws', 'page-new'), [ + Uint8Array.of(21), + ]); +}); + +void test('the desktop store reads a change that a quota failure holds back until a later write commits it', async t => { + t.mock.method(console, 'warn', () => {}); + t.mock.method(console, 'error', () => {}); + const indexedDB = createMemoryIdbFactory(); + let limit = 0; + const { store, quota } = await openQuotaLimitedDesktop( + t, + indexedDB, + ['ws'], + 'ws', + () => limit + ); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + store.putBlob('ws', 'img', Uint8Array.of(2)); + await assert.rejects(store.flush(), quota); + assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(1)]); + assert.deepEqual(await store.loadBlob('ws', 'img'), Uint8Array.of(2)); + assert.deepEqual(await store.listStoredDocIds('ws'), ['page']); + + limit = Infinity; + await store.flush(); + assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(1)]); + const cold = await openDesktopStore(['ws'], { indexedDB }); + assert.deepEqual(cold.docFrames('ws', 'page'), [Uint8Array.of(1)]); + assert.deepEqual(await cold.loadBlob('ws', 'img'), Uint8Array.of(2)); +}); + +void test('a deletion that commits before a read does not erase the frames that another connection writes after it', async () => { + const memory = createMemoryIdbFactory(); + const indexedDB = orderTransactions(memory); + const store = await openDesktopStore(['ws'], { indexedDB }); + store.pushUpdate('ws', 'page', Uint8Array.of(1)); + await store.flush(); + const other = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws', + indexedDB, + now: () => Date.UTC(2030, 0, 1), + }); + await other.open(); + + store.deleteDoc('ws', 'page'); + // Start the deletion transaction, then the read, then the remote write. + await Promise.resolve(); + await Promise.resolve(); + const read = store.loadDocFrames('ws', 'page'); + const remote = other.writeDocOpsNow([ + { docId: 'page', bin: Uint8Array.of(9) }, + ]); + assert.deepEqual(await read, [Uint8Array.of(9)]); + await remote; + assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(9)]); + assert.deepEqual(await store.listStoredDocIds('ws'), ['page']); + other.close(); +}); + +void test('during pagehide a lazy desktop store starts at once the write of a page that it did not load and of a new page, after the stored updates', async t => { + const indexedDB = withSnapshotTimeCursor(createMemoryIdbFactory()); + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'ws-clock' }, + { indexedDB } + ); + t.after(() => db.close()); + const seed = db.transaction(['updates', 'clocks'], 'readwrite'); + seed.objectStore('updates').put({ + docId: 'page', + bin: Uint8Array.of(1), + createdAt: new Date(5000), + }); + seed.objectStore('clocks').put({ docId: 'page', timestamp: new Date(5000) }); + seed.commit(); + await new Promise(resolve => (seed.oncomplete = resolve)); + const transaction = db.transaction.bind(db); + let writes = 0; + t.mock.method(db, 'transaction', (stores, mode) => { + if (mode === 'readwrite') writes += 1; + return transaction(stores, mode); + }); + + for (const lazyTier1 of [true, false]) { + const store = await openDesktopStore(['ws-clock'], { + indexedDB: { + open() { + const req = { result: db }; + queueMicrotask(() => req.onsuccess()); + return req; + }, + }, + lazyTier1, + now: () => 4000, + }); + const listeners = new Map(); + const win = { + addEventListener: (type, listener) => listeners.set(type, listener), + document: { addEventListener() {}, visibilityState: 'visible' }, + }; + flushDesktopOnHide({ flush_web_desktop() {} }, store, win); + store.pushUpdate('ws-clock', 'page', Uint8Array.of(lazyTier1 ? 2 : 3)); + store.pushUpdate('ws-clock', `new-${lazyTier1}`, Uint8Array.of(4)); + const before = writes; + listeners.get('pagehide')(); + assert.equal(writes, before + 1, `lazyTier1 ${lazyTier1}`); + await store.flush(); + } + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-clock', + indexedDB, + }); + const raw = await storage.getDocRaw('page'); + assert.deepEqual(raw.updates, [ + Uint8Array.of(1), + Uint8Array.of(2), + Uint8Array.of(3), + ]); + assert.deepEqual( + raw.updateTimes.map(time => time.getTime()), + [5000, 5001, 5002] + ); + assert.deepEqual(await storage.getDocTimestamps(new Date(5000)), { + page: new Date(5002), + }); + for (const docId of ['new-true', 'new-false']) { + assert.deepEqual((await storage.getDocRaw(docId)).updates, [ + Uint8Array.of(4), + ]); + } +}); + +void test('a lazy desktop store writes a page that it did not load after a stored update or snapshot time that a slow clock left above the clock record', async () => { + const indexedDB = withSnapshotTimeCursor(createMemoryIdbFactory()); + const db = await openWorkspaceIdb( + { flavour: 'local', type: 'workspace', id: 'ws-skew' }, + { indexedDB } + ); + // Another connection wrote at 9000, then one with a slow clock moved the + // clock records back to 5001. + const seed = db.transaction(['updates', 'snapshots', 'clocks'], 'readwrite'); + seed.objectStore('updates').put({ + docId: 'by-update', + bin: Uint8Array.of(1), + createdAt: new Date(9000), + }); + seed.objectStore('snapshots').put({ + docId: 'by-snapshot', + bin: Uint8Array.of(1), + createdAt: new Date(9000), + updatedAt: new Date(9000), + }); + for (const docId of ['by-update', 'by-snapshot']) { + seed.objectStore('updates').put({ + docId, + bin: Uint8Array.of(2), + createdAt: new Date(5001), + }); + seed.objectStore('clocks').put({ docId, timestamp: new Date(5001) }); + } + seed.commit(); + await new Promise(resolve => (seed.oncomplete = resolve)); + + const store = await openDesktopStore(['ws-skew'], { + indexedDB, + lazyTier1: true, + now: () => 4000, + }); + assert.deepEqual(store.docIds('ws-skew'), []); + store.pushUpdate('ws-skew', 'by-update', Uint8Array.of(3)); + store.pushUpdate('ws-skew', 'by-snapshot', Uint8Array.of(3)); + await store.flush(); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-skew', + indexedDB, + }); + assert.deepEqual( + Object.keys(await storage.getDocTimestamps(new Date(9000))).sort(), + ['by-snapshot', 'by-update'] + ); + assert.deepEqual((await storage.getDocRaw('by-update')).updates, [ + Uint8Array.of(2), + Uint8Array.of(1), + Uint8Array.of(3), + ]); +}); diff --git a/packages/frontend/hosts/web/tests/idb-storage.test.mjs b/packages/frontend/hosts/web/tests/idb-storage.test.mjs index 9a24ab4601..7305309c6c 100644 --- a/packages/frontend/hosts/web/tests/idb-storage.test.mjs +++ b/packages/frontend/hosts/web/tests/idb-storage.test.mjs @@ -1,15 +1,20 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; +import { BroadcastChannel as NodeBroadcastChannel } from 'node:worker_threads'; import { openDesktopStore } from '../desktop/start.js'; import { bootWebHost, flushBeforeNavigation } from '../src/host.js'; import { addLocalWorkspaceId, + canonicalizeOrigin, createIdbV1ReadonlyReader, createIdbWorkspaceStorage, createPendingWriteFlusher, + createReplicatorLease, + formatAccountScope, formatIdbChannelName, formatIdbName, + formatReplicatorLockName, getLocalWorkspaceIds, getWebPreference, IDB_SCHEMA_VERSION, @@ -2678,3 +2683,1021 @@ void test('writeDocOpsNow applies deletions and updates in order', async () => { 'kept', ]); }); + +const ALICE = { origin: 'https://app.example.com', userId: 'alice' }; +const BOB = { origin: 'https://app.example.com', userId: 'bob' }; + +void test('cloud spaces get one database per canonical server origin and user, and local names stay 0.27.5 names', () => { + const name = account => + formatIdbName({ + flavour: 'affine-cloud', + type: 'workspace', + id: 'ws', + account, + }); + const alice = name(ALICE); + for (const [origin, same] of [ + ['https://app.example.com', true], + ['HTTPS://App.Example.COM', true], + ['https://app.example.com:443/path?q=1#x', true], + ['https://app.example.com/', true], + ['https://app.example.com:8443', false], + ['http://app.example.com', false], + ['https://other.example.com', false], + ]) { + assert.equal(name({ origin, userId: 'alice' }) === alice, same, origin); + } + assert.notEqual(name(BOB), alice); + assert.equal(canonicalizeOrigin('HTTP://LOCALHOST:80/x'), 'http://localhost'); + assert.equal( + formatAccountScope({ + origin: 'http://10.0.0.2:3010', + userId: 'alice@example.com', + }), + 'http%3A%2F%2F10.0.0.2%3A3010@alice%40example.com' + ); + assert.equal( + alice, + 'affine-cloud@https%3A%2F%2Fapp.example.com@alice:workspace:ws' + ); + assert.equal( + formatIdbName({ flavour: 'local', type: 'workspace', id: 'ws' }), + 'local:workspace:ws' + ); + assert.equal( + formatIdbName({ flavour: 'affine-cloud', type: 'userspace', id: 'alice' }), + 'affine-cloud:userspace:alice' + ); + for (const [opts, message] of [ + [ + { flavour: 'local', type: 'workspace', id: 'ws', account: ALICE }, + /local space/, + ], + [ + { + flavour: 'cloud', + type: 'workspace', + id: 'ws', + account: { origin: 'ftp://x', userId: 'a' }, + }, + /http or https/, + ], + [ + { + flavour: 'cloud', + type: 'workspace', + id: 'ws', + account: { origin: 'not a url', userId: 'a' }, + }, + /not a valid URL/, + ], + [ + { + flavour: 'cloud', + type: 'workspace', + id: 'ws', + account: { origin: 'https://user:pass@app.example.com', userId: 'a' }, + }, + /credentials/, + ], + [ + { + flavour: 'cloud', + type: 'workspace', + id: 'ws', + account: { origin: ALICE.origin, userId: '' }, + }, + /user ID/, + ], + ]) { + assert.throws(() => formatIdbName(opts), { name: 'TypeError', message }); + } +}); + +void test('two accounts of one server never read or overwrite the documents of the other', async () => { + const idb = createMemoryIdbFactory(); + const open = account => + createIdbWorkspaceStorage({ + flavour: 'affine-cloud', + type: 'workspace', + id: 'ws', + account, + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 1_000, + }); + const alice = open(ALICE); + const bob = open(BOB); + await alice.open(); + await bob.open(); + await alice.writeDocOpsNow([{ docId: 'page', bin: Uint8Array.of(1) }]); + await bob.writeDocOpsNow([{ docId: 'page', bin: Uint8Array.of(2) }]); + assert.deepEqual((await alice.getDocRaw('page')).updates, [Uint8Array.of(1)]); + assert.deepEqual((await bob.getDocRaw('page')).updates, [Uint8Array.of(2)]); + assert.notEqual(alice.dbName, bob.dbName); + assert.ok(idb.getMeta(alice.dbName) && idb.getMeta(bob.dbName)); + assert.equal(idb.getMeta('affine-cloud:workspace:ws'), undefined); +}); + +void test('the pushed local_seq watermark moves only across gap-free acknowledgements of the same account', async () => { + const idb = createMemoryIdbFactory(); + const Bus = createBroadcastBus(); + const make = () => + createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-seq', + indexedDB: idb, + BroadcastChannelImpl: Bus, + }); + const storage = make(); + const peer = make(); + await storage.open(); + await peer.open(); + const notices = []; + peer.subscribeChanges(changes => notices.push(changes.watermarksUpdated)); + + for (const [seq, pushed, advanced] of [ + [3, 0, false], + [1, 1, true], + [1, 1, false], + [3, 1, false], + [2, 3, true], + [5, 3, false], + [4, 5, true], + [6, 6, true], + ]) { + assert.deepEqual( + await storage.ackLocalSeq(ALICE, 'page', seq), + { pushedLocalSeq: pushed, advanced }, + `ack ${seq}` + ); + } + assert.deepEqual(notices, [true, true, true, true]); + await storage.ackLocalSeq(ALICE, 'other', 1); + + const reopened = make(); + assert.equal(await reopened.getPushedLocalSeq(ALICE, 'page'), 6); + assert.equal( + await reopened.getPushedLocalSeq( + { origin: 'HTTPS://APP.example.com:443', userId: 'alice' }, + 'page' + ), + 6 + ); + assert.deepEqual(await reopened.getPushedLocalSeqs(ALICE), { + other: 1, + page: 6, + }); + for (const account of [ + BOB, + { origin: 'https://other.example.com', userId: 'alice' }, + ]) { + assert.equal(await reopened.getPushedLocalSeq(account, 'page'), 0); + assert.deepEqual(await reopened.getPushedLocalSeqs(account), {}); + } + assert.deepEqual(await reopened.getPeerPushedClocks('affine-cloud'), {}); + for (const seq of [0, -1, 1.5, Number.NaN]) { + await assert.rejects(storage.ackLocalSeq(ALICE, 'page', seq), { + name: 'TypeError', + }); + } +}); + +/** + * Adds a key cursor to the `updatedAt` index of `snapshots` of the in-memory + * IndexedDB double, which has none. The cursor walks the index keys in + * order. It reads the records with the `getAll` that the double had before + * other test wrappers, so read counters do not see it. + */ +function withSnapshotTimeCursor(factory) { + const patched = new WeakSet(); + const patchDb = db => { + if (patched.has(db)) return; + patched.add(db); + const transaction = db.transaction.bind(db); + db.transaction = (names, mode) => { + const tx = transaction(names, mode); + const objectStore = tx.objectStore.bind(tx); + tx.objectStore = storeName => { + const store = objectStore(storeName); + if (storeName !== 'snapshots') return store; + const getAll = store.getAll.bind(store); + const index = store.index.bind(store); + store.index = indexName => { + const found = index(indexName); + if (indexName !== 'updatedAt') return found; + return { + ...found, + openKeyCursor() { + const req = { result: null, onsuccess: null, onerror: null }; + const all = getAll(); + all.onsuccess = () => { + const entries = all.result + .map(value => ({ + key: value.updatedAt, + primaryKey: value.docId, + })) + .sort( + (a, b) => + +a.key - +b.key || (a.primaryKey < b.primaryKey ? -1 : 1) + ); + for (const entry of entries) { + req.result = { ...entry, continue() {} }; + req.onsuccess?.(); + } + req.result = null; + req.onsuccess?.(); + }; + return req; + }, + }; + }; + return store; + }; + return tx; + }; + }; + return { + ...factory, + open(name, version) { + const req = factory.open(name, version); + return new Proxy(req, { + get(target, prop) { + const value = Reflect.get(target, prop); + if (prop === 'result' && value) patchDb(value); + return value; + }, + }); + }, + }; +} + +/** + * Wraps an IndexedDB factory and records each request that reads stored + * values (`get` and `getAll` of a store or index) by store name. Key cursors + * read no values and are not recorded. + */ +function recordValueReads(factory) { + /** @type {Array<{ store: string, method: string, key: unknown }>} */ + const reads = []; + const wrapStore = (name, store) => + new Proxy(store, { + get(target, prop) { + if (prop === 'get' || prop === 'getAll') { + return key => { + reads.push({ store: name, method: prop, key }); + return target[prop](key); + }; + } + if (prop === 'index') { + return indexName => { + const index = target.index(indexName); + return { + getAll: key => { + reads.push({ store: name, method: 'index.getAll', key }); + return index.getAll(key); + }, + openKeyCursor: (...args) => index.openKeyCursor(...args), + }; + }; + } + return Reflect.get(target, prop); + }, + }); + const wrapDb = db => + new Proxy(db, { + get(target, prop) { + if (prop !== 'transaction') return Reflect.get(target, prop); + return (names, mode) => { + const tx = target.transaction(names, mode); + return new Proxy(tx, { + get(txTarget, txProp) { + if (txProp === 'objectStore') { + return name => wrapStore(name, txTarget.objectStore(name)); + } + return Reflect.get(txTarget, txProp); + }, + }); + }; + }, + }); + return { + reads, + indexedDB: { + ...factory, + open(name, version) { + const req = factory.open(name, version); + return new Proxy(req, { + get(target, prop) { + const value = Reflect.get(target, prop); + return prop === 'result' && value ? wrapDb(value) : value; + }, + }); + }, + }, + }; +} + +/** Docs of a large workspace: a root, two tables, a user table, and pages. */ +async function seedLargeWorkspace(idb, { pages = 1000, blobs = 50 } = {}) { + let clock = 1_000; + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => clock++, + }); + await storage.open(); + const ops = [ + { docId: 'ws', bin: Uint8Array.of(1) }, + { docId: 'db$docProperties', bin: Uint8Array.of(2) }, + { docId: 'db$folders', bin: Uint8Array.of(3) }, + { docId: 'userdata$alice$ws$favorite', bin: Uint8Array.of(4) }, + ]; + for (let i = 0; i < pages; i += 1) { + ops.push({ docId: `page-${i}`, bin: Uint8Array.of(10, i & 0xff) }); + ops.push({ docId: `page-${i}`, bin: Uint8Array.of(11, i & 0xff) }); + } + for (let i = 0; i < blobs; i += 1) { + const data = new Uint8Array(256 * 1024); + data[0] = i; + ops.push({ blobKey: `blob-${i}`, data }); + } + await storage.writeDocOpsNow(ops); + // Snapshots of the root, a table, and two pages. + for (const docId of ['ws', 'db$folders', 'page-7', 'page-8']) { + const source = await storage.getDocRaw(docId); + await storage.compactDocWithMerged({ + docId, + mergedBin: Uint8Array.of(99, ...source.updates.at(-1)), + source, + }); + } + await storage.writeDocOpsNow([{ docId: 'page-7', bin: Uint8Array.of(12) }]); + const all = await storage.getAllDocsRaw(); + storage.close(); + return all; +} + +void test('tier-1 cold reads of a 1,000-page workspace with 50 blobs read only the root, tables, and the given pages, and no blob bytes', async () => { + const memory = withSnapshotTimeCursor(createMemoryIdbFactory()); + const all = await seedLargeWorkspace(memory); + assert.equal(all.size, 1004); + const { indexedDB, reads } = recordValueReads(memory); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws', + indexedDB, + BroadcastChannelImpl: createBroadcastBus(), + }); + const tier1 = await storage.getTier1DocsRaw({ + includeDocIds: ['page-7', 'page-500', 'db$folders', 'missing'], + }); + const expected = [ + 'ws', + 'db$docProperties', + 'db$folders', + 'userdata$alice$ws$favorite', + 'page-7', + 'page-500', + ]; + assert.deepEqual([...tier1.keys()].sort(), [...expected].sort()); + for (const docId of expected) { + assert.deepEqual(tier1.get(docId), all.get(docId), docId); + } + assert.deepEqual(tier1.get('page-7'), [ + Uint8Array.of(99, 11, 7), + Uint8Array.of(12), + ]); + const docOf = ({ store, key }) => + store === 'updates' ? key[0] : String(key); + const valueReads = reads.filter( + read => read.store === 'updates' || read.store === 'snapshots' + ); + const otherPages = valueReads.filter( + read => !expected.includes(docOf(read)) && docOf(read) !== 'missing' + ); + assert.equal(otherPages.length, 0); + assert.equal(reads.filter(read => read.store === 'blobData').length, 0); + // One `getAll` reads the `clocks` records (IDs and times, no frames). + assert.deepEqual( + reads + .filter(read => read.method !== 'get') + .map(read => `${read.store}.${read.method}`), + ['clocks.getAll'] + ); + // One read per stored update: 1 of `db$docProperties`, of the user table, + // and of `page-7` after its snapshot, and 2 of `page-500`. + assert.equal(valueReads.filter(read => read.store === 'updates').length, 5); + const frameBytes = docs => + [...docs.values()].flat().reduce((sum, frame) => sum + frame.byteLength, 0); + const tier1Reads = reads.length; + reads.length = 0; + const eagerDocs = await storage.getAllDocsRaw(); + const eagerBlobs = await storage.getAllBlobsRaw(); + const eagerRecords = reads.length; + console.log( + `tier-1 cold read of 1,004 documents and 50 blobs: ${valueReads.length} frame reads (${tier1Reads} value requests, ${frameBytes(tier1)} B); ` + + `full read: ${eagerRecords} getAll requests over ${eagerDocs.size} documents (${frameBytes(eagerDocs)} B) and ${eagerBlobs.size} blobs (${frameBytes(eagerBlobs)} B)` + ); + + reads.length = 0; + const ids = await storage.listDocIds(); + assert.deepEqual(ids.sort(), [...all.keys()].sort()); + assert.equal(reads.length, 0); + + reads.length = 0; + const some = await storage.getDocsByIdsRaw(['page-900', 'page-8', 'missing']); + assert.deepEqual([...some.keys()].sort(), ['page-8', 'page-900']); + assert.deepEqual(some.get('page-900'), all.get('page-900')); + assert.deepEqual([...new Set(reads.map(docOf))].sort(), [ + 'missing', + 'page-8', + 'page-900', + ]); + + reads.length = 0; + const blob = await storage.getBlob('blob-42'); + assert.equal(blob.data[0], 42); + assert.deepEqual(reads.map(read => `${read.store}:${read.key}`).sort(), [ + 'blobData:blob-42', + 'blobs:blob-42', + ]); + storage.close(); +}); + +void test('tier-1 reads of a userspace include its editor settings', async () => { + const idb = withSnapshotTimeCursor(createMemoryIdbFactory()); + const storage = createIdbWorkspaceStorage({ + flavour: 'affine-cloud', + type: 'userspace', + id: 'alice', + account: ALICE, + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 5, + }); + await storage.open(); + await storage.writeDocOpsNow([ + { docId: 'editorSetting', bin: Uint8Array.of(1) }, + { docId: 'journal', bin: Uint8Array.of(2) }, + ]); + assert.deepEqual( + [...(await storage.getTier1DocsRaw()).keys()], + ['editorSetting'] + ); +}); + +void test('each committed write tells the other connections which documents, blobs, and watermarks changed, without frames or bytes', async () => { + const idb = createMemoryIdbFactory(); + const Bus = createBroadcastBus(); + let clock = 100; + const make = () => + createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-changes', + indexedDB: idb, + BroadcastChannelImpl: Bus, + now: () => clock++, + }); + const writer = make(); + const reader = make(); + await writer.open(); + await reader.open(); + const seen = []; + reader.subscribeChanges(changes => seen.push(changes)); + const mine = []; + writer.subscribeChanges(changes => mine.push(changes)); + const none = { + docsUpdated: [], + docsDeleted: [], + blobsUpdated: [], + blobsDeleted: [], + watermarksUpdated: false, + }; + + const steps = [ + [ + () => + writer.writeDocOpsNow([ + { docId: 'a', bin: Uint8Array.of(1) }, + { docId: 'a', bin: Uint8Array.of(2) }, + { docId: 'b', delete: true }, + { blobKey: 'img', data: new Uint8Array(1024) }, + ]), + { docsUpdated: ['a'], docsDeleted: ['b'], blobsUpdated: ['img'] }, + ], + [ + async () => { + const source = await writer.getDocRaw('a'); + await writer.compactDocWithMerged({ + docId: 'a', + mergedBin: Uint8Array.of(3), + source, + }); + }, + { docsUpdated: ['a'] }, + ], + [ + () => writer.pushDocUpdate({ docId: 'c', bin: Uint8Array.of(4) }), + { docsUpdated: ['c'] }, + ], + [ + () => writer.createDocIfMissing({ docId: 'd', bin: Uint8Array.of(5) }), + { docsUpdated: ['d'] }, + ], + [() => writer.deleteDoc('c'), { docsDeleted: ['c'] }], + [ + () => + writer.setBlob({ key: 'x', mime: 'image/png', data: Uint8Array.of(6) }), + { blobsUpdated: ['x'] }, + ], + [() => writer.deleteBlob('x'), { blobsDeleted: ['x'] }], + [() => writer.deleteBlob('img', true), { blobsDeleted: ['img'] }], + [() => writer.ackLocalSeq(ALICE, 'a', 1), { watermarksUpdated: true }], + ]; + for (const [run, expected] of steps) { + seen.length = 0; + await run(); + assert.deepEqual(seen, [{ ...none, ...expected }]); + } + assert.deepEqual(mine, []); + assert.equal(await reader.getBlob('x'), null); + assert.equal(await reader.getBlob('img'), null); + assert.equal( + idb.getMeta(writer.dbName).stores.get('blobData').records.size, + 1 + ); + seen.length = 0; + await writer.ackLocalSeq(ALICE, 'a', 1); + await writer.compactDocWithMerged({ + docId: 'a', + mergedBin: Uint8Array.of(7), + source: null, + }); + assert.deepEqual(seen, []); +}); + +/** Timers that run only when a test advances the clock. */ +function createFakeTimers() { + let now = 0; + let nextId = 1; + const timers = new Map(); + return { + now: () => now, + setTimeout: (fn, ms) => { + const id = nextId++; + timers.set(id, { at: now + ms, fn }); + return id; + }, + clearTimeout: id => timers.delete(id), + pending: () => timers.size, + advance(ms) { + const end = now + ms; + for (;;) { + const due = [...timers] + .filter(([, t]) => t.at <= end) + .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0]; + if (!due) break; + timers.delete(due[0]); + now = due[1].at; + due[1].fn(); + } + now = end; + }, + }; +} + +/** + * A Web Locks API double: one exclusive lock per name, granted in request + * order. `crash(name)` frees a held lock without the holder, as when its tab + * dies. + */ +function createFakeWebLocks() { + const held = new Map(); + const queues = new Map(); + const grant = name => { + if (held.has(name)) return; + const next = queues.get(name)?.shift(); + if (!next) return; + const holder = { done: false }; + held.set(name, holder); + const free = () => { + if (holder.done) return; + holder.done = true; + held.delete(name); + queueMicrotask(() => grant(name)); + }; + holder.free = free; + Promise.resolve() + .then(() => next.callback({ name, mode: 'exclusive' })) + .then( + value => { + free(); + next.resolve(value); + }, + error => { + free(); + next.reject(error); + } + ); + }; + return { + request(name, opts, callback) { + return new Promise((resolve, reject) => { + const entry = { callback, resolve, reject }; + const queue = queues.get(name) ?? []; + queues.set(name, queue); + queue.push(entry); + opts?.signal?.addEventListener('abort', () => { + const index = queue.indexOf(entry); + if (index < 0) return; + queue.splice(index, 1); + reject(Object.assign(new Error('aborted'), { name: 'AbortError' })); + }); + grant(name); + }); + }, + crash(name) { + held.get(name)?.free(); + }, + isHeld: name => held.has(name), + waiting: name => queues.get(name)?.length ?? 0, + }; +} + +const settle = async () => { + for (let i = 0; i < 10; i += 1) await Promise.resolve(); +}; + +void test('Web Locks elect one replicator tab per database and hand the role over on release or crash', async () => { + const locks = createFakeWebLocks(); + const timers = createFakeTimers(); + const dbName = 'local:workspace:ws'; + const lockName = formatReplicatorLockName(dbName); + assert.equal(lockName, 'affine:replicator:local:workspace:ws'); + const changes = []; + const Bus = createBroadcastBus(); + const tab = (id, name = dbName) => + createReplicatorLease({ + dbName: name, + locks, + BroadcastChannelImpl: Bus, + tabId: id, + ...timers, + onLeadershipChange: leader => changes.push(`${id}:${leader}`), + }); + // A holder leads after it waits `min(20, heartbeatMs)` for a lease tab. + const step = async () => { + await settle(); + timers.advance(20); + await settle(); + }; + const a = tab('a'); + const b = tab('b'); + const c = tab('c'); + const other = tab('o', 'local:workspace:other'); + await step(); + assert.deepEqual( + [a.isLeader(), b.isLeader(), c.isLeader(), other.isLeader()], + [true, false, false, true] + ); + assert.deepEqual([a.mode, b.mode], ['locks', 'locks']); + + a.release(); + await step(); + assert.deepEqual( + [a.isLeader(), b.isLeader(), c.isLeader()], + [false, true, false] + ); + + locks.crash(lockName); + await step(); + assert.equal(c.isLeader(), true); + assert.deepEqual(changes, [ + 'a:true', + 'o:true', + 'a:false', + 'b:true', + 'c:true', + ]); + + // A waiting tab that leaves never becomes the replicator. + const d = tab('d'); + await step(); + assert.equal(locks.waiting(lockName), 1); + d.release(); + await step(); + assert.equal(locks.waiting(lockName), 0); + c.release(); + await step(); + assert.equal(d.isLeader(), false); + assert.deepEqual(changes.slice(5), ['c:false']); + // `b` lost its lock in the crash; its page is gone in a browser. + b.release(); + other.release(); + assert.equal(timers.pending(), 0); +}); + +void test('a failed or missing Web Locks API falls back to a broadcast lease, then to a single replicator tab', async t => { + t.mock.method(console, 'warn', () => {}); + const Bus = createBroadcastBus(); + for (const [locks, mode] of [ + [ + { + request: () => { + throw new Error('SecurityError'); + }, + }, + 'broadcast', + ], + [ + { request: () => Promise.reject(new Error('SecurityError')) }, + 'broadcast', + ], + [null, 'broadcast'], + [{}, 'broadcast'], + ]) { + const timers = createFakeTimers(); + const lease = createReplicatorLease({ + dbName: 'ws', + locks, + BroadcastChannelImpl: Bus, + tabId: 'x', + ...timers, + }); + await settle(); + assert.equal(lease.mode, mode); + timers.advance(1000); + assert.equal(lease.isLeader(), true); + lease.release(); + } + const listener = t.mock.fn(() => { + throw new Error('listener'); + }); + t.mock.method(console, 'error', () => {}); + const solo = createReplicatorLease({ + dbName: 'ws', + locks: null, + BroadcastChannelImpl: null, + onLeadershipChange: listener, + }); + assert.equal(solo.mode, 'solo'); + assert.equal(solo.isLeader(), true); + solo.release(); + assert.equal(solo.isLeader(), false); + assert.deepEqual( + listener.mock.calls.map(call => call.arguments[0]), + [true, false] + ); +}); + +void test('the broadcast lease keeps one replicator tab, hands over to the lowest candidate on release, and takes over after a crash', () => { + const Bus = createBroadcastBus(); + const timers = createFakeTimers(); + const tabs = new Map(); + const tab = id => { + const channels = []; + class TabChannel extends Bus { + constructor(name) { + super(name); + channels.push(this); + } + } + const ownTimers = new Map(); + let nextId = 1; + let crashed = false; + const lease = createReplicatorLease({ + dbName: 'ws', + locks: null, + BroadcastChannelImpl: TabChannel, + tabId: id, + now: timers.now, + heartbeatMs: 1000, + leaseMs: 3000, + setTimeout: (fn, ms) => { + const key = nextId++; + ownTimers.set( + key, + timers.setTimeout(() => crashed || fn(), ms) + ); + return key; + }, + clearTimeout: key => timers.clearTimeout(ownTimers.get(key)), + }); + tabs.set(id, lease); + return { + lease, + crash() { + crashed = true; + for (const channel of channels) channel.close(); + }, + }; + }; + const leaders = () => + [...tabs].filter(([, l]) => l.isLeader()).map(([id]) => id); + + const b = tab('b'); + const c = tab('c'); + timers.advance(1000); + assert.deepEqual(leaders(), ['b']); + // A later tab with a lower ID joins while a replicator holds the lease. + const a = tab('a'); + timers.advance(10_000); + assert.deepEqual(leaders(), ['b']); + + // Both followers stand after the resignation, and `c` withdraws for `a`. + b.lease.release(); + assert.deepEqual(leaders(), []); + timers.advance(1000); + assert.deepEqual(leaders(), ['a']); + + // After the lease runs out, `c` probes once and claims the lease when no + // heartbeat answers within one heartbeat interval. + a.crash(); + tabs.delete('a'); + timers.advance(4000); + assert.deepEqual(leaders(), []); + timers.advance(1000); + assert.deepEqual(leaders(), ['c']); + c.lease.release(); +}); + +void test('with an asynchronous BroadcastChannel, three lease tabs never have two replicators, also after the replicator resigns', async () => { + const timers = createFakeTimers(); + const leaders = new Set(); + const atClaim = []; + const turn = () => new Promise(resolve => setImmediate(resolve)); + // Node delivers `BroadcastChannel` messages in later event loop turns. + const deliver = async () => { + for (let i = 0; i < 20; i += 1) await turn(); + }; + const tabs = ['a', 'b', 'c'].map(id => + createReplicatorLease({ + dbName: `async-${process.pid}`, + locks: null, + BroadcastChannelImpl: NodeBroadcastChannel, + tabId: id, + ...timers, + onLeadershipChange: leader => { + if (leader) { + leaders.add(id); + atClaim.push([...leaders]); + } else { + leaders.delete(id); + } + }, + }) + ); + const [a, b, c] = tabs; + await deliver(); + timers.advance(1000); + await deliver(); + assert.deepEqual([...leaders], ['a']); + + a.release(); + await deliver(); + for (let i = 0; i < 3; i += 1) { + timers.advance(1000); + await deliver(); + } + assert.deepEqual([...leaders], ['b']); + assert.deepEqual(atClaim, [['a'], ['b']]); + b.release(); + c.release(); + await deliver(); + assert.equal(timers.pending(), 0); +}); + +void test('a replicator that releases inside its leadership callback leaves no lock, timer, or second leader, and the next tab takes over', async () => { + const locks = createFakeWebLocks(); + const Bus = createBroadcastBus(); + for (const mode of ['locks', 'broadcast']) { + const timers = createFakeTimers(); + const events = []; + const tab = (id, onLeadershipChange) => + createReplicatorLease({ + dbName: `ws-${mode}`, + locks: mode === 'locks' ? locks : null, + BroadcastChannelImpl: Bus, + tabId: id, + ...timers, + onLeadershipChange, + }); + const a = tab('a', leader => { + events.push(`a:${leader}`); + if (leader) a.release(); + }); + const b = tab('b', leader => events.push(`b:${leader}`)); + for (let i = 0; i < 3; i += 1) { + await settle(); + timers.advance(1000); + } + await settle(); + assert.deepEqual(events, ['a:true', 'a:false', 'b:true'], mode); + assert.deepEqual([a.isLeader(), b.isLeader()], [false, true], mode); + b.release(); + await settle(); + assert.equal(timers.pending(), 0, mode); + assert.equal(locks.isHeld(`affine:replicator:ws-${mode}`), false, mode); + } +}); + +void test('a lease tab follows a tab that holds the Web Lock until it releases the lock, and yields before the holder leads', async t => { + t.mock.method(console, 'warn', () => {}); + const locks = createFakeWebLocks(); + const failing = { + request: () => Promise.reject(new Error('SecurityError')), + }; + const Bus = createBroadcastBus(); + for (const order of ['lock first', 'lease first']) { + const timers = createFakeTimers(); + const events = []; + let lease; + let atGrant = null; + const tab = (id, tabLocks) => { + return createReplicatorLease({ + dbName: 'ws-mixed', + locks: tabLocks, + BroadcastChannelImpl: Bus, + tabId: id, + ...timers, + onLeadershipChange: leader => { + events.push(`${id}:${leader}`); + if (id === 'z' && leader) atGrant = lease ? lease.isLeader() : false; + }, + }); + }; + let holder; + if (order === 'lock first') { + // The lease tab has the lower ID, so only the lock decides. + holder = tab('z', locks); + await settle(); + timers.advance(20); + lease = tab('a', failing); + await settle(); + } else { + lease = tab('a', failing); + await settle(); + timers.advance(1000); + assert.equal(lease.isLeader(), true, order); + holder = tab('z', locks); + await settle(); + } + assert.equal(lease.mode, 'broadcast', order); + for (let i = 0; i < 12; i += 1) { + timers.advance(1000); + await settle(); + assert.deepEqual( + [holder.isLeader(), lease.isLeader()], + [true, false], + `${order} ${i}` + ); + } + assert.equal(atGrant, false, order); + assert.deepEqual( + events, + order === 'lock first' ? ['z:true'] : ['a:true', 'a:false', 'z:true'], + order + ); + holder.release(); + await settle(); + timers.advance(2000); + assert.deepEqual([holder.isLeader(), lease.isLeader()], [false, true]); + lease.release(); + assert.equal(timers.pending(), 0); + } +}); + +void test('frame reads return each requested document once', async () => { + const idb = withSnapshotTimeCursor(createMemoryIdbFactory()); + const storage = createIdbWorkspaceStorage({ + flavour: 'local', + type: 'workspace', + id: 'ws-dupes', + indexedDB: idb, + BroadcastChannelImpl: createBroadcastBus(), + now: () => 10, + }); + await storage.open(); + await storage.writeDocOpsNow([ + { docId: 'ws-dupes', bin: Uint8Array.of(1) }, + { docId: 'page', bin: Uint8Array.of(2) }, + { docId: 'page', bin: Uint8Array.of(3) }, + ]); + const frames = [Uint8Array.of(2), Uint8Array.of(3)]; + for (const docs of [ + await storage.getDocsByIdsRaw(['page', 'page', '']), + await storage.getTier1DocsRaw({ + includeDocIds: ['ws-dupes', 'page', 'page'], + }), + ]) { + assert.deepEqual(docs.get('page'), frames); + } + assert.deepEqual((await storage.listDocIds()).sort(), ['page', 'ws-dupes']); +});