diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 8a120c162d..e53886c897 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -223,6 +223,10 @@ export default class AuthStore extends Store { this.availableTeams = res.data.availableTeams; this.collaborationToken = res.data.collaborationToken; + // Covers the first session after login, where no team was available + // in localStorage when the root store was constructed. + this.rootStore.enablePersistence(); + if (env.SENTRY_DSN) { const scope = Sentry.getCurrentScope(); scope.setUser({ id: this.currentUserId! }); diff --git a/app/stores/PoliciesStore.ts b/app/stores/PoliciesStore.ts index fb40f65ed5..ddb4aef8c2 100644 --- a/app/stores/PoliciesStore.ts +++ b/app/stores/PoliciesStore.ts @@ -36,6 +36,10 @@ export default class PoliciesStore extends Store { policy.abilities[key] = can; } + // The abilities are mutated in place rather than through add(), so + // the persisted copy must be refreshed explicitly. + this.persistence?.persist(policy.id); + Logger.debug("policies", "Removed membership from policy", { policy: policy.id, ability: key, diff --git a/app/stores/RootStore.ts b/app/stores/RootStore.ts index 07fb24bd2e..6f4ff0de2f 100644 --- a/app/stores/RootStore.ts +++ b/app/stores/RootStore.ts @@ -36,6 +36,7 @@ import UsersStore from "./UsersStore"; import ViewsStore from "./ViewsStore"; import WebhookSubscriptionsStore from "./WebhookSubscriptionStore"; import type Store from "./base/Store"; +import StorePersistence from "./base/StorePersistence"; export default class RootStore { apiKeys: ApiKeysStore; @@ -113,6 +114,26 @@ export default class RootStore { // AuthStore must be initialized last as it makes use of the other stores. this.registerStore(AuthStore, "auth"); + + // AuthStore will have synchronously rehydrated the current team from + // localStorage at this point, if a session exists. + this.enablePersistence(); + } + + /** + * Enable IndexedDB persistence for eligible stores, scoped to the current + * team. A no-op when there is no authenticated team or persistence is + * already enabled. + */ + public enablePersistence() { + const teamId = this.auth.currentTeamId; + if (!teamId) { + return; + } + + void this.policies.enablePersistence( + StorePersistence.databaseName("policies", teamId) + ); } /** diff --git a/app/stores/base/Store.ts b/app/stores/base/Store.ts index d72e98a901..b905a4ce1c 100644 --- a/app/stores/base/Store.ts +++ b/app/stores/base/Store.ts @@ -23,6 +23,7 @@ import type { PaginationParams, PartialExcept, Properties } from "~/types"; import { client } from "~/utils/ApiClient"; import { AuthorizationError, NotFoundError } from "~/utils/errors"; import ParanoidModel from "~/models/base/ParanoidModel"; +import StorePersistence from "./StorePersistence"; type ListPredicate = | ((value: T, index: number, collection: ArrayLike) => boolean) @@ -77,6 +78,8 @@ export default abstract class Store { rootStore: RootStore; + protected persistence?: StorePersistence; + actions = [ RPCAction.Info, RPCAction.List, @@ -98,6 +101,24 @@ export default abstract class Store { @action clear() { this.data.clear(); + this.persistence?.clear(); + } + + /** + * Enables persistence of this store's data to IndexedDB and hydrates any + * previously persisted records into the store. Safe to call multiple times, + * subsequent calls are a no-op. + * + * @param databaseName the name of the IndexedDB database to persist to. + * @returns a promise that resolves when hydration is complete. + */ + async enablePersistence(databaseName: string): Promise { + if (this.persistence || !StorePersistence.isSupported) { + return; + } + + this.persistence = new StorePersistence(this, databaseName); + await this.persistence.hydrate(); } addPolicies = (policies: Policy[]) => { @@ -176,16 +197,19 @@ export default abstract class Store { if (existingModel) { existingModel.updateData(item); + this.persistence?.persist(existingModel.id); return existingModel; } // @ts-expect-error TS thinks that we're instantiating an abstract class here const newModel = new ModelClass(item, this); this.data.set(newModel.id, newModel); + this.persistence?.persist(newModel.id); return newModel; } this.data.set(item.id, item); + this.persistence?.persist(item.id); return item; }; @@ -244,6 +268,10 @@ export default abstract class Store { } LifecycleManager.executeHooks(model.constructor, "afterRemove", model); + + // Persists the soft-deleted model, or removes the persisted record if the + // model was hard-deleted from the store. + this.persistence?.persist(id); } @action diff --git a/app/stores/base/StorePersistence.test.ts b/app/stores/base/StorePersistence.test.ts new file mode 100644 index 0000000000..7d6ba4c0ce --- /dev/null +++ b/app/stores/base/StorePersistence.test.ts @@ -0,0 +1,95 @@ +/* oxlint-disable */ +import "fake-indexeddb/auto"; +// The stores singleton must be imported before RootStore so that the module +// cycle through AuthStore -> developer.ts -> ~/stores resolves in the same +// order as the application entry point. +import "~/stores"; +import { toJS } from "mobx"; +import RootStore from "~/stores/RootStore"; +import StorePersistence from "./StorePersistence"; + +describe("StorePersistence", () => { + test("round-trips models through IndexedDB into a fresh store", async () => { + const name = StorePersistence.databaseName("policies", "team-1"); + const source = new RootStore(); + const persistence = new StorePersistence(source.policies, name); + + source.policies.add({ + id: "doc-1", + abilities: { read: true, update: ["membership-1"] }, + }); + persistence.persist("doc-1"); + await persistence.flush(); + + const target = new RootStore(); + const targetPersistence = new StorePersistence(target.policies, name); + await targetPersistence.hydrate(); + + expect(toJS(target.policies.get("doc-1")?.abilities)).toEqual({ + read: true, + update: ["membership-1"], + }); + expect(target.policies.abilities("doc-1").read).toBe(true); + expect(target.policies.abilities("doc-1").update).toBeTruthy(); + }); + + test("does not overwrite models already in the store when hydrating", async () => { + const name = StorePersistence.databaseName("policies", "team-2"); + const source = new RootStore(); + const persistence = new StorePersistence(source.policies, name); + + source.policies.add({ id: "doc-1", abilities: { read: false } }); + persistence.persist("doc-1"); + await persistence.flush(); + + const target = new RootStore(); + target.policies.add({ id: "doc-1", abilities: { read: true } }); + const targetPersistence = new StorePersistence(target.policies, name); + await targetPersistence.hydrate(); + + expect(target.policies.get("doc-1")?.abilities).toEqual({ read: true }); + }); + + test("deletes the persisted record when the model has been removed", async () => { + const name = StorePersistence.databaseName("policies", "team-3"); + const source = new RootStore(); + const persistence = new StorePersistence(source.policies, name); + + source.policies.add({ id: "doc-1", abilities: { read: true } }); + persistence.persist("doc-1"); + await persistence.flush(); + + source.policies.remove("doc-1"); + persistence.persist("doc-1"); + await persistence.flush(); + + const target = new RootStore(); + const targetPersistence = new StorePersistence(target.policies, name); + await targetPersistence.hydrate(); + + expect(target.policies.get("doc-1")).toBeUndefined(); + }); + + test("clear removes all persisted records", async () => { + const name = StorePersistence.databaseName("policies", "team-4"); + const source = new RootStore(); + const persistence = new StorePersistence(source.policies, name); + + source.policies.add({ id: "doc-1", abilities: { read: true } }); + source.policies.add({ id: "doc-2", abilities: { read: true } }); + persistence.persist("doc-1"); + persistence.persist("doc-2"); + await persistence.flush(); + + persistence.clear(); + + // clear() runs asynchronously in the background, wait for it to finish. + await new Promise((resolve) => setTimeout(resolve, 50)); + + const target = new RootStore(); + const targetPersistence = new StorePersistence(target.policies, name); + await targetPersistence.hydrate(); + + expect(target.policies.orderedData).toHaveLength(0); + }); +}); diff --git a/app/stores/base/StorePersistence.ts b/app/stores/base/StorePersistence.ts new file mode 100644 index 0000000000..966b3c76e3 --- /dev/null +++ b/app/stores/base/StorePersistence.ts @@ -0,0 +1,226 @@ +import { debounce } from "es-toolkit/compat"; +import type Model from "~/models/base/Model"; +import type { PartialExcept } from "~/types"; +import Logger from "~/utils/Logger"; +import type Store from "./Store"; + +/** Bump to discard previously persisted data when the format changes. */ +const SCHEMA_VERSION = 1; + +/** Name of the single object store used within each database. */ +const OBJECT_STORE_NAME = "items"; + +/** How long to wait after the last change before writing to IndexedDB. */ +const FLUSH_DELAY_MS = 1000; + +interface PersistedRecord { + id: string; + data: PartialExcept; +} + +/** + * Persists a store's models to IndexedDB so that previously loaded data + * survives a reload and is available offline. Persisted data is strictly a + * cache – it is hydrated into the store at boot as stale data and revalidated + * by normal API traffic, which always wins over the cached copy. + */ +export default class StorePersistence { + /** Whether IndexedDB persistence is supported in the current environment. */ + public static get isSupported(): boolean { + return typeof window !== "undefined" && !!window.indexedDB; + } + + /** + * Builds the name of the database backing a store, scoped to a team so that + * cached data is never shared between accounts on the same origin. + * + * @param storeName the name of the store, eg "policies". + * @param teamId the ID of the team the data belongs to. + * @returns the database name. + */ + public static databaseName(storeName: string, teamId: string): string { + return `outline.${storeName}.${teamId}`; + } + + constructor(store: Store, databaseName: string) { + this.store = store; + this.name = databaseName; + } + + /** + * Loads all persisted records into the store. Records for models already in + * the store are skipped, as in-memory data is always fresher than the cache. + * + * @returns a promise that resolves when hydration is complete. + */ + public hydrate = async (): Promise => { + try { + const database = await this.open(); + const records = await promisifyRequest[]>( + database + .transaction(OBJECT_STORE_NAME, "readonly") + .objectStore(OBJECT_STORE_NAME) + .getAll() + ); + + for (const record of records) { + if (!this.store.get(record.id)) { + this.store.add(record.data); + } + } + } catch (err) { + this.disabled = true; + Logger.warn("Failed to hydrate store from IndexedDB", { + database: this.name, + error: err, + }); + } + }; + + /** + * Schedules the model with the given ID to be written to IndexedDB. If the + * model is no longer in the store when the write occurs, the persisted + * record is deleted instead. + * + * @param id the ID of the model to persist. + */ + public persist = (id: string) => { + if (this.disabled) { + return; + } + this.dirty.add(id); + this.scheduleFlush(); + }; + + /** + * Writes all pending changes to IndexedDB immediately. + * + * @returns a promise that resolves when the write is complete. + */ + public flush = async (): Promise => { + if (this.disabled || this.dirty.size === 0) { + return; + } + + const ids = Array.from(this.dirty); + this.dirty.clear(); + + try { + const database = await this.open(); + const transaction = database.transaction(OBJECT_STORE_NAME, "readwrite"); + const objectStore = transaction.objectStore(OBJECT_STORE_NAME); + + for (const id of ids) { + const model = this.store.get(id); + if (model) { + objectStore.put({ id, data: serialize(model) }); + } else { + objectStore.delete(id); + } + } + + await promisifyTransaction(transaction); + } catch (err) { + Logger.warn("Failed to write store to IndexedDB", { + database: this.name, + error: err, + }); + } + }; + + /** + * Removes all persisted records, used when the store is cleared on logout. + */ + public clear = () => { + this.dirty.clear(); + + if (this.disabled) { + return; + } + + void this.open() + .then((database) => + promisifyRequest( + database + .transaction(OBJECT_STORE_NAME, "readwrite") + .objectStore(OBJECT_STORE_NAME) + .clear() + ) + ) + .catch((err) => { + Logger.warn("Failed to clear persisted store in IndexedDB", { + database: this.name, + error: err, + }); + }); + }; + + private open = (): Promise => { + if (!this.database) { + this.database = new Promise((resolve, reject) => { + const request = window.indexedDB.open(this.name, SCHEMA_VERSION); + + request.onupgradeneeded = () => { + const database = request.result; + if (database.objectStoreNames.contains(OBJECT_STORE_NAME)) { + database.deleteObjectStore(OBJECT_STORE_NAME); + } + database.createObjectStore(OBJECT_STORE_NAME, { keyPath: "id" }); + }; + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + } + return this.database; + }; + + private scheduleFlush = debounce(() => void this.flush(), FLUSH_DELAY_MS); + + private store: Store; + + private name: string; + + private database?: Promise; + + private dirty = new Set(); + + private disabled = false; +} + +/** + * Serializes a model to a plain object safe for structured cloning, dropping + * functions and other non-serializable properties. + * + * @param model the model to serialize. + * @returns a plain object representation of the model. + */ +function serialize(model: T): PartialExcept { + return JSON.parse(JSON.stringify(model)); +} + +/** + * Converts an IndexedDB request into a promise. + * + * @param request the request to convert. + * @returns a promise that resolves with the request result. + */ +function promisifyRequest(request: IDBRequest): Promise { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +/** + * Converts an IndexedDB transaction into a promise. + * + * @param transaction the transaction to convert. + * @returns a promise that resolves when the transaction completes. + */ +function promisifyTransaction(transaction: IDBTransaction): Promise { + return new Promise((resolve, reject) => { + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + transaction.onabort = () => reject(transaction.error); + }); +} diff --git a/app/utils/developer.ts b/app/utils/developer.ts index 7a70652085..161a6b80cd 100644 --- a/app/utils/developer.ts +++ b/app/utils/developer.ts @@ -1,5 +1,6 @@ import { flatten } from "es-toolkit/compat"; import stores from "~/stores"; +import StorePersistence from "~/stores/base/StorePersistence"; import { flattenTree } from "@shared/utils/tree"; /** @@ -12,6 +13,12 @@ export async function deleteAllDatabases() { return; } + if (stores.auth.currentTeamId) { + window.indexedDB.deleteDatabase( + StorePersistence.databaseName("policies", stores.auth.currentTeamId) + ); + } + if ("databases" in window.indexedDB) { const databases = await window.indexedDB.databases(); diff --git a/package.json b/package.json index 7ca810de0a..5551d083b5 100644 --- a/package.json +++ b/package.json @@ -354,6 +354,7 @@ "browserslist-to-esbuild": "^1.2.0", "concurrently": "^8.2.2", "discord-api-types": "^0.38.48", + "fake-indexeddb": "^6.2.5", "husky": "^8.0.3", "i18next-parser": "^9.4.0", "ioredis-mock": "^8.13.1", diff --git a/yarn.lock b/yarn.lock index 3dfb6ad76c..47a1276e04 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11186,6 +11186,13 @@ __metadata: languageName: node linkType: hard +"fake-indexeddb@npm:^6.2.5": + version: 6.2.5 + resolution: "fake-indexeddb@npm:6.2.5" + checksum: 10c0/6c5e2fe84a61daa06d7ad63699d1041fe61847f15f92db12415634b3db94f363a64be9e08a3c3c4434af9c3c0132086b85c4d5dc5e8e06edae1e7daf70ce1f3c + languageName: node + linkType: hard + "fast-content-type-parse@npm:^3.0.0": version: 3.0.0 resolution: "fast-content-type-parse@npm:3.0.0" @@ -15605,6 +15612,7 @@ __metadata: emoji-regex: "npm:^10.6.0" es-toolkit: "npm:^1.47.1" es6-error: "npm:^4.1.1" + fake-indexeddb: "npm:^6.2.5" fast-deep-equal: "npm:^3.1.3" fetch-retry: "npm:^5.0.6" form-data: "npm:^4.0.6"