diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index a6733f7966..5dd095e824 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -13,7 +13,6 @@ import { import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; -import { IndexeddbPersistence } from "y-indexeddb"; import * as Y from "yjs"; import { EditorUpdateError } from "@shared/collaboration/CloseEvents"; import History from "@shared/editor/extensions/History"; @@ -31,6 +30,7 @@ import useIsMounted from "~/hooks/useIsMounted"; import usePageVisibility from "~/hooks/usePageVisibility"; import useStores from "~/hooks/useStores"; import type { AwarenessChangeEvent } from "~/types"; +import { IndexeddbPersistence } from "~/utils/IndexeddbPersistence"; import Logger from "~/utils/Logger"; import { homePath } from "~/utils/routeHelpers"; import { sleep } from "@shared/utils/timers"; @@ -82,6 +82,9 @@ function MultiplayerEditor( // an orphaned websocket connection. // see: https://github.com/facebook/react/issues/20090#issuecomment-715926549 useLayoutEffect(() => { + // Tracks whether this effect has been cleaned up so async persistence + // callbacks below do not update state afterwards. + let isActive = true; const debug = env.ENVIRONMENT === "development"; const name = `document.${documentId}`; const localProvider = @@ -172,10 +175,23 @@ function MultiplayerEditor( }; provider.on("awarenessChange", showCursorNames); - localProvider?.on("synced", () => - // only set local storage to "synced" if it's loaded a non-empty doc - setLocalSynced(!!ydoc.get("default")._start) - ); + localProvider?.whenSynced + .then(() => { + if (!isActive || !localProvider.synced) { + return; + } + if (debug) { + Logger.debug("collaboration", "local synced"); + } + // only set local storage to "synced" if it's loaded a non-empty doc + setLocalSynced(!!ydoc.get("default")._start); + }) + .catch(() => { + // IndexedDB exists but is unusable, e.g. Firefox private browsing. + if (isActive) { + setHasLocalPersistence(false); + } + }); provider.on("synced", () => { presence.touch(documentId, currentUser.id, false); setRemoteSynced(true); @@ -211,9 +227,6 @@ function MultiplayerEditor( message: ev.message, }) ); - localProvider?.on("synced", () => - Logger.debug("collaboration", "local synced") - ); } provider.on("status", (ev: ConnectionStatusEvent) => { @@ -225,6 +238,7 @@ function MultiplayerEditor( setRemoteProvider(provider); return () => { + isActive = false; window.removeEventListener("click", finishObserving); window.removeEventListener("wheel", finishObserving); window.removeEventListener("scroll", syncScrollPosition); diff --git a/app/utils/IndexeddbPersistence.ts b/app/utils/IndexeddbPersistence.ts new file mode 100644 index 0000000000..7d64223ac1 --- /dev/null +++ b/app/utils/IndexeddbPersistence.ts @@ -0,0 +1,234 @@ +import * as Y from "yjs"; + +/** + * Persists a Y.Doc to IndexedDB so documents can be loaded instantly from the + * local cache and edited offline. + * + * Adapted from y-indexeddb (https://github.com/yjs/y-indexeddb, MIT licensed) + * so that we have full control over the underlying database rows. The schema + * is kept compatible with databases created by y-indexeddb: one database per + * document containing an "updates" object store where each row is a binary + * Yjs update keyed by an auto-incrementing integer. Rows are periodically + * compacted into a single row holding the whole document state. + */ +export class IndexeddbPersistence { + /** Name of the IndexedDB database that backs this instance. */ + public readonly name: string; + + /** The Y.Doc that is being persisted. */ + public readonly doc: Y.Doc; + + /** Whether the state stored in the database has been applied to the document. */ + public synced = false; + + /** + * Resolves once the state stored in the database has been applied to the + * document, or immediately if the instance is destroyed beforehand – check + * `synced` to distinguish the two. + */ + public readonly whenSynced: Promise; + + /** + * @param name Name of the database, unique per persisted document. + * @param doc The Y.Doc to persist. + */ + constructor(name: string, doc: Y.Doc) { + this.name = name; + this.doc = doc; + this.dbPromise = openDatabase(name); + + this.whenSynced = this.dbPromise.then(async (db) => { + this.db = db; + await this.fetchStoredUpdates(true); + + if (!this.destroyed) { + this.synced = true; + } + return this; + }); + + doc.on("update", this.handleDocUpdate); + doc.on("destroy", this.destroy); + } + + /** + * Merges all stored update rows into a single row containing the current + * document state. + * + * @returns a promise that resolves when compaction has completed. + */ + public compact(): Promise { + return this.storeState(true); + } + + /** + * Stops persisting the document and closes the database connection. Data + * already stored is left intact. + * + * @returns a promise that resolves when the database has been closed. + */ + public destroy = (): Promise => { + if (this.destroyed) { + return Promise.resolve(); + } + this.destroyed = true; + + if (this.storeTimeoutId !== undefined) { + clearTimeout(this.storeTimeoutId); + this.storeTimeoutId = undefined; + } + + this.doc.off("update", this.handleDocUpdate); + this.doc.off("destroy", this.destroy); + + return this.dbPromise.then( + (db) => db.close(), + () => undefined + ); + }; + + private dbPromise: Promise; + + private db: IDBDatabase | null = null; + + /** Key of the first update row that has not been applied to the document. */ + private dbref = 0; + + /** Approximate number of rows in the updates store. */ + private dbsize = 0; + + private destroyed = false; + + /** + * Number of stored updates after which they are merged into a single + * database row containing the entire document state, keeping loads fast. + */ + private preferredTrimSize = 500; + + /** Time in ms to debounce compaction once the trim size is reached. */ + private storeTimeout = 1000; + + private storeTimeoutId?: ReturnType; + + /** + * Appends every local document update as a new row, and schedules a + * compaction once the number of rows grows beyond the preferred trim size. + */ + private handleDocUpdate = (update: Uint8Array, origin: unknown) => { + if (!this.db || origin === this || this.destroyed) { + return; + } + + this.updatesStore(this.db).add(update); + + if (++this.dbsize >= this.preferredTrimSize) { + if (this.storeTimeoutId !== undefined) { + clearTimeout(this.storeTimeoutId); + } + this.storeTimeoutId = setTimeout(() => { + this.storeTimeoutId = undefined; + void this.storeState(false); + }, this.storeTimeout); + } + }; + + /** + * Applies all rows stored since the last read to the document – on first + * call this loads the document, on later calls it picks up rows written by + * other tabs. When `storeCurrentState` is set, any state already in the + * document is written as a new row so it cannot be lost. + * + * @returns the object store, still inside the read-write transaction. + */ + private async fetchStoredUpdates( + storeCurrentState = false + ): Promise { + if (!this.db) { + return undefined; + } + const store = this.updatesStore(this.db); + const updates: Uint8Array[] = await requestToPromise( + store.getAll(IDBKeyRange.lowerBound(this.dbref, false)) + ); + + if (!this.destroyed) { + if (storeCurrentState && this.doc.store.clients.size > 0) { + store.add(Y.encodeStateAsUpdate(this.doc)); + } + Y.transact( + this.doc, + () => updates.forEach((update) => Y.applyUpdate(this.doc, update)), + this, + false + ); + } + + const lastKeyPromise = getLastKey(store); + const countPromise = requestToPromise(store.count()); + this.dbref = (await lastKeyPromise) + 1; + this.dbsize = await countPromise; + return store; + } + + /** + * Writes the whole document state as a single row and deletes the rows it + * replaces. Unless `force` is set, this only happens once the number of + * rows has grown beyond the preferred trim size. + */ + private async storeState(force: boolean): Promise { + const store = await this.fetchStoredUpdates(); + + if (!store || this.destroyed) { + return; + } + if (force || this.dbsize >= this.preferredTrimSize) { + store.add(Y.encodeStateAsUpdate(this.doc)); + store.delete(IDBKeyRange.upperBound(this.dbref, true)); + this.dbsize = await requestToPromise(store.count()); + } + } + + private updatesStore(db: IDBDatabase): IDBObjectStore { + return db + .transaction(updatesStoreName, "readwrite") + .objectStore(updatesStoreName); + } +} + +const updatesStoreName = "updates"; + +function requestToPromise(request: IDBRequest): Promise { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function openDatabase(name: string): Promise { + return new Promise((resolve, reject) => { + const request = indexedDB.open(name); + request.onupgradeneeded = () => { + const db = request.result; + if (!db.objectStoreNames.contains(updatesStoreName)) { + db.createObjectStore(updatesStoreName, { autoIncrement: true }); + } + }; + request.onsuccess = () => { + const db = request.result; + // Close the connection when another context deletes or upgrades the + // database, otherwise their request would block indefinitely. + db.onversionchange = () => db.close(); + resolve(db); + }; + request.onerror = () => reject(request.error); + }); +} + +function getLastKey(store: IDBObjectStore): Promise { + return new Promise((resolve, reject) => { + const request = store.openKeyCursor(null, "prev"); + request.onsuccess = () => + resolve(request.result ? Number(request.result.key) : -1); + request.onerror = () => reject(request.error); + }); +} diff --git a/package.json b/package.json index 567ac96957..bf258decfe 100644 --- a/package.json +++ b/package.json @@ -274,7 +274,6 @@ "vite-plugin-pwa": "1.3.0", "winston": "^3.17.0", "ws": "^7.5.11", - "y-indexeddb": "^9.0.12", "y-prosemirror": "^1.3.7", "y-protocols": "^1.0.7", "yauzl": "^3.3.1", diff --git a/vite.config.ts b/vite.config.ts index 70ef306888..1498a81502 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -229,7 +229,7 @@ export default ({ mode }: ConfigEnv) => }, { name: "vendor-collab", - test: /node_modules[\\/](yjs|y-prosemirror|y-indexeddb|@hocuspocus|lib0)/, + test: /node_modules[\\/](yjs|y-prosemirror|@hocuspocus|lib0)/, priority: 20, }, { diff --git a/yarn.lock b/yarn.lock index 58cc82fe9f..84d551a4f3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14065,7 +14065,7 @@ __metadata: languageName: node linkType: hard -"lib0@npm:^0.2.109, lib0@npm:^0.2.46, lib0@npm:^0.2.47, lib0@npm:^0.2.74, lib0@npm:^0.2.85, lib0@npm:^0.2.99": +"lib0@npm:^0.2.109, lib0@npm:^0.2.46, lib0@npm:^0.2.47, lib0@npm:^0.2.85, lib0@npm:^0.2.99": version: 0.2.114 resolution: "lib0@npm:0.2.114" dependencies: @@ -15974,7 +15974,6 @@ __metadata: vitest: "npm:^4.1.10" winston: "npm:^3.17.0" ws: "npm:^7.5.11" - y-indexeddb: "npm:^9.0.12" y-prosemirror: "npm:^1.3.7" y-protocols: "npm:^1.0.7" yauzl: "npm:^3.3.1" @@ -21533,17 +21532,6 @@ __metadata: languageName: node linkType: hard -"y-indexeddb@npm:^9.0.12": - version: 9.0.12 - resolution: "y-indexeddb@npm:9.0.12" - dependencies: - lib0: "npm:^0.2.74" - peerDependencies: - yjs: ^13.0.0 - checksum: 10c0/b31fbc12ef4a7d71f09212db02570af07c6a17b02537ce4cbb29f0549137adcbebf613cb2af63fa1d13e0932645be0293a4e7189cb5bf5dc6263cf2f72b65004 - languageName: node - linkType: hard - "y-prosemirror@npm:^1.3.7": version: 1.3.7 resolution: "y-prosemirror@npm:1.3.7"