mirror of
https://github.com/outline/outline.git
synced 2026-12-03 10:00:13 +03:00
feat: Persist policies to IndexedDB so abilities survive reload
Adds a StorePersistence layer that caches a store's models in IndexedDB and hydrates them back at boot as stale data, revalidated by normal API traffic. Enabled for the policies store, scoped per team, so cached abilities are available immediately after a reload instead of every policy needing a forced refetch. - Persistence hooks in the base Store add/remove/clear methods, since add() updates existing models in place and map observation would miss those changes - Enabled from RootStore construction (team read from localStorage) and again after auth.info succeeds to cover the first session after login - Store.clear() wipes the persisted records, covering both logout paths - deleteAllDatabases() fallback removes the policies database on browsers without indexedDB.databases() Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XisV6sRdexfnPSiehurKoV
This commit is contained in:
1 parent
f4b9c7c910
commit
6455506edc
9 files changed
+394
No files matched your search
@@ -223,6 +223,10 @@ export default class AuthStore extends Store<Team> {
|
||||
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! });
|
||||
|
||||
@@ -36,6 +36,10 @@ export default class PoliciesStore extends Store<Policy> {
|
||||
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,
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<T> =
|
||||
| ((value: T, index: number, collection: ArrayLike<T>) => boolean)
|
||||
@@ -77,6 +78,8 @@ export default abstract class Store<T extends Model> {
|
||||
|
||||
rootStore: RootStore;
|
||||
|
||||
protected persistence?: StorePersistence<T>;
|
||||
|
||||
actions = [
|
||||
RPCAction.Info,
|
||||
RPCAction.List,
|
||||
@@ -98,6 +101,24 @@ export default abstract class Store<T extends Model> {
|
||||
@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<void> {
|
||||
if (this.persistence || !StorePersistence.isSupported) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.persistence = new StorePersistence<T>(this, databaseName);
|
||||
await this.persistence.hydrate();
|
||||
}
|
||||
|
||||
addPolicies = (policies: Policy[]) => {
|
||||
@@ -176,16 +197,19 @@ export default abstract class Store<T extends Model> {
|
||||
|
||||
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<T extends Model> {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<T extends Model> {
|
||||
id: string;
|
||||
data: PartialExcept<T, "id">;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<T extends Model> {
|
||||
/** 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<T>, 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<void> => {
|
||||
try {
|
||||
const database = await this.open();
|
||||
const records = await promisifyRequest<PersistedRecord<T>[]>(
|
||||
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<void> => {
|
||||
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<IDBDatabase> => {
|
||||
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<T>;
|
||||
|
||||
private name: string;
|
||||
|
||||
private database?: Promise<IDBDatabase>;
|
||||
|
||||
private dirty = new Set<string>();
|
||||
|
||||
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<T extends Model>(model: T): PartialExcept<T, "id"> {
|
||||
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<T>(request: IDBRequest<T>): Promise<T> {
|
||||
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<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(transaction.error);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user