From abc5ed76ad5aa45b9e0eae6a120f7c9bd3c13f1f Mon Sep 17 00:00:00 2001 From: Mikhail Yarmaliuk Date: Tue, 29 Sep 2026 17:42:30 -0700 Subject: [PATCH] feat: batch persist saves and add key-value and IndexedDB storages (#53) Persisted stores were serialized with a deep toJS of the whole store on every change, including other stores referenced from plain fields, and every change rewrote the whole storage value. - track only persisted attributes, referenced stores are not traversed - batch changes per `persistDelay` (default 100 ms, 0 keeps save-on-every-change, the server always saves immediately) - flush queued changes on page hide, before a store is destroyed, on destroy() and on `manager.flushPersist()` - write every changed storage once per batch, compare stores by JSON and serialize each store once - add optional `IStorage.saveChanges` for incremental saves, built-in single-value storages assemble JSON from cached store JSON - add KeyValueStorage (a key per store: AsyncStorage, MMKV, localStorage) and IndexedDBStorage, both with migration from an existing storage - CookieStorage warns once when the value exceeds 4 KB --- README.md | 2 +- __probes__/consumer-explicit.tsx | 16 + __probes__/consumer.tsx | 16 + __tests__/manager.ts | 136 +++++- __tests__/on-change-listener.ts | 550 +++++++++++++++++++++-- __tests__/storages/async-storage.ts | 43 ++ __tests__/storages/combined-storage.ts | 149 ++++++ __tests__/storages/cookie-storage.ts | 18 + __tests__/storages/indexed-db-storage.ts | 212 +++++++++ __tests__/storages/key-value-storage.ts | 272 +++++++++++ __tests__/storages/local-storage.ts | 37 ++ docs/ai-usage.md | 38 +- docs/api/manager.md | 39 +- docs/examples/recipes.md | 143 ++++++ package-lock.json | 11 + package.json | 1 + src/deep-compare.ts | 5 +- src/manager.ts | 233 ++++++++-- src/on-change-listener.ts | 55 ++- src/storages/async-storage.ts | 18 +- src/storages/combined-storage.ts | 228 ++++++++-- src/storages/cookie-storage.ts | 37 +- src/storages/indexed-db-storage.ts | 264 +++++++++++ src/storages/key-value-storage.ts | 230 ++++++++++ src/storages/local-storage.ts | 14 +- src/storages/store-records-storage.ts | 130 ++++++ src/store-state.ts | 71 +++ src/types.ts | 28 ++ src/wakeup.ts | 2 +- 29 files changed, 2895 insertions(+), 103 deletions(-) create mode 100644 __tests__/storages/indexed-db-storage.ts create mode 100644 __tests__/storages/key-value-storage.ts create mode 100644 src/storages/indexed-db-storage.ts create mode 100644 src/storages/key-value-storage.ts create mode 100644 src/storages/store-records-storage.ts create mode 100644 src/store-state.ts diff --git a/README.md b/README.md index 0e899a2..159272d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ It is built for apps that want explicit store ownership, SSR support, persistenc - Support code splitting out of the box. - Access stores from other stores. - Can be a replacement for react context. -- Persistence support +- Persistence with batched writes: local/session storage, cookies, AsyncStorage, per-store key-value (AsyncStorage, MMKV) and IndexedDB - Vite plugin support - Best-effort HMR - And many other nice things 😎 diff --git a/__probes__/consumer-explicit.tsx b/__probes__/consumer-explicit.tsx index 01848fb..d0ee62e 100644 --- a/__probes__/consumer-explicit.tsx +++ b/__probes__/consumer-explicit.tsx @@ -9,6 +9,8 @@ import SessionStorage from '@lomray/react-mobx-manager/storages/session-storage. import CookieStorage from '@lomray/react-mobx-manager/storages/cookie-storage.js'; import AsyncStorage from '@lomray/react-mobx-manager/storages/async-storage.js'; import CombinedStorage from '@lomray/react-mobx-manager/storages/combined-storage.js'; +import KeyValueStorage from '@lomray/react-mobx-manager/storages/key-value-storage.js'; +import IndexedDBStorage from '@lomray/react-mobx-manager/storages/indexed-db-storage.js'; import vitePlugin from '@lomray/react-mobx-manager/plugins/vite/index.js'; import connectDevExtension from '@lomray/react-mobx-manager/plugins/dev-extension/index.js'; import { @@ -44,6 +46,8 @@ void [ CookieStorage, AsyncStorage, CombinedStorage, + KeyValueStorage, + IndexedDBStorage, connectDevExtension, connectViteHmr, connectWebpackHmr, @@ -52,6 +56,18 @@ void [ ManagerHmr, ]; +const persisted = new api.Manager({ + storage: new CombinedStorage({ + local: new IndexedDBStorage({ migrateFrom: new LocalStorage({ storage: localStorage }) }), + native: new KeyValueStorage({ + storage: { getItem: () => null, setItem: () => undefined, removeItem: () => undefined }, + }), + }), + options: { persistDelay: 200 }, +}); +const isFlushed: Promise = persisted.flushPersist(); +void isFlushed; + api.Manager.persistStore(Store, 'example'); // @ts-expect-error A persistence ID is required. api.Manager.persistStore(Store); diff --git a/__probes__/consumer.tsx b/__probes__/consumer.tsx index 1b4661a..20a5f9c 100644 --- a/__probes__/consumer.tsx +++ b/__probes__/consumer.tsx @@ -9,6 +9,8 @@ import SessionStorage from '@lomray/react-mobx-manager/storages/session-storage' import CookieStorage from '@lomray/react-mobx-manager/storages/cookie-storage'; import AsyncStorage from '@lomray/react-mobx-manager/storages/async-storage'; import CombinedStorage from '@lomray/react-mobx-manager/storages/combined-storage'; +import KeyValueStorage from '@lomray/react-mobx-manager/storages/key-value-storage'; +import IndexedDBStorage from '@lomray/react-mobx-manager/storages/indexed-db-storage'; import vitePlugin from '@lomray/react-mobx-manager/plugins/vite'; import connectDevExtension from '@lomray/react-mobx-manager/plugins/dev-extension'; import { @@ -44,6 +46,8 @@ void [ CookieStorage, AsyncStorage, CombinedStorage, + KeyValueStorage, + IndexedDBStorage, connectDevExtension, connectViteHmr, connectWebpackHmr, @@ -52,6 +56,18 @@ void [ ManagerHmr, ]; +const persisted = new api.Manager({ + storage: new CombinedStorage({ + local: new IndexedDBStorage({ migrateFrom: new LocalStorage({ storage: localStorage }) }), + native: new KeyValueStorage({ + storage: { getItem: () => null, setItem: () => undefined, removeItem: () => undefined }, + }), + }), + options: { persistDelay: 200 }, +}); +const isFlushed: Promise = persisted.flushPersist(); +void isFlushed; + api.Manager.persistStore(Store, 'example'); // @ts-expect-error A persistence ID is required. api.Manager.persistStore(Store); diff --git a/__tests__/manager.ts b/__tests__/manager.ts index b3f739c..e903f86 100644 --- a/__tests__/manager.ts +++ b/__tests__/manager.ts @@ -1,4 +1,4 @@ -import { makeAutoObservable } from 'mobx'; +import { makeAutoObservable, makeObservable, observable, reaction, runInAction } from 'mobx'; import sinon from 'sinon'; import { afterEach, describe, expect, it } from 'vitest'; import { makeExported } from '@src/make-exported'; @@ -690,4 +690,138 @@ describe('Manager', () => { plainValue: 'plain', }); }); + + it('should not traverse other stores referenced by plain fields', () => { + const other = makeAutoObservable({ counter: 0 }); + const store = makeAutoObservable({ value: 1 }); + const effect = sandbox.stub(); + + Object.assign(store, { other }); + + const dispose = reaction(() => Manager.getObservableProps(store as never), effect); + + runInAction(() => { + other.counter += 1; + }); + sinon.assert.notCalled(effect); + + runInAction(() => { + store.value += 1; + }); + sinon.assert.calledOnce(effect); + expect(effect.firstCall.args[0]).to.deep.equal({ value: 2 }); + + dispose(); + }); + + it('should get and save only persisted attributes', async () => { + const set = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set, flush: sandbox.stub() } }), + }); + + class ListStore { + public libStoreId = 'list'; + + public libStorageOptions = { + behaviour: 'include' as const, + attributes: { local: ['items', 'missing'] }, + }; + + public items = [1]; + + public isFetching = true; + + constructor() { + makeObservable(this, { items: observable, isFetching: observable }); + } + } + + const store = new ListStore(); + + expect(manager.getPersistState(store)).to.deep.equal({ items: [1] }); + expect(await manager.savePersistedStore(store)).to.equal(true); + sinon.assert.calledOnceWithExactly(set, { list: { items: [1] } }); + }); + + it('should flush through overridden single store saving', async () => { + const storage = new CombinedStorage({ + local: { get: () => ({}), set: sandbox.stub(), flush: sandbox.stub() }, + }); + const saveStoreData = sandbox.stub(storage, 'saveStoreData').resolves(); + const manager = new Manager({ storage }); + const store = { libStoreId: 'store', toJSON: () => ({ value: 1 }) }; + + manager.schedulePersist(store); + + expect(await manager.flushPersist()).to.equal(true); + sinon.assert.calledOnceWithExactly(saveStoreData, store, { value: 1 }); + + const savePersistedStore = sandbox.stub(manager, 'savePersistedStore').resolves(false); + + manager.schedulePersist(store); + + expect(await manager.flushPersist()).to.equal(false); + sinon.assert.calledOnceWithExactly(savePersistedStore, store); + }); + + it('should ignore scheduled persist when persist is disabled', async () => { + const set = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set, flush: sandbox.stub() } }), + options: { shouldDisablePersist: true }, + }); + + manager.schedulePersist({ libStoreId: 'store', toJSON: () => ({ value: 1 }) }); + + expect(await manager.flushPersist()).to.equal(false); + sinon.assert.notCalled(set); + }); + + it('should wait for storage writes in progress on flush', async () => { + let finishWrite: () => void = () => undefined; + const set = sandbox.stub().callsFake( + () => + new Promise((resolve) => { + finishWrite = resolve; + }), + ); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set, flush: sandbox.stub() } }), + }); + const isFlushed = sandbox.stub(); + + manager.schedulePersist({ libStoreId: 'store', toJSON: () => ({ value: 1 }) }); + void manager.flushPersist(); + void manager.flushPersist().then(isFlushed); + + await Promise.resolve(); + sinon.assert.calledOnce(set); + sinon.assert.notCalled(isFlushed); + + finishWrite(); + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + + sinon.assert.calledOnceWithExactly(isFlushed, true); + }); + + it('should remove page listeners on destroy', () => { + const set = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set, flush: sandbox.stub() } }), + }); + + manager.schedulePersist({ libStoreId: 'store', toJSON: () => ({ value: 1 }) }); + manager.destroy(); + + sinon.assert.calledOnce(set); + + const flushPersist = sandbox.spy(manager, 'flushPersist'); + + window.dispatchEvent(new Event('pagehide')); + + sinon.assert.notCalled(flushPersist); + }); }); diff --git a/__tests__/on-change-listener.ts b/__tests__/on-change-listener.ts index eabff1d..04cac7c 100644 --- a/__tests__/on-change-listener.ts +++ b/__tests__/on-change-listener.ts @@ -1,52 +1,542 @@ +import { extendObservable, makeObservable, observable, runInAction } from 'mobx'; import sinon from 'sinon'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; +import { makeExported } from '@src/make-exported'; +import Manager from '@src/manager'; +import onChangeListener from '@src/on-change-listener'; +import CombinedStorage from '@src/storages/combined-storage'; +import type { IConstructorParams, IManagerOptions, IStorePersisted } from '@src/types'; describe('onChangeListener', () => { + const sandbox = sinon.createSandbox(); + afterEach(() => { - vi.resetModules(); - vi.doUnmock('mobx'); + sandbox.restore(); + Manager.getPersistedStoresIds().clear(); }); - it('should return undefined when persist is disabled', async () => { - const { default: onChangeListener } = await import('@src/on-change-listener'); - const listener = onChangeListener!; + class SessionStore { + public static isGlobal = true; + + public counter = 0; + + constructor() { + makeObservable(this, { counter: observable }); + } + } + + /** + * Fresh store class: persistStore keeps options in the class prototype + */ + const createFeedStore = () => + class FeedStore { + public static isGlobal = true; + + public items: string[] = []; + + public page = 1; - const result = listener({ toJSON: () => ({}) }, { + public isFetching = false; + + public sessionStore: SessionStore; + + constructor({ getStore }: IConstructorParams) { + this.sessionStore = getStore(SessionStore)!; + + makeObservable(this, { items: observable, page: observable, isFetching: observable }); + } + }; + + /** + * Create manager with sync storage + */ + const createManager = async (options: IManagerOptions = {}, data: Record = {}) => { + const set = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => data, set, flush: sandbox.stub() } }), + options, + logger: { level: 0 }, + }); + + await manager.init(); + + return { manager, set }; + }; + + it('should return undefined when persist is disabled', () => { + const result = onChangeListener!({ toJSON: () => ({}) }, { options: { shouldDisablePersist: true }, } as never); expect(result).to.be.undefined; }); - it('should subscribe with reaction and persist store changes', async () => { - const dispose = sinon.stub(); - const reaction = sinon.stub().callsFake((track: () => void, effect: () => void) => { - track(); - effect(); + it('should return undefined when manager has no storage', () => { + expect(onChangeListener!({}, new Manager())).to.be.undefined; + }); + + it('should track only persisted attributes and save changes in batches', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { + behaviour: 'include', + attributes: { local: ['items', 'page'] }, + }); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(FeedStore)!; + + runInAction(() => { + store.isFetching = true; + }); + runInAction(() => { + store.sessionStore.counter += 1; + }); + await clock.tickAsync(1000); + + sinon.assert.notCalled(set); + + runInAction(() => { + store.items.push('a'); + }); + runInAction(() => { + store.items.push('b'); + store.page = 2; + }); + + sinon.assert.notCalled(set); + + await clock.tickAsync(99); + + sinon.assert.notCalled(set); + + await clock.tickAsync(1); + + sinon.assert.calledOnceWithExactly(set, { feed: { items: ['a', 'b'], page: 2 } }); + + runInAction(() => { + store.items[0] = 'c'; + }); + await clock.tickAsync(100); + + sinon.assert.calledTwice(set); + sinon.assert.calledWithExactly(set.secondCall, { feed: { items: ['c', 'b'], page: 2 } }); + }); + + it('should persist all observable props by default without traversing other stores', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed'); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(FeedStore)!; + + runInAction(() => { + store.sessionStore.counter += 1; + }); + await clock.tickAsync(100); + + sinon.assert.notCalled(set); + + runInAction(() => { + store.isFetching = true; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { + feed: { items: [], page: 1, isFetching: true }, + }); + }); + + it('should serialize store once per batch', async () => { + const toJSON = sandbox.stub(); + + class CustomStore { + public static isGlobal = true; + + public value = 0; + + constructor() { + makeObservable(this, { value: observable }); + toJSON.callsFake(() => ({ doubled: this.value * 2 })); + } + + public toJSON() { + return toJSON() as Record; + } + } + + Manager.persistStore(CustomStore, 'custom'); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(CustomStore)!; + + sinon.assert.calledOnce(toJSON); + + for (let index = 0; index < 5; index++) { + runInAction(() => { + store.value += 1; + }); + } + + await clock.tickAsync(100); - return dispose; + sinon.assert.calledTwice(toJSON); + sinon.assert.calledOnceWithExactly(set, { custom: { doubled: 10 } }); + }); + + it('should save on every change when persist delay is 0', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { attributes: { local: ['page'] } }); + + const { manager, set } = await createManager({ persistDelay: 0 }); + const store = manager.getStore(FeedStore)!; + + runInAction(() => { + store.page = 2; }); - const toJS = sinon.stub().returns({ fromToJs: true }); - vi.doMock('mobx', () => ({ - reaction, - toJS, - })); + sinon.assert.calledOnceWithExactly(set, { feed: { page: 2 } }); + + runInAction(() => { + store.page = 3; + }); + + sinon.assert.calledTwice(set); + }); + + it('should save immediately on the server', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { attributes: { local: ['page'] } }); + + const { manager, set } = await createManager(); + + manager.isServer = true; + + const store = manager.getStore(FeedStore)!; + + runInAction(() => { + store.page = 2; + }); + + sinon.assert.calledOnceWithExactly(set, { feed: { page: 2 } }); + }); + + it('should save scheduled changes before store is destroyed', async () => { + const onDestroy = sandbox.stub(); + + class DraftStore { + public text = ''; + + public onDestroy = onDestroy; + + constructor() { + makeObservable(this, { text: observable }); + } + } + + Manager.persistStore(DraftStore, 'draft'); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const { relativeStores } = manager.createStores( + [['draft', DraftStore]], + 'parent', + 'context', + 'suspense', + 'Component', + ); + const store = relativeStores.draft as DraftStore; + + runInAction(() => { + store.text = 'hello'; + }); + manager.destroy(); + + sinon.assert.calledOnceWithExactly(set, { draft: { text: 'hello' } }); + expect(set.calledBefore(onDestroy)).to.equal(true); + + await clock.tickAsync(1000); + + sinon.assert.calledOnce(set); + }); + + it('should save scheduled changes when page is hidden', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { attributes: { local: ['page'] } }); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(FeedStore)!; - const { default: onChangeListener } = await import('@src/on-change-listener'); - const listener = onChangeListener!; - const manager = { - options: { shouldDisablePersist: false }, - storage: {}, - savePersistedStore: sinon.stub(), + runInAction(() => { + store.page = 2; + }); + window.dispatchEvent(new Event('pagehide')); + + sinon.assert.calledOnceWithExactly(set, { feed: { page: 2 } }); + + runInAction(() => { + store.page = 3; + }); + Object.defineProperty(document, 'visibilityState', { + configurable: true, + get: () => 'hidden', + }); + document.dispatchEvent(new Event('visibilitychange')); + delete (document as { visibilityState?: string }).visibilityState; + + sinon.assert.calledTwice(set); + sinon.assert.calledWithExactly(set.secondCall, { feed: { page: 3 } }); + + await clock.tickAsync(1000); + + sinon.assert.calledTwice(set); + }); + + it('should stop tracking after dispose', async () => { + class PlainStore { + public libStoreId = 'plain'; + + public value = 1; + + constructor() { + makeObservable(this, { value: observable }); + } + } + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = new PlainStore(); + const dispose = onChangeListener!(store, manager)!; + + runInAction(() => { + store.value = 2; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { plain: { value: 2 } }); + + dispose(); + runInAction(() => { + store.value = 3; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnce(set); + }); + + it('should track props added later and exported props', async () => { + class ProfileStore { + public static isGlobal = true; + + public name = 'a'; + + public settings = { theme: 'light' }; + + public session: SessionStore; + + constructor({ getStore }: IConstructorParams) { + this.session = getStore(SessionStore)!; + + makeObservable(this, { name: observable, settings: observable }); + makeExported(this, { session: 'observable' }); + } + } + + Manager.persistStore(ProfileStore, 'profile'); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(ProfileStore)!; + + runInAction(() => { + extendObservable(store, { avatar: 'x.png' }); + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { + profile: { + name: 'a', + settings: { theme: 'light' }, + session: { counter: 0 }, + avatar: 'x.png', + }, + }); + + runInAction(() => { + (store as ProfileStore & { avatar: string }).avatar = 'y.png'; + store.session.counter = 5; + }); + await clock.tickAsync(100); + + sinon.assert.calledWithExactly(set.secondCall, { + profile: { + name: 'a', + settings: { theme: 'light' }, + session: { counter: 5 }, + avatar: 'y.png', + }, + }); + }); + + it('should save merged init state restored on wakeup', async () => { + class SettingsStore { + public static isGlobal = true; + + public theme = 'light'; + + public lang = 'en'; + + constructor() { + makeObservable(this, { theme: observable, lang: observable }); + } + } + + Manager.persistStore(SettingsStore, 'settings'); + + const clock = sandbox.useFakeTimers(); + const set = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ + local: { get: () => ({ settings: { theme: 'dark' } }), set, flush: sandbox.stub() }, + }), + initState: { settings: { lang: 'de' } }, + }); + + await manager.init(); + + const store = manager.getStore(SettingsStore)!; + + expect(store.theme).to.equal('dark'); + expect(store.lang).to.equal('de'); + + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { settings: { theme: 'dark', lang: 'de' } }); + }); + + it('should keep tracking changes when persist is disabled at runtime', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { attributes: { local: ['page'] } }); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = manager.getStore(FeedStore)!; + + runInAction(() => { + store.page = 2; + }); + manager.options.shouldDisablePersist = true; + + expect(await manager.flushPersist()).to.equal(false); + + runInAction(() => { + store.page = 3; + }); + await clock.tickAsync(100); + + sinon.assert.notCalled(set); + + manager.options.shouldDisablePersist = false; + runInAction(() => { + store.page = 4; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { feed: { page: 4 } }); + }); + + it('should track store created inside action', async () => { + const FeedStore = createFeedStore(); + + Manager.persistStore(FeedStore, 'feed', { attributes: { local: ['page'] } }); + + const clock = sandbox.useFakeTimers(); + const { manager, set } = await createManager(); + const store = runInAction(() => manager.getStore(FeedStore)!); + + runInAction(() => { + store.page = 2; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { feed: { page: 2 } }); + }); + + it('should report store serialization error and keep tracking', async () => { + class ValueStore { + public static isGlobal = true; + + public value = 0; + + constructor() { + makeObservable(this, { value: observable }); + } + + public toJSON() { + if (this.value === 1) { + throw new Error('broken value'); + } + + return { value: this.value }; + } + } + + Manager.persistStore(ValueStore, 'value'); + + const clock = sandbox.useFakeTimers(); + const set = sandbox.stub(); + const err = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set, flush() {} } }), + logger: { log: sandbox.stub(), err, warn: sandbox.stub(), debug: sandbox.stub() } as never, + }); + + await manager.init(); + + const store = manager.getStore(ValueStore)!; + + runInAction(() => { + store.value = 1; + }); + + expect(await manager.flushPersist()).to.equal(false); + sinon.assert.calledOnce(err); + sinon.assert.notCalled(set); + + runInAction(() => { + store.value = 2; + }); + await clock.tickAsync(100); + + sinon.assert.calledOnceWithExactly(set, { value: { value: 2 } }); + }); + + it('should report failed flush', async () => { + const store: IStorePersisted = { + libStoreId: 'broken', + toJSON: () => { + throw new Error('boom'); + }, }; - const store = {}; + const err = sandbox.stub(); + const manager = new Manager({ + storage: new CombinedStorage({ local: { get: () => ({}), set: sandbox.stub(), flush() {} } }), + logger: { log: sandbox.stub(), err, warn: sandbox.stub(), debug: sandbox.stub() } as never, + }); - const result = listener(store, manager as never); + manager.schedulePersist(store); - sinon.assert.calledOnce(reaction); - sinon.assert.calledWith(toJS, store); - sinon.assert.calledWith(manager.savePersistedStore, store); - expect(result).to.equal(dispose); + expect(await manager.flushPersist()).to.equal(false); + sinon.assert.calledOnce(err); + expect(await manager.flushPersist()).to.equal(true); }); }); diff --git a/__tests__/storages/async-storage.ts b/__tests__/storages/async-storage.ts index 02dd053..ac9e255 100644 --- a/__tests__/storages/async-storage.ts +++ b/__tests__/storages/async-storage.ts @@ -70,4 +70,47 @@ describe('AsyncStorage', () => { sinon.assert.calledWith(storage.removeItem, 'stores'); sinon.assert.calledTwice(error); }); + + it('should save assembled json on incremental save and log errors', async () => { + const storage = { + getItem: sandbox.stub().resolves(null), + setItem: sandbox.stub().resolves(), + removeItem: sandbox.stub().resolves(), + }; + const error = sandbox.stub(console, 'error'); + const target = new AsyncStorage({ storage }); + + await target.saveChanges({ value: {}, changes: new Map(), toJSON: () => '{"a":1}' }); + + sinon.assert.calledOnceWithExactly(storage.setItem, 'stores', '{"a":1}'); + + storage.setItem.rejects(new Error('disk')); + await target.saveChanges({ value: {}, changes: new Map(), toJSON: () => '{}' }); + + sinon.assert.calledOnce(error); + }); + + it('should keep overridden set of subclasses on incremental save', async () => { + const storage = { + getItem: sandbox.stub().resolves(null), + setItem: sandbox.stub().resolves(), + removeItem: sandbox.stub().resolves(), + }; + const set = sandbox.stub().resolves(); + + class CustomStorage extends AsyncStorage { + set(value: Record | undefined): Promise { + return set(value) as Promise; + } + } + + await new CustomStorage({ storage }).saveChanges({ + value: { a: 1 }, + changes: new Map(), + toJSON: () => '', + }); + + sinon.assert.calledOnceWithExactly(set, { a: 1 }); + sinon.assert.notCalled(storage.setItem); + }); }); diff --git a/__tests__/storages/combined-storage.ts b/__tests__/storages/combined-storage.ts index 065be79..65edee2 100644 --- a/__tests__/storages/combined-storage.ts +++ b/__tests__/storages/combined-storage.ts @@ -1,6 +1,7 @@ import sinon from 'sinon'; import { afterEach, describe, expect, it } from 'vitest'; import CombinedStorage from '@src/storages/combined-storage'; +import type { IStorageChanges } from '@src/types'; describe('CombinedStorage', () => { const sandbox = sinon.createSandbox(); @@ -196,4 +197,152 @@ describe('CombinedStorage', () => { sinon.assert.calledOnce(flushPrimary); sinon.assert.calledOnce(flushSecondary); }); + + it('should return persisted attributes of store', () => { + const target = new CombinedStorage({ + primary: { get: sandbox.stub(), set: sandbox.stub(), flush: sandbox.stub() }, + secondary: { get: sandbox.stub(), set: sandbox.stub(), flush: sandbox.stub() }, + }); + + expect(target.getStoreAttributes({ libStoreId: 'store' })).to.be.undefined; + expect( + target.getStoreAttributes({ + libStoreId: 'store', + libStorageOptions: { attributes: { primary: ['foo', 'bar'], secondary: ['bar', 'baz'] } }, + }), + ).to.deep.equal(['foo', 'bar', 'baz']); + expect( + target.getStoreAttributes({ + libStoreId: 'store', + libStorageOptions: { attributes: { primary: ['foo'], secondary: ['*'] } }, + }), + ).to.be.undefined; + expect( + target.getStoreAttributes({ libStoreId: 'store', libStorageOptions: { attributes: {} } }), + ).to.deep.equal([]); + }); + + it('should write every changed storage once for many stores', async () => { + const setPrimary = sandbox.stub(); + const setSecondary = sandbox.stub(); + const target = new CombinedStorage({ + primary: { get: () => ({ old: { value: 0 } }), set: setPrimary, flush: sandbox.stub() }, + secondary: { get: () => ({}), set: setSecondary, flush: sandbox.stub() }, + }); + + await target.get(); + await target.saveStoresData([ + [{ libStoreId: 'first' }, { value: 1 }], + [{ libStoreId: 'second' }, { value: 2 }], + [{ libStoreId: 'old' }, { value: 0 }], + ]); + + sinon.assert.calledOnceWithExactly(setPrimary, { + old: { value: 0 }, + first: { value: 1 }, + second: { value: 2 }, + }); + sinon.assert.notCalled(setSecondary); + }); + + it('should compare serialized data to skip unchanged writes', async () => { + const set = sandbox.stub(); + const target = new CombinedStorage({ + primary: { get: () => ({ store: { date: '2020-01-01T00:00:00.000Z' } }), set, flush() {} }, + }); + + await target.get(); + await target.saveStoreData({ libStoreId: 'store' }, { date: new Date('2020-01-01') }); + await target.saveStoreData({ libStoreId: 'empty' }, { skipped: undefined }); + + sinon.assert.notCalled(set); + + await target.saveStoreData({ libStoreId: 'store' }, { date: new Date('2021-01-01') }); + + sinon.assert.calledOnceWithExactly(set, { store: { date: new Date('2021-01-01') } }); + }); + + it('should pass changes to storages with incremental save', async () => { + const saveChanges = sandbox.stub<[IStorageChanges], void>(); + const set = sandbox.stub(); + const loaded = { + 'user-store': { name: 'Émilie "E" 🚀', tags: ['a', 'b'], nested: { deep: [1, { x: null }] } }, + '10': { numeric: true }, + }; + const target = new CombinedStorage({ + primary: { + get: () => JSON.parse(JSON.stringify(loaded)) as typeof loaded, + set, + flush() {}, + saveChanges, + }, + }); + + await target.get(); + await target.saveStoresData([ + [{ libStoreId: 'feed' }, { items: [{ id: 1, text: 'line\nbreak' }], empty: undefined }], + [{ libStoreId: 'user-store' }, { ...loaded['user-store'], name: 'Emily' }], + ]); + + sinon.assert.notCalled(set); + sinon.assert.calledOnce(saveChanges); + + const [{ value, changes, toJSON }] = saveChanges.firstCall.args; + + expect([...changes]).to.deep.equal([ + ['feed', JSON.stringify({ items: [{ id: 1, text: 'line\nbreak' }] })], + ['user-store', JSON.stringify({ ...loaded['user-store'], name: 'Emily' })], + ]); + expect(toJSON()).to.equal(JSON.stringify(value)); + expect(JSON.parse(toJSON())).to.deep.equal({ + ...loaded, + 'user-store': { ...loaded['user-store'], name: 'Emily' }, + feed: { items: [{ id: 1, text: 'line\nbreak' }] }, + }); + }); + + it('should write other storages and reject when storage fails', async () => { + const setSecondary = sandbox.stub(); + const target = new CombinedStorage({ + primary: { + get: () => ({}), + set: () => { + throw new Error('quota'); + }, + flush() {}, + }, + secondary: { get: () => ({}), set: setSecondary, flush() {} }, + }); + + await target.get(); + + const result = target.saveStoreData( + { + libStoreId: 'store', + libStorageOptions: { + behaviour: 'include', + attributes: { primary: ['a'], secondary: ['b'] }, + }, + }, + { a: 1, b: 2 }, + ); + + sinon.assert.calledOnceWithExactly(setSecondary, { store: { b: 2 } }); + await expect(result).rejects.toThrow('quota'); + }); + + it('should save other stores and reject when store data is not serializable', async () => { + const set = sandbox.stub(); + const target = new CombinedStorage({ primary: { get: () => ({}), set, flush() {} } }); + + await target.get(); + + await expect( + target.saveStoresData([ + [{ libStoreId: 'broken' }, { value: 1n }], + [{ libStoreId: 'valid' }, { value: 1 }], + ]), + ).rejects.toThrow(TypeError); + sinon.assert.calledOnceWithExactly(set, { valid: { value: 1 } }); + }); }); diff --git a/__tests__/storages/cookie-storage.ts b/__tests__/storages/cookie-storage.ts index 7712dc9..0bde000 100644 --- a/__tests__/storages/cookie-storage.ts +++ b/__tests__/storages/cookie-storage.ts @@ -65,4 +65,22 @@ describe('CookieStorage', () => { sinon.assert.calledWith(storage.set, 'stores', '{"foo":"bar"}', cookieAttr); sinon.assert.calledWith(storage.remove, 'stores', cookieAttr); }); + + it('should save assembled json and warn once about big cookie', () => { + const storage = { get: sandbox.stub(), set: sandbox.stub(), remove: sandbox.stub() }; + const warn = sandbox.stub(console, 'warn'); + const target = new CookieStorage({ storage, cookieAttr: { path: '/' } }); + const big = JSON.stringify({ store: { value: 'x'.repeat(5000) } }); + + target.saveChanges({ value: {}, changes: new Map(), toJSON: () => '{"a":1}' }); + + sinon.assert.calledOnceWithExactly(storage.set, 'stores', '{"a":1}', { path: '/' }); + sinon.assert.notCalled(warn); + + target.saveChanges({ value: {}, changes: new Map(), toJSON: () => big }); + target.set({ store: { value: 'x'.repeat(5000) } }); + + sinon.assert.calledOnce(warn); + sinon.assert.calledWith(storage.set.thirdCall, 'stores', big, { path: '/' }); + }); }); diff --git a/__tests__/storages/indexed-db-storage.ts b/__tests__/storages/indexed-db-storage.ts new file mode 100644 index 0000000..e7d7e8f --- /dev/null +++ b/__tests__/storages/indexed-db-storage.ts @@ -0,0 +1,212 @@ +import { IDBFactory } from 'fake-indexeddb'; +import { makeObservable, observable, runInAction } from 'mobx'; +import sinon from 'sinon'; +import { afterEach, describe, expect, it } from 'vitest'; +import Manager from '@src/manager'; +import CombinedStorage from '@src/storages/combined-storage'; +import IndexedDBStorage from '@src/storages/indexed-db-storage'; +import LocalStorage from '@src/storages/local-storage'; + +describe('IndexedDBStorage', () => { + const sandbox = sinon.createSandbox(); + + afterEach(() => { + sandbox.restore(); + Manager.getPersistedStoresIds().clear(); + }); + + /** + * In-memory localStorage + */ + const createLocalStorage = (initial: Record = {}) => { + const data = new Map(Object.entries(initial)); + + return { + data, + storage: { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value), + removeItem: (key: string) => void data.delete(key), + } as unknown as Storage, + }; + }; + + it('should save every store as own record', async () => { + const indexedDB = new IDBFactory(); + const target = new CombinedStorage({ local: new IndexedDBStorage({ indexedDB }) }); + + expect(await target.get()).to.deep.equal({ local: {} }); + + await target.saveStoresData([ + [{ libStoreId: 'feed' }, { items: [1, 2] }], + [{ libStoreId: 'settings' }, { theme: 'dark' }], + ]); + await target.saveStoreData({ libStoreId: 'feed' }, { items: [3] }); + + const restored = new IndexedDBStorage({ indexedDB }); + + expect(await restored.get()).to.deep.equal({ + feed: { items: [3] }, + settings: { theme: 'dark' }, + }); + }); + + it('should migrate legacy data once and keep it by default', async () => { + const indexedDB = new IDBFactory(); + const { data, storage } = createLocalStorage({ stores: '{"feed":{"items":[1]}}' }); + const migrateFrom = new LocalStorage({ storage }); + + expect(await new IndexedDBStorage({ indexedDB, migrateFrom }).get()).to.deep.equal({ + feed: { items: [1] }, + }); + expect(data.has('stores')).to.equal(true); + + data.set('stores', '{"feed":{"items":["stale"]}}'); + + expect(await new IndexedDBStorage({ indexedDB, migrateFrom }).get()).to.deep.equal({ + feed: { items: [1] }, + }); + }); + + it('should remove legacy data after migration when requested', async () => { + const indexedDB = new IDBFactory(); + const { data, storage } = createLocalStorage({ stores: '{"feed":{"items":[1]}}' }); + const target = new IndexedDBStorage({ + indexedDB, + dbName: 'app', + migrateFrom: new LocalStorage({ storage }), + shouldRemoveMigrated: true, + }); + + expect(await target.get()).to.deep.equal({ feed: { items: [1] } }); + expect(data.size).to.equal(0); + expect(await new IndexedDBStorage({ indexedDB, dbName: 'app' }).get()).to.deep.equal({ + feed: { items: [1] }, + }); + }); + + it('should return legacy data and retry migration on the next save', async () => { + const indexedDB = new IDBFactory(); + const { storage } = createLocalStorage({ + stores: '{"feed":{"items":[1]},"user":{"name":"a"}}', + }); + const error = sandbox.stub(console, 'error'); + const target = new IndexedDBStorage({ indexedDB, migrateFrom: new LocalStorage({ storage }) }); + const write = sandbox.stub(target as unknown as { write: () => Promise }, 'write'); + + write.callThrough(); + write.onFirstCall().rejects(new Error('quota exceeded')); + + expect(await target.get()).to.deep.equal({ feed: { items: [1] }, user: { name: 'a' } }); + + await target.saveChanges({ + value: { feed: { items: [2] }, user: { name: 'a' } }, + changes: new Map([['feed', '{"items":[2]}']]), + toJSON: () => '', + }); + + expect(await new IndexedDBStorage({ indexedDB }).get()).to.deep.equal({ + feed: { items: [2] }, + user: { name: 'a' }, + }); + sinon.assert.calledOnce(error); + }); + + it('should reopen database after connection is closed', async () => { + const indexedDB = new IDBFactory(); + const target = new IndexedDBStorage({ indexedDB }); + + await target.get(); + + const { db } = target as unknown as { db: IDBDatabase }; + + db.close(); + db.onclose?.(new Event('close')); + + await target.saveChanges({ + value: {}, + changes: new Map([['feed', '{"items":[1]}']]), + toJSON: () => '', + }); + + expect(await new IndexedDBStorage({ indexedDB }).get()).to.deep.equal({ + feed: { items: [1] }, + }); + }); + + it('should replace all stores on set and clear everything on flush', async () => { + const indexedDB = new IDBFactory(); + const { data, storage } = createLocalStorage({ stores: '{"legacy":{}}' }); + const target = new IndexedDBStorage({ indexedDB, migrateFrom: new LocalStorage({ storage }) }); + + await target.get(); + await target.set({ b: { value: 1 } }); + + expect(await new IndexedDBStorage({ indexedDB }).get()).to.deep.equal({ b: { value: 1 } }); + + await target.flush(); + + expect(await new IndexedDBStorage({ indexedDB }).get()).to.deep.equal({}); + expect(data.size).to.equal(0); + }); + + it('should use legacy storage when IndexedDB is not available', async () => { + const { data, storage } = createLocalStorage({ stores: '{"feed":{"items":[1]}}' }); + const target = new CombinedStorage({ + local: new IndexedDBStorage({ migrateFrom: new LocalStorage({ storage }) }), + }); + + // jsdom doesn't implement IndexedDB + expect(globalThis.indexedDB).to.be.undefined; + expect(await target.get()).to.deep.equal({ local: { feed: { items: [1] } } }); + + await target.saveStoreData({ libStoreId: 'feed' }, { items: [2] }); + + expect(data.get('stores')).to.equal('{"feed":{"items":[2]}}'); + }); + + it('should return empty object when database cannot be opened', async () => { + const error = sandbox.stub(console, 'error'); + const indexedDB = new IDBFactory(); + + sandbox.stub(indexedDB, 'open').throws(new Error('denied')); + + const target = new IndexedDBStorage({ indexedDB }); + + expect(await target.get()).to.deep.equal({}); + await target.saveChanges({ value: {}, changes: new Map([['a', '{}']]), toJSON: () => '' }); + sinon.assert.calledOnce(error); + }); + + it('should persist manager stores', async () => { + class SettingsStore { + public static isGlobal = true; + + public theme = 'light'; + + constructor() { + makeObservable(this, { theme: observable }); + } + } + + Manager.persistStore(SettingsStore, 'settings'); + + const indexedDB = new IDBFactory(); + const manager = new Manager({ + storage: new CombinedStorage({ local: new IndexedDBStorage({ indexedDB }) }), + }); + + await manager.init(); + + const store = manager.getStore(SettingsStore)!; + + runInAction(() => { + store.theme = 'dark'; + }); + + expect(await manager.flushPersist()).to.equal(true); + expect(await new IndexedDBStorage({ indexedDB }).get()).to.deep.equal({ + settings: { theme: 'dark' }, + }); + }); +}); diff --git a/__tests__/storages/key-value-storage.ts b/__tests__/storages/key-value-storage.ts new file mode 100644 index 0000000..aa3f7cc --- /dev/null +++ b/__tests__/storages/key-value-storage.ts @@ -0,0 +1,272 @@ +import sinon from 'sinon'; +import { afterEach, describe, expect, it } from 'vitest'; +import AsyncStorage from '@src/storages/async-storage'; +import CombinedStorage from '@src/storages/combined-storage'; +import KeyValueStorage from '@src/storages/key-value-storage'; +import LocalStorage from '@src/storages/local-storage'; + +describe('KeyValueStorage', () => { + const sandbox = sinon.createSandbox(); + + afterEach(() => { + sandbox.restore(); + }); + + /** + * In-memory adapter + */ + const createAdapter = (initial: Record = {}, isAsync = false) => { + const data = new Map(Object.entries(initial)); + const wrap = (value: T) => (isAsync ? Promise.resolve(value) : value); + + return { + data, + getItem: sandbox.spy((key: string) => wrap(data.get(key) ?? null)), + setItem: sandbox.spy((key: string, value: string) => wrap(void data.set(key, value))), + removeItem: sandbox.spy((key: string) => wrap(void data.delete(key))), + }; + }; + + it('should save every store under own key', async () => { + const adapter = createAdapter(); + const target = new CombinedStorage({ local: new KeyValueStorage({ storage: adapter }) }); + + expect(await target.get()).to.deep.equal({ local: {} }); + + await target.saveStoresData([ + [{ libStoreId: 'feed' }, { items: [1, 2] }], + [{ libStoreId: 'settings' }, { theme: 'dark' }], + ]); + + expect(Object.fromEntries(adapter.data)).to.deep.equal({ + 'stores:feed': '{"items":[1,2]}', + 'stores:settings': '{"theme":"dark"}', + 'stores-keys': '["feed","settings"]', + }); + + adapter.setItem.resetHistory(); + await target.saveStoreData({ libStoreId: 'feed' }, { items: [3] }); + + sinon.assert.calledOnceWithExactly(adapter.setItem, 'stores:feed', '{"items":[3]}'); + + const restored = new CombinedStorage({ local: new KeyValueStorage({ storage: adapter }) }); + + expect(await restored.get()).to.deep.equal({ + local: { feed: { items: [3] }, settings: { theme: 'dark' } }, + }); + }); + + it('should skip broken store and missing values', async () => { + const adapter = createAdapter( + { + 'app-keys': '["broken","missing","valid"]', + 'app:broken': '{', + 'app:valid': '{"a":1}', + }, + true, + ); + const error = sandbox.stub(console, 'error'); + + expect(await new KeyValueStorage({ storage: adapter, prefix: 'app' }).get()).to.deep.equal({ + valid: { a: 1 }, + }); + sinon.assert.calledOnce(error); + }); + + it('should migrate legacy data once and keep it by default', async () => { + const adapter = createAdapter({ stores: '{"feed":{"items":[1]},"user":{"name":"a"}}' }, true); + // async adapter + const legacy = new AsyncStorage({ storage: adapter as never }); + const target = new KeyValueStorage({ storage: adapter, migrateFrom: legacy }); + + expect(await target.get()).to.deep.equal({ feed: { items: [1] }, user: { name: 'a' } }); + expect(adapter.data.get('stores:feed')).to.equal('{"items":[1]}'); + expect(adapter.data.get('stores-keys')).to.equal('["feed","user"]'); + expect(adapter.data.has('stores')).to.equal(true); + + adapter.data.set('stores', '{"feed":{"items":["stale"]}}'); + + expect( + await new KeyValueStorage({ storage: adapter, migrateFrom: legacy }).get(), + ).to.deep.equal({ feed: { items: [1] }, user: { name: 'a' } }); + }); + + it('should remove legacy data after migration when requested', async () => { + const adapter = createAdapter({ stores: '{"feed":{"items":[1]}}' }); + const target = new KeyValueStorage({ + storage: adapter, + prefix: 'v2', + migrateFrom: new LocalStorage({ storage: adapter as unknown as Storage }), + shouldRemoveMigrated: true, + }); + + expect(await target.get()).to.deep.equal({ feed: { items: [1] } }); + expect(Object.fromEntries(adapter.data)).to.deep.equal({ + 'v2:feed': '{"items":[1]}', + 'v2-keys': '["feed"]', + }); + }); + + it('should return legacy data and retry migration on the next save', async () => { + const adapter = createAdapter({ stores: '{"feed":{"items":[1]},"user":{"name":"a"}}' }); + const error = sandbox.stub(console, 'error'); + const { setItem } = adapter; + let isFull = true; + + adapter.setItem = sandbox.spy((key: string, value: string) => { + if (isFull) { + throw new Error('disk is full'); + } + + return setItem(key, value); + }); + + const target = new KeyValueStorage({ + storage: adapter, + migrateFrom: new LocalStorage({ storage: adapter as unknown as Storage }), + shouldRemoveMigrated: true, + }); + + expect(await target.get()).to.deep.equal({ feed: { items: [1] }, user: { name: 'a' } }); + expect([...adapter.data.keys()]).to.deep.equal(['stores']); + + isFull = false; + await target.saveChanges({ + value: { feed: { items: [2] }, user: { name: 'a' } }, + changes: new Map([['feed', '{"items":[2]}']]), + toJSON: () => '', + }); + + expect(Object.fromEntries(adapter.data)).to.deep.equal({ + 'stores:feed': '{"items":[2]}', + 'stores:user': '{"name":"a"}', + 'stores-keys': '["feed","user"]', + }); + sinon.assert.calledOnce(error); + }); + + it('should replace all stores on set and remove everything on flush', async () => { + const adapter = createAdapter({ + 'stores-keys': '["a","b"]', + 'stores:a': '{}', + 'stores:b': '{}', + 'stores:orphan': '{}', + stores: '{"legacy":{}}', + }); + const target = new KeyValueStorage({ + storage: adapter, + migrateFrom: new LocalStorage({ storage: adapter as unknown as Storage }), + }); + + await target.get(); + await target.set({ b: { value: 1 }, c: { value: 2 } }); + + expect(Object.fromEntries(adapter.data)).to.deep.equal({ + 'stores-keys': '["b","c"]', + 'stores:b': '{"value":1}', + 'stores:c': '{"value":2}', + 'stores:orphan': '{}', + stores: '{"legacy":{}}', + }); + + await target.flush(); + + expect(Object.fromEntries(adapter.data)).to.deep.equal({ 'stores:orphan': '{}' }); + }); + + it('should keep stores list when it cannot be read', async () => { + const adapter = createAdapter({ + 'stores-keys': '["feed","settings"]', + 'stores:feed': '{"items":[1]}', + 'stores:settings': '{"theme":"dark"}', + }); + const error = sandbox.stub(console, 'error'); + const target = new KeyValueStorage({ storage: adapter }); + + adapter.getItem = sandbox.spy((key: string): string | null => { + throw new Error(`read failed: ${key}`); + }); + + expect(await target.get()).to.deep.equal({}); + + await target.saveChanges({ + value: {}, + changes: new Map([['profile', '{"name":"a"}']]), + toJSON: () => '', + }); + + expect(Object.fromEntries(adapter.data)).to.deep.equal({ + 'stores-keys': '["feed","settings"]', + 'stores:feed': '{"items":[1]}', + 'stores:settings': '{"theme":"dark"}', + 'stores:profile': '{"name":"a"}', + }); + sinon.assert.called(error); + }); + + it('should add stores to saved list without reading stores first', async () => { + const adapter = createAdapter({ 'stores-keys': '["feed"]', 'stores:feed': '{}' }, true); + + await new KeyValueStorage({ storage: adapter }).saveChanges({ + value: {}, + changes: new Map([['settings', '{}']]), + toJSON: () => '', + }); + + expect(adapter.data.get('stores-keys')).to.equal('["feed","settings"]'); + }); + + it('should replace broken stores list on the next save', async () => { + const adapter = createAdapter({ 'stores-keys': '{', 'stores:feed': '{}' }); + const error = sandbox.stub(console, 'error'); + const target = new KeyValueStorage({ storage: adapter }); + + expect(await target.get()).to.deep.equal({}); + + await target.saveChanges({ + value: {}, + changes: new Map([['settings', '{}']]), + toJSON: () => '', + }); + + expect(adapter.data.get('stores-keys')).to.equal('["settings"]'); + sinon.assert.calledOnce(error); + }); + + it('should restore other stores when one of them cannot be read', async () => { + const adapter = createAdapter({ + 'stores-keys': '["feed","settings"]', + 'stores:feed': '{"items":[1]}', + 'stores:settings': '{"theme":"dark"}', + }); + const error = sandbox.stub(console, 'error'); + const { getItem } = adapter; + + adapter.getItem = sandbox.spy((key: string) => { + if (key === 'stores:feed') { + throw new Error('read failed'); + } + + return getItem(key); + }); + + expect(await new KeyValueStorage({ storage: adapter }).get()).to.deep.equal({ + settings: { theme: 'dark' }, + }); + sinon.assert.calledOnce(error); + }); + + it('should return empty object when storage fails', async () => { + const error = sandbox.stub(console, 'error'); + const target = new KeyValueStorage({ + storage: { + getItem: () => Promise.reject(new Error('boom')), + setItem: sandbox.stub(), + removeItem: sandbox.stub(), + }, + }); + + expect(await target.get()).to.deep.equal({}); + sinon.assert.calledOnce(error); + }); +}); diff --git a/__tests__/storages/local-storage.ts b/__tests__/storages/local-storage.ts index 4a034d1..f1b75b3 100644 --- a/__tests__/storages/local-storage.ts +++ b/__tests__/storages/local-storage.ts @@ -67,4 +67,41 @@ describe('LocalStorage', () => { sinon.assert.calledWith(storage.setItem, 'stores', '{"foo":"bar"}'); sinon.assert.calledWith(storage.removeItem, 'stores'); }); + + it('should save assembled json on incremental save', () => { + const storage = { + getItem: sandbox.stub(), + removeItem: sandbox.stub(), + setItem: sandbox.stub(), + }; + const target = new LocalStorage({ storage: storage as unknown as Storage }); + + target.saveChanges({ value: { a: {} }, changes: new Map(), toJSON: () => '{"a":{}}' }); + + sinon.assert.calledOnceWithExactly(storage.setItem, 'stores', '{"a":{}}'); + }); + + it('should keep overridden set of subclasses on incremental save', () => { + const storage = { + getItem: sandbox.stub(), + removeItem: sandbox.stub(), + setItem: sandbox.stub(), + }; + const toJSON = sandbox.stub(); + + class EncodedStorage extends LocalStorage { + set(value: Record | undefined): void { + this.storage.setItem(this.globalKey, btoa(JSON.stringify(value))); + } + } + + new EncodedStorage({ storage: storage as unknown as Storage }).saveChanges({ + value: { a: 1 }, + changes: new Map(), + toJSON, + }); + + sinon.assert.notCalled(toJSON); + sinon.assert.calledOnceWithExactly(storage.setItem, 'stores', btoa('{"a":1}')); + }); }); diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 31a9724..daccc08 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -259,7 +259,12 @@ Runtime behavior: - it sets `store.libStoreId = id` - it adds default `wakeup` and `addOnChangeListener` handlers if the store does not already define them - `CombinedStorage` loads all registered storages on `manager.init()` -- store changes are saved through `manager.savePersistedStore(...)` +- the default listener tracks only persisted fields (not other stores referenced from the store) and queues the store through `manager.schedulePersist(...)` +- queued stores are serialized once per `options.persistDelay` (default `100` ms) and each storage is written once; unchanged stores are skipped +- the queue is flushed when the page is hidden, before a store is destroyed, on `manager.destroy()` and on `manager.flushPersist()`; on the server and with `persistDelay: 0` every change is saved immediately +- React Native has no page events: call `manager.flushPersist()` when `AppState` leaves `active` +- tests that read a storage right after a change: `await manager.flushPersist()` first, or use `persistDelay: 0` +- `manager.savePersistedStore(...)` saves one store immediately, without batching `IPersistOptions`: @@ -375,7 +380,13 @@ The root export is the safest contract. Subpath imports are available in the pub - `touchedStores(stores: TStores): void` - `getStoreState(store: TAnyStore, withNotExported?: boolean): Record` - `toJSON(ids?: string[], isIncludeExported?: boolean): Record` + - `getPersistState(store: IStorePersisted): Record` - `savePersistedStore(store: IStorePersisted): Promise` + - `schedulePersist(store: IStorePersisted, getState?: () => Record | undefined): void` + - `flushPersist(): Promise` +- Key options (`IManagerOptions`): + - `shouldDisablePersist?: boolean` + - `persistDelay?: number` (default `100`, `0` saves on every change) - Key static methods: - `Manager.get(): Manager` - `Manager.getPersistedStoresIds(): Set` @@ -447,7 +458,7 @@ The root export is the safest contract. Subpath imports are available in the pub `onChangeListener` - Signature: `(store, manager) => (() => void) | undefined` -- Purpose: default persisted-store change subscription using MobX `reaction(...)` +- Purpose: default persisted-store change subscription using MobX `reaction(...)`; tracks only persisted fields and schedules batched saves #### React Context Exports @@ -506,6 +517,7 @@ These are re-exported from `src/types.ts` at the package root: - `IManagerParams` - `TWakeup` - `IStorage` +- `IStorageChanges` - `IManagerOptions` - `TAnyStore` - `TStores` @@ -603,6 +615,25 @@ The package build preserves module paths under `src/`, so these imports are avai - default export `AsyncStorage` +`@lomray/react-mobx-manager/storages/key-value-storage` + +- `IKeyValueAdapter`, `IKeyValueStorageOptions` +- default export `KeyValueStorage` +- every store under its own key (`stores:` plus the `stores-keys` index), for AsyncStorage, MMKV or any `getItem`/`setItem`/`removeItem` backend +- options: `storage`, `prefix?`, `migrateFrom?: IStorage`, `shouldRemoveMigrated?: boolean` + +`@lomray/react-mobx-manager/storages/indexed-db-storage` + +- `IIndexedDBStorageOptions` +- default export `IndexedDBStorage` +- every store as its own IndexedDB record, falls back to `migrateFrom` when IndexedDB is not available +- options: `dbName?`, `indexedDB?: IDBFactory`, `migrateFrom?: IStorage`, `shouldRemoveMigrated?: boolean` + +`@lomray/react-mobx-manager/storages/store-records-storage` + +- `IStoreRecordsStorageOptions`, `serializeStores` +- default export `StoreRecordsStorage`: abstract base of `KeyValueStorage` and `IndexedDBStorage` (migration from `migrateFrom`, retried on the next save when it fails) + `@lomray/react-mobx-manager/storages/combined-storage` - default export `CombinedStorage` @@ -611,7 +642,10 @@ The package build preserves module paths under `src/`, so these imports are avai - `flush()` - `set(value, storageId?)` - `getStoreData(store)` + - `getStoreAttributes(store)` - `saveStoreData(store, data)` + - `saveStoresData(entries)`: many stores at once, every changed storage written once +- calls the optional `IStorage.saveChanges({ value, changes, toJSON })` instead of `set` when a storage defines it #### Vite Plugin diff --git a/docs/api/manager.md b/docs/api/manager.md index ee0dc1b..5f4e706 100644 --- a/docs/api/manager.md +++ b/docs/api/manager.md @@ -12,6 +12,21 @@ new Manager({ }); ``` +## Options + +```ts +new Manager({ + options: { + // don't create persist listeners and don't save anything + shouldDisablePersist: false, + // batch persisted store changes and save them at most once per 100 ms + persistDelay: 100, + }, +}); +``` + +- `persistDelay` (default `100`): changes of persisted stores are collected and written at most once per this delay. `0` saves on every change, as older versions did. On the server (`manager.isServer`) changes are always saved immediately. In tests that read a storage right after a change, `await manager.flushPersist()` first or use `0`. + ## Important methods ### `init(): Promise` @@ -38,9 +53,31 @@ Moves relative stores from `init` to `touched` status when they are passed deepe Returns serializable store state. +### `getPersistState(store)` + +Returns the state of a persisted store that goes to storages: only attributes listed in `persistStore(...)` options (all exported attributes by default). Uses `store.toJSON()` when the store defines it. + ### `savePersistedStore(store)` -Saves persisted store state through configured storage. +Saves persisted store state through configured storage right now, without batching. + +### `schedulePersist(store, getState?)` + +Queues saving of a persisted store. The default change listener calls it: all stores queued during `persistDelay` are written together, each storage once. + +### `flushPersist(): Promise` + +Writes queued changes right now and resolves when storage writes are finished (`false` if something failed or persist is disabled). + +The manager flushes automatically when the browser page is hidden (`pagehide`, `visibilitychange`), before a store is destroyed and on `destroy()`. Call it yourself when the environment has no page events, e.g. when a React Native app goes to background: + +```ts +AppState.addEventListener('change', (state) => { + if (state !== 'active') { + void manager.flushPersist(); + } +}); +``` ### `destroy()` diff --git a/docs/examples/recipes.md b/docs/examples/recipes.md index 418c57d..5c3b8d8 100644 --- a/docs/examples/recipes.md +++ b/docs/examples/recipes.md @@ -291,6 +291,18 @@ export default Manager.persistStore(UserStore, 'user'); Use persistence for durable state. Avoid using it for temporary screen state, loading flags, or one-off UI flows. +When a persisted store also has short-lived fields, keep them out of storage: list the persisted fields explicitly, or mark the others as excluded. Changes of fields that are not persisted don't trigger any persist work. + +```ts +export default Manager.persistStore(FeedStore, 'feed', { + behaviour: 'include', + attributes: { local: ['items', 'filters'] }, +}); + +// or inside the store constructor +makeExported(this, { isFetching: 'excluded' }); +``` + ## Persist a store across multiple storages ```ts @@ -382,6 +394,137 @@ This setup is useful when: - other fields fit better in local storage - SSR or stream rendering must hydrate the manager before the app starts +## How persisted changes are saved + +- the change listener tracks only persisted fields of the store; other stores referenced from its fields are not traversed +- changes are batched: all persisted stores changed during `options.persistDelay` (100 ms by default) are serialized once and every storage gets one write +- a store whose persisted state didn't change is not written again +- queued changes are written right away when the page is hidden, before a store is destroyed, on `manager.destroy()` and on `manager.flushPersist()` +- on the server changes are saved immediately; `persistDelay: 0` does the same in the browser + +```ts +const manager = new Manager({ + storage, + options: { persistDelay: 300 }, +}); +``` + +React Native has no page events, so flush when the app goes to background: + +```ts +import { AppState } from 'react-native'; + +AppState.addEventListener('change', (state) => { + if (state !== 'active') { + void manager.flushPersist(); + } +}); +``` + +Tests that read a storage right after a store change should wait for the write: + +```ts +store.setTheme('dark'); + +await manager.flushPersist(); + +expect(JSON.parse(localStorage.getItem('stores') ?? '{}')).toMatchObject({ + settings: { theme: 'dark' }, +}); +``` + +or create the test manager with `options: { persistDelay: 0 }`. + +## Save every store under its own key + +`LocalStorage`, `SessionStorage`, `CookieStorage` and `AsyncStorage` keep all persisted stores in one value, so every save rewrites all of them. With many or large stores use `KeyValueStorage`: each store is a separate key and a save writes only the changed stores. It also keeps values small, which matters for Android AsyncStorage, where a single large row (around 2 MB) may fail to load. + +```ts +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { Manager } from '@lomray/react-mobx-manager'; +import MobxAsyncStorage from '@lomray/react-mobx-manager/storages/async-storage'; +import CombinedStorage from '@lomray/react-mobx-manager/storages/combined-storage'; +import KeyValueStorage from '@lomray/react-mobx-manager/storages/key-value-storage'; + +const manager = new Manager({ + storage: new CombinedStorage({ + local: new KeyValueStorage({ + storage: AsyncStorage, + // stores saved by the previous setup are moved on the first start + migrateFrom: new MobxAsyncStorage({ storage: AsyncStorage }), + }), + }), +}); +``` + +Any key-value backend with `getItem`, `setItem` and `removeItem` works, sync or async. For example, MMKV: + +```ts +import { createMMKV } from 'react-native-mmkv'; + +const mmkv = createMMKV(); + +const storage = new KeyValueStorage({ + storage: { + getItem: (key) => mmkv.getString(key), + setItem: (key, value) => mmkv.set(key, value), + removeItem: (key) => mmkv.remove(key), + }, +}); +``` + +What to know: + +- stores are saved as `stores:` plus the `stores-keys` index; change the prefix with `prefix` +- `migrateFrom` is read only when there is no index yet, i.e. on the first start with the new storage +- migrated data is kept by default, so an app version rollback still finds it; pass `shouldRemoveMigrated: true` to remove it right after migration +- if the migrated stores can't be saved, the app still starts with the old data, and all stores are saved again on the next change +- `flush()` removes the stores, the index and the `migrateFrom` data + +## IndexedDB storage for the web + +`IndexedDBStorage` saves every store as its own record. Writes are asynchronous and don't block the main thread, and the quota is much larger than the ~5 MB of `localStorage`. + +```ts +import CombinedStorage from '@lomray/react-mobx-manager/storages/combined-storage'; +import IndexedDBStorage from '@lomray/react-mobx-manager/storages/indexed-db-storage'; +import LocalStorage from '@lomray/react-mobx-manager/storages/local-storage'; + +const storage = new CombinedStorage({ + local: new IndexedDBStorage({ + // moved on the first start and used when IndexedDB is not available + migrateFrom: new LocalStorage(), + }), +}); +``` + +- options: `dbName` (default `'mobx-manager'`), `migrateFrom`, `shouldRemoveMigrated`, `indexedDB` (custom factory, e.g. for tests) +- state is restored asynchronously on `manager.init()`: wait for it before rendering persisted stores, e.g. with `shouldInit` on `StoreManagerProvider` +- when IndexedDB can't be opened (private mode restrictions, old browsers), the storage reads and writes `migrateFrom` + +## Custom storage with incremental saves + +A storage only needs `get`, `set` and `flush`. `set` receives all stores of that storage on every save. Implement the optional `saveChanges` to write only what changed: + +```ts +import type { IStorage } from '@lomray/react-mobx-manager'; + +const storage: IStorage = { + get: () => readAllStores(), + set: (value) => writeAllStores(value), + flush: () => removeAllStores(), + // called instead of `set` when defined + saveChanges: ({ changes, value, toJSON }) => { + // changes: store id => store state JSON, only stores changed in this batch + // value: all stores of this storage, the same object `set` receives + // toJSON(): JSON of `value`, assembled from already serialized stores + changes.forEach((json, storeId) => writeStore(storeId, json)); + }, +}; +``` + +Built-in single-value storages use `toJSON()`, so unchanged stores are not serialized again. Keep cookie storage for small fields only: browsers ignore cookies larger than ~4 KB, and `CookieStorage` warns once in the console when the value is bigger. + ## Suspense query pattern for SSR and stream rendering If your project wraps the internal suspense helper with something like `createSuspenseQuery(this)`, the usage can look like this: diff --git a/package-lock.json b/package-lock.json index be337aa..866d567 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "@types/sinon": "^22.0.0", "@vitest/coverage-v8": "^5.0.1", "eslint": "^10.11.0", + "fake-indexeddb": "^6.2.5", "globals": "^17.12.0", "husky": "^9.1.7", "jsdom": "^30.1.0", @@ -6695,6 +6696,16 @@ "node": ">=12.0.0" } }, + "node_modules/fake-indexeddb": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz", + "integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", diff --git a/package.json b/package.json index 377b4de..18ce766 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "@types/sinon": "^22.0.0", "@vitest/coverage-v8": "^5.0.1", "eslint": "^10.11.0", + "fake-indexeddb": "^6.2.5", "globals": "^17.12.0", "husky": "^9.1.7", "jsdom": "^30.1.0", diff --git a/src/deep-compare.ts b/src/deep-compare.ts index 718daeb..46e0804 100644 --- a/src/deep-compare.ts +++ b/src/deep-compare.ts @@ -11,15 +11,14 @@ const deepCompare = (obj1: unknown, obj2: unknown): boolean => { } const keys1 = Object.keys(obj1); - const keys2 = Object.keys(obj2); - if (keys1.length !== keys2.length) { + if (keys1.length !== Object.keys(obj2).length) { return false; } for (const key of keys1) { if ( - !keys2.includes(key) || + !Object.prototype.hasOwnProperty.call(obj2, key) || !deepCompare((obj1 as Record)[key], (obj2 as Record)[key]) ) { return false; diff --git a/src/manager.ts b/src/manager.ts index d83014f..23b0303 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -1,16 +1,11 @@ import EventManager from '@lomray/event-manager'; -import { isObservableProp, toJS } from 'mobx'; import { ROOT_CONTEXT_ID } from './constants'; import deepMerge from './deep-merge'; import Events from './events'; import Logger from './logger'; -import { - isPropExcludedFromExport, - isPropObservableExported, - isPropSimpleExported, -} from './make-exported'; import onChangeListener from './on-change-listener'; -import CombinedStorage from './storages/combined-storage'; +import CombinedStorage, { type TStoreStateEntry } from './storages/combined-storage'; +import { getObservableProps, getPersistState } from './store-state'; import StoreStatus from './store-status'; import type { IConstructableStore, @@ -27,6 +22,8 @@ import type { } from './types'; import wakeup from './wakeup'; +const PERSIST_ERROR = 'Failed to persist stores: '; + /** * Mobx stores manager */ @@ -76,8 +73,33 @@ class Manager { shouldDisablePersist: false, shouldRemoveInitState: true, failedCreationStrategy: 'empty', + persistDelay: 100, }; + /** + * Persisted stores waiting to be saved: store => state getter + * @see schedulePersist + */ + protected readonly persistQueue = new Map< + IStorePersisted, + (() => Record | undefined) | undefined + >(); + + /** + * Scheduled persist flush + */ + protected persistTimer?: ReturnType; + + /** + * Storage writes in progress + */ + protected readonly persistWrites = new Set>(); + + /** + * Remove page lifecycle listeners + */ + protected removePageListeners?: () => void; + /** * Suspense stores relations * @see withStores @@ -89,14 +111,14 @@ class Manager { */ protected readonly logger: Logger; - /** - * @constructor - */ /** * Detect server side: stores live until the manager is destroyed, no timers are armed */ public isServer = typeof window === 'undefined'; + /** + * @constructor + */ public constructor({ initState, storesParams, storage, options, logger }: IManagerParams = {}) { this.initState = initState || {}; this.storesParams = storesParams || {}; @@ -537,6 +559,11 @@ class Manager { this.removeRelationContext(store.libStoreContextId!); + // save scheduled changes before the store stops tracking them + if (this.persistQueue.has(store)) { + void this.flushPersist(); + } + if ('onDestroy' in store) { store.onDestroy?.(); } @@ -591,6 +618,12 @@ class Manager { this.removeStore(store); } + if (this.persistQueue.size > 0) { + void this.flushPersist(); + } + + this.removePageListeners?.(); + this.removePageListeners = undefined; this.storesRelations.clear(); this.suspenseRelations.clear(); } @@ -676,7 +709,14 @@ class Manager { } /** - * Save persisted store state to provided storage + * Get store state saved by persist: only attributes of storages + */ + public getPersistState(store: IStorePersisted): Record { + return getPersistState(store, this.storage?.getStoreAttributes(store)); + } + + /** + * Save persisted store state to provided storage right now */ public async savePersistedStore(store: IStorePersisted): Promise { if (this.options.shouldDisablePersist || !this.storage) { @@ -684,38 +724,177 @@ class Manager { } try { - await this.storage.saveStoreData(store, this.getStoreState(store, true)); + await this.storage.saveStoreData(store, this.getPersistState(store)); return true; } catch (e) { - this.logger.err('Failed to persist stores: ', e); + this.logger.err(PERSIST_ERROR, e); } return false; } /** - * Get observable store props (fields) + * Schedule saving persisted store state. + * Changes are collected and saved at most once per options.persistDelay. + * @param store + * @param getState - returns collected store state, by default: getPersistState */ - public static getObservableProps(store: TAnyStore, withNotExported = false): Record { - const props = toJS(store) as Record; - const result: Record = {}; + public schedulePersist( + store: IStorePersisted, + getState?: () => Record | undefined, + ): void { + if (this.options.shouldDisablePersist || !this.storage) { + this.skipPersist(getState); + + return; + } + + if (getState || !this.persistQueue.has(store)) { + this.persistQueue.set(store, getState); + } + + const delay = this.isServer ? 0 : (this.options.persistDelay ?? 100); + + if (delay <= 0) { + void this.flushPersist(); + + return; + } + + if (this.persistTimer === undefined) { + this.persistTimer = setTimeout(() => void this.flushPersist(), delay); + this.listenPageHide(); + } + } + + /** + * Save scheduled persisted stores right now. + * E.g. call it when a mobile app goes to background. + * Resolves when all storage writes are finished: true - saved, false - failed or disabled. + */ + public async flushPersist(): Promise { + clearTimeout(this.persistTimer); + this.persistTimer = undefined; + + const { storage } = this; + const queue = [...this.persistQueue]; + const pendingWrites = [...this.persistWrites]; + + this.persistQueue.clear(); - for (const prop of Object.keys(props)) { - if ( - (isObservableProp(store, prop) && - !isPropExcludedFromExport(store, prop, withNotExported)) || - isPropSimpleExported(store, prop) - ) { - result[prop] = props[prop]; + if (this.options.shouldDisablePersist || !storage) { + queue.forEach(([, getState]) => this.skipPersist(getState)); + + return false; + } + + const entries: TStoreStateEntry[] = []; + let isSaved = true; + + for (const [store, getState] of queue) { + try { + entries.push([store, getState?.() ?? this.getPersistState(store)]); + } catch (e) { + isSaved = false; + this.logger.err(PERSIST_ERROR, e); + } + } + + if (entries.length > 0) { + this.logger.debug('Persist stores.', { + stores: entries.map(([store]) => store.libStoreId), + }); + + const write = this.writePersisted(storage, entries); + + this.persistWrites.add(write); + isSaved = (await write) && isSaved; + this.persistWrites.delete(write); + } + + await Promise.all(pendingWrites); + + return isSaved; + } + + /** + * Persist is disabled (e.g. at runtime): nothing to save, + * but collecting the state keeps store changes listener subscribed + */ + protected skipPersist(getState?: () => unknown): void { + try { + getState?.(); + } catch { + // nothing to save + } + } + + /** + * Write stores state to storage + */ + protected async writePersisted( + storage: CombinedStorage, + entries: TStoreStateEntry[], + ): Promise { + try { + // respect overridden or mocked saving of a single store + if (this.savePersistedStore !== Manager.prototype.savePersistedStore) { + const results = await Promise.all(entries.map(([store]) => this.savePersistedStore(store))); + + return results.every(Boolean); } - if (isPropObservableExported(store, prop)) { - result[prop] = Manager.getObservableProps((store as Record)[prop]); + if (storage.saveStoreData !== CombinedStorage.prototype.saveStoreData) { + await Promise.all(entries.map(([store, data]) => storage.saveStoreData(store, data))); + } else { + await storage.saveStoresData(entries); } + + return true; + } catch (e) { + this.logger.err(PERSIST_ERROR, e); + + return false; } + } - return result; + /** + * Save scheduled changes when the page is hidden or unloaded + */ + protected listenPageHide(): void { + if ( + this.removePageListeners || + typeof window === 'undefined' || + typeof window.addEventListener !== 'function' + ) { + return; + } + + const doc = typeof document !== 'undefined' ? document : undefined; + const onPageHide = (): void => { + void this.flushPersist(); + }; + const onVisibilityChange = (): void => { + if (doc?.visibilityState === 'hidden') { + void this.flushPersist(); + } + }; + + window.addEventListener('pagehide', onPageHide); + doc?.addEventListener?.('visibilitychange', onVisibilityChange); + + this.removePageListeners = () => { + window.removeEventListener('pagehide', onPageHide); + doc?.removeEventListener?.('visibilitychange', onVisibilityChange); + }; + } + + /** + * Get observable store props (fields) + */ + public static getObservableProps(store: TAnyStore, withNotExported = false): Record { + return getObservableProps(store, withNotExported); } /** diff --git a/src/on-change-listener.ts b/src/on-change-listener.ts index a388e08..e8be132 100644 --- a/src/on-change-listener.ts +++ b/src/on-change-listener.ts @@ -1,18 +1,67 @@ -import { reaction, toJS } from 'mobx'; +import { reaction } from 'mobx'; import type { IStorePersisted } from './types'; /** * Listen persist store changes + * + * Tracks only attributes which are saved to storages (other stores referenced by the store + * are not traversed). The reaction is re-run by the manager in batches: many changes + * during Manager.options.persistDelay are serialized and saved once. */ const onChangeListener: IStorePersisted['addOnChangeListener'] = (store, manager) => { if (manager.options.shouldDisablePersist || !manager.storage) { return; } + let run: (() => void) | undefined; + let result: { state?: Record; error?: unknown } | undefined; + let version = 0; + + /** + * Re-run reaction: collect store state and track dependencies again + */ + const getState = (): Record | undefined => { + const runReaction = run; + + run = undefined; + result = {}; + runReaction?.(); + + const { state, error } = result; + + result = undefined; + + if (error) { + throw error; + } + + return state; + }; + return reaction( - () => store.toJSON?.() ?? toJS(store), () => { - void manager.savePersistedStore(store); + // the first run only subscribes to changes: result is collected by getState + try { + const state = manager.getPersistState(store); + + if (result) { + result.state = state; + } + } catch (error) { + if (result) { + result.error = error; + } + } + + // don't keep the state inside reaction + return ++version; + }, + () => undefined, + { + scheduler: (runReaction) => { + run = runReaction; + manager.schedulePersist(store, getState); + }, }, ); }; diff --git a/src/storages/async-storage.ts b/src/storages/async-storage.ts index dc958be..af7306e 100644 --- a/src/storages/async-storage.ts +++ b/src/storages/async-storage.ts @@ -1,4 +1,4 @@ -import type { IStorage } from '../types'; +import type { IStorage, IStorageChanges } from '../types'; interface IAsyncStorage { getItem: (key: string) => Promise; @@ -70,6 +70,22 @@ class AsyncStorage implements IStorage { console.error('Failed to set value to async storage:', e); } } + + /** + * @inheritDoc + */ + async saveChanges({ value, toJSON }: IStorageChanges): Promise { + // keep custom serialization of subclasses + if (this.set !== AsyncStorage.prototype.set) { + return this.set(value); + } + + try { + return await this.storage.setItem(this.globalKey, toJSON()); + } catch (e) { + console.error('Failed to set value to async storage:', e); + } + } } export default AsyncStorage; diff --git a/src/storages/combined-storage.ts b/src/storages/combined-storage.ts index a264946..43fe59e 100644 --- a/src/storages/combined-storage.ts +++ b/src/storages/combined-storage.ts @@ -1,4 +1,3 @@ -import deepCompare from '../deep-compare'; import type { IPersistOptions, IStorage, IStorePersisted } from '../types'; interface ICombinedStorage { @@ -10,6 +9,11 @@ interface ICombinedStorage { */ type TStorageData = Record>; +/** + * Store and the state to save + */ +export type TStoreStateEntry = [IStorePersisted, Record | undefined]; + /** * Combined storage for mobx store manager */ @@ -25,6 +29,12 @@ class CombinedStorage implements IStorage { */ protected persistData: Record = {}; + /** + * Serialized persist data: storage id => store id => store state JSON + * @protected + */ + protected persistJSON: Record> = {}; + /** * Default storage id * @protected @@ -58,6 +68,7 @@ class CombinedStorage implements IStorage { }), {}, ); + this.persistJSON = {}; return this.persistData; } catch { @@ -73,6 +84,7 @@ class CombinedStorage implements IStorage { Object.values(this.storages).map((storage) => Promise.resolve(storage.flush())), ); this.persistData = {}; + this.persistJSON = {}; } /** @@ -104,6 +116,25 @@ class CombinedStorage implements IStorage { }; } + /** + * Return store attributes saved in any storage + * undefined - all attributes + */ + public getStoreAttributes(store: IStorePersisted): string[] | undefined { + const { attributes } = this.getStoreOptions(store); + const result = new Set(); + + for (const attr of Object.values(attributes ?? {})) { + if (attr[0] === '*') { + return undefined; + } + + attr.forEach((attrName) => result.add(attrName)); + } + + return [...result]; + } + /** * Return store persist data */ @@ -136,54 +167,191 @@ class CombinedStorage implements IStorage { /** * Save store data in storage */ - public async saveStoreData( + public saveStoreData( store: IStorePersisted, data: Record | undefined, ): Promise { - const storeId = store.libStoreId!; - const { attributes, behaviour } = this.getStoreOptions(store); - const dataKeys = new Set(Object.keys(data ?? {})); + return this.saveStoresData([[store, data]]); + } + + /** + * Save data of many stores: every changed storage is written once + * + * NOTE: storages are called synchronously, before the returned promise settles + */ + public async saveStoresData(entries: TStoreStateEntry[]): Promise { + const changed = new Map>(); + let error: unknown; + + for (const [store, data] of entries) { + try { + this.applyStoreData(store, data, changed); + } catch (e) { + error = error ?? e; + } + } + + const writes: Promise[] = []; + + for (const [storageId, changes] of changed) { + try { + writes.push(Promise.resolve(this.write(storageId, changes))); + } catch (e) { + writes.push(Promise.reject(e as Error)); + } + } + + await Promise.all(writes); + + if (error) { + throw error; + } + } + + /** + * Serialized stores of storage + */ + protected getStorageJSON(storageId: string): Map { + this.persistJSON[storageId] ??= new Map(); + + return this.persistJSON[storageId]; + } + + /** + * Serialized store data which is saved in storage + */ + protected getSavedJSON(storageId: string, storeId: string): string { + const storageJSON = this.getStorageJSON(storageId); + const savedJSON = storageJSON.get(storeId); + + if (savedJSON !== undefined) { + return savedJSON; + } + + const savedData = this.persistData[storageId]?.[storeId]; + + if (!savedData) { + return '{}'; + } + + const json = JSON.stringify(savedData); + + storageJSON.set(storeId, json); + + return json; + } + + /** + * Pick store attributes of storage + * Picked attributes are removed from dataKeys for 'exclude' behaviour. + */ + protected pickStorageData( + attr: string[], + data: Record | undefined, + dataKeys: Set, + behaviour: IPersistOptions['behaviour'], + ): Record { + const storeData: Record = {}; + + for (const attrName of attr[0] === '*' ? [...dataKeys] : attr) { + if (!dataKeys.has(attrName)) { + continue; + } + + if (behaviour === 'exclude') { + dataKeys.delete(attrName); + } - const dataByStorages = Object.entries(attributes!).map(([storageId, attr]) => { - const storeData = (attr[0] === '*' ? [...dataKeys] : attr).reduce((r, attrName) => { - if (!dataKeys.has(attrName)) { - return r; - } + storeData[attrName] = data?.[attrName]; + } - if (behaviour === 'exclude') { - dataKeys.delete(attrName); - } + return storeData; + } - return { - ...r, - [attrName]: data?.[attrName], - }; - }, {}); + /** + * Split store data by storages and remember changed stores + */ + protected applyStoreData( + store: IStorePersisted, + data: Record | undefined, + changed: Map>, + ): void { + const storeId = store.libStoreId!; + const { attributes, behaviour } = this.getStoreOptions(store); + const dataKeys = new Set(Object.keys(data ?? {})); - const newData = { - ...(this.persistData?.[storageId] ?? {}), - [storeId]: storeData, - } as Record; + for (const [storageId, attr] of Object.entries(attributes!)) { + const storeData = this.pickStorageData(attr, data, dataKeys, behaviour); + const storeJSON = JSON.stringify(storeData); // skip updating if nothing changed - if (deepCompare(this.persistData?.[storageId]?.[storeId] ?? {}, storeData)) { - return null; + if (storeJSON === this.getSavedJSON(storageId, storeId)) { + continue; } if (!this.persistData[storageId]) { this.persistData[storageId] = {}; } - if (!this.persistData[storageId]?.[storeId]) { - this.persistData[storageId][storeId] = {}; + this.persistData[storageId][storeId] = storeData; + this.getStorageJSON(storageId).set(storeId, storeJSON); + + if (!changed.has(storageId)) { + changed.set(storageId, new Map()); + } + + changed.get(storageId)!.set(storeId, storeJSON); + } + } + + /** + * Write storage changes + */ + protected write(storageId: string, changes: Map): ReturnType { + const storage = this.storages[storageId]; + + if (!storage) { + return; + } + + const value = { ...this.persistData[storageId] }; + + if (typeof storage.saveChanges === 'function') { + return storage.saveChanges({ + value, + changes, + toJSON: () => this.toJSON(storageId, value), + }); + } + + return this.set(value, storageId); + } + + /** + * Storage data JSON assembled from cached stores JSON. + * Equal to JSON.stringify(value). + */ + protected toJSON(storageId: string, value: TStorageData): string { + const storageJSON = this.getStorageJSON(storageId); + const parts: string[] = []; + + for (const storeId of Object.keys(value)) { + let storeJSON = storageJSON.get(storeId); + + if (storeJSON === undefined) { + // undefined for unsupported values, e.g. undefined + storeJSON = JSON.stringify(value[storeId]) ?? ''; + storageJSON.set(storeId, storeJSON); } - this.persistData[storageId][storeId] = storeData; + if (!storeJSON) { + continue; + } - return this.set(newData, storageId); - }); + parts.push(`${JSON.stringify(storeId)}:${storeJSON}`); + } - await Promise.all(dataByStorages as Promise[]); + return `{${parts.join(',')}}`; } } diff --git a/src/storages/cookie-storage.ts b/src/storages/cookie-storage.ts index 87a690d..b40cbdd 100644 --- a/src/storages/cookie-storage.ts +++ b/src/storages/cookie-storage.ts @@ -1,4 +1,11 @@ -import type { IStorage } from '../types'; +import type { IStorage, IStorageChanges } from '../types'; + +/** + * Browsers ignore cookies bigger than ~4KB + */ +const MAX_COOKIE_SIZE = 4096; + +let hasSizeWarning = false; interface ICookiesStorageAttributes { expires?: number | Date | undefined; @@ -72,8 +79,34 @@ class CookieStorage implements IStorage { * @inheritDoc */ public set(value: Record | undefined): void { + return this.write(JSON.stringify(value ?? {})); + } + + /** + * @inheritDoc + */ + public saveChanges({ value, toJSON }: IStorageChanges): void { + // keep custom serialization of subclasses + if (this.set !== CookieStorage.prototype.set) { + return this.set(value); + } + + return this.write(toJSON()); + } + + /** + * Write cookie + */ + protected write(json: string): void { + if (!hasSizeWarning && encodeURIComponent(json).length > MAX_COOKIE_SIZE) { + hasSizeWarning = true; + console.warn( + `Persisted stores cookie "${this.globalKey}" is bigger than ${MAX_COOKIE_SIZE} bytes and can be ignored by browsers. Move big attributes to another storage.`, + ); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- cookie adapters (js-cookie, universal-cookie) return library-specific values that are passed through as-is. - return this.storage.set(this.globalKey, JSON.stringify(value ?? {}), this.cookieAttr); + return this.storage.set(this.globalKey, json, this.cookieAttr); } } diff --git a/src/storages/indexed-db-storage.ts b/src/storages/indexed-db-storage.ts new file mode 100644 index 0000000..5c9bc65 --- /dev/null +++ b/src/storages/indexed-db-storage.ts @@ -0,0 +1,264 @@ +import type { IStorage, IStorageChanges } from '../types'; +import StoreRecordsStorage, { + type IStoreRecordsStorageOptions, + serializeStores, +} from './store-records-storage'; + +// eslint-disable-next-line @typescript-eslint/naming-convention -- IndexedDB is the API name. +export interface IIndexedDBStorageOptions extends IStoreRecordsStorageOptions { + /** + * Database name. Default: 'mobx-manager' + */ + dbName?: string; + /** + * IndexedDB factory. Default: globalThis.indexedDB + */ + indexedDB?: IDBFactory; + /** + * Storage with previously persisted stores (e.g. LocalStorage). + * Its data is moved on the first start and removed on flush. + * It is also used when IndexedDB is not available. + */ + migrateFrom?: IStorage; +} + +/** + * Object store name + */ +const STORE_NAME = 'stores'; + +/** + * Promisify IndexedDB request + */ +const promisify = (request: IDBRequest): Promise => + new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed.')); + }); + +/** + * IndexedDB storage for mobx store manager + * + * Every store is saved as its own record: a change writes only the changed stores, + * writes don't block the main thread and the quota is much bigger than localStorage. + */ +class IndexedDBStorage extends StoreRecordsStorage { + /** + * Database name + */ + protected dbName: string; + + /** + * IndexedDB factory + */ + protected factory?: IDBFactory; + + /** + * Opened database + */ + protected db?: IDBDatabase; + + /** + * Opening database + */ + protected opening?: Promise; + + /** + * @constructor + */ + constructor({ dbName, indexedDB, ...options }: IIndexedDBStorageOptions = {}) { + super(options); + this.dbName = dbName ?? 'mobx-manager'; + this.factory = + indexedDB ?? (typeof globalThis !== 'undefined' ? globalThis.indexedDB : undefined); + } + + /** + * Open database. Resolves undefined when IndexedDB is not available. + */ + protected open(): Promise { + if (this.db) { + return Promise.resolve(this.db); + } + + this.opening ??= new Promise((resolve) => { + if (!this.factory) { + resolve(undefined); + + return; + } + + try { + const request = this.factory.open(this.dbName, 1); + + request.onupgradeneeded = () => { + if (!request.result.objectStoreNames.contains(STORE_NAME)) { + request.result.createObjectStore(STORE_NAME); + } + }; + request.onsuccess = () => { + const db = request.result; + const reset = (): void => { + this.db = undefined; + this.opening = undefined; + }; + + // let other tabs upgrade the database + db.onversionchange = () => { + db.close(); + reset(); + }; + // e.g. database is deleted: reopen on the next save + db.onclose = reset; + this.db = db; + resolve(db); + }; + request.onerror = () => { + console.error('Failed to open IndexedDB:', request.error); + resolve(undefined); + }; + } catch (e) { + console.error('Failed to open IndexedDB:', e); + resolve(undefined); + } + }); + + return this.opening; + } + + /** + * @inheritDoc + */ + public async get(): Promise | undefined> { + try { + const db = await this.open(); + + if (!db) { + return (await this.migrateFrom?.get()) ?? {}; + } + + const store = db.transaction(STORE_NAME, 'readonly').objectStore(STORE_NAME); + const [keys, values] = await Promise.all([ + promisify(store.getAllKeys()), + promisify(store.getAll() as IDBRequest), + ]); + + if (keys.length === 0) { + return await this.migrate(); + } + + const result: Record = {}; + + keys.forEach((key, index) => { + try { + result[key as string] = JSON.parse(values[index]) as unknown; + } catch (e) { + console.error(`Failed to parse persisted store "${key as string}":`, e); + } + }); + + return result; + } catch (e) { + console.error('Failed to get stores from IndexedDB:', e); + + return {}; + } + } + + /** + * Write stores in one transaction + */ + protected write(changes: Map, shouldClear = false): Promise { + const transaction = (db: IDBDatabase): Promise => + new Promise((resolve, reject) => { + const tx = db.transaction(STORE_NAME, 'readwrite', { durability: 'relaxed' }); + const store = tx.objectStore(STORE_NAME); + + if (shouldClear) { + store.clear(); + } + + changes.forEach((json, storeId) => store.put(json, storeId)); + + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error ?? new Error('IndexedDB transaction failed.')); + tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted.')); + }); + + // start transaction synchronously when possible (e.g. on page hide) + if (this.db) { + return transaction(this.db); + } + + return this.open().then((db) => (db ? transaction(db) : undefined)); + } + + /** + * @inheritDoc + */ + public async saveChanges(changes: IStorageChanges): Promise { + if (!this.db && !(await this.open())) { + return this.saveFallback(changes); + } + + return super.saveChanges(changes); + } + + /** + * Save to legacy storage when IndexedDB is not available + */ + protected async saveFallback(changes: IStorageChanges): Promise { + const { migrateFrom } = this; + + if (!migrateFrom) { + return; + } + + if (typeof migrateFrom.saveChanges === 'function') { + await migrateFrom.saveChanges(changes); + + return; + } + + await migrateFrom.set(changes.value); + } + + /** + * @inheritDoc + */ + public async set(value: Record | undefined): Promise { + const data = value ?? {}; + + if (!this.db && !(await this.open())) { + await this.migrateFrom?.set(data); + + return; + } + + return this.write(serializeStores(data), true); + } + + /** + * @inheritDoc + */ + public async flush(): Promise { + const db = await this.open(); + + this.isMigrationPending = false; + + await Promise.all([ + db && + new Promise((resolve, reject) => { + const tx = db.transaction(STORE_NAME, 'readwrite'); + + tx.objectStore(STORE_NAME).clear(); + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error ?? new Error('IndexedDB transaction failed.')); + tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted.')); + }), + this.migrateFrom?.flush(), + ]); + } +} + +export default IndexedDBStorage; diff --git a/src/storages/key-value-storage.ts b/src/storages/key-value-storage.ts new file mode 100644 index 0000000..a4b1a5c --- /dev/null +++ b/src/storages/key-value-storage.ts @@ -0,0 +1,230 @@ +import StoreRecordsStorage, { + type IStoreRecordsStorageOptions, + serializeStores, +} from './store-records-storage'; + +/** + * Key-value storage adapter: localStorage, sessionStorage, AsyncStorage, MMKV wrapper etc. + */ +export interface IKeyValueAdapter { + getItem: (key: string) => string | null | undefined | Promise; + setItem: (key: string, value: string) => unknown; + removeItem: (key: string) => unknown; +} + +export interface IKeyValueStorageOptions extends IStoreRecordsStorageOptions { + storage: IKeyValueAdapter; + /** + * Keys prefix: store state is saved under `${prefix}:${storeId}`, + * list of saved stores under `${prefix}-keys`. + * Default: 'stores' + */ + prefix?: string; +} + +/** + * Key-value storage for mobx store manager + * + * Every store is saved under its own key: a change writes only the changed stores + * instead of all persisted stores. + */ +class KeyValueStorage extends StoreRecordsStorage { + /** + * @protected + */ + protected storage: IKeyValueAdapter; + + /** + * Keys prefix + */ + protected prefix: string; + + /** + * Saved stores ids + */ + protected storeIds = new Set(); + + /** + * Saved stores list is read: it's safe to overwrite it + */ + protected isIndexLoaded = false; + + /** + * @constructor + */ + constructor({ storage, prefix, ...options }: IKeyValueStorageOptions) { + super(options); + this.storage = storage; + this.prefix = prefix ?? 'stores'; + } + + /** + * Store state key + */ + protected getKey(storeId: string): string { + return `${this.prefix}:${storeId}`; + } + + /** + * Saved stores list key + */ + protected getIndexKey(): string { + return `${this.prefix}-keys`; + } + + /** + * Read saved stores ids. undefined - there is no list yet. + * Throws when the storage can't be read. + */ + protected async getIndex(): Promise { + const index = await Promise.resolve(this.storage.getItem(this.getIndexKey())); + + if (typeof index !== 'string') { + return undefined; + } + + try { + const ids = JSON.parse(index) as unknown; + + if (Array.isArray(ids)) { + return ids.map(String); + } + } catch { + // broken list is replaced on the next save + } + + console.error('Persisted stores list is broken:', index); + + return []; + } + + /** + * Read saved stores ids into storeIds + * Returns false when the list can't be read: it must not be overwritten then. + */ + protected async loadIndex(): Promise { + if (!this.isIndexLoaded) { + try { + (await this.getIndex())?.forEach((storeId) => this.storeIds.add(storeId)); + this.isIndexLoaded = true; + } catch (e) { + console.error('Failed to get persisted stores list:', e); + } + } + + return this.isIndexLoaded; + } + + /** + * Read store state + */ + protected async getStore(storeId: string): Promise { + try { + const value = await Promise.resolve(this.storage.getItem(this.getKey(storeId))); + + return typeof value === 'string' ? (JSON.parse(value) as unknown) : undefined; + } catch (e) { + console.error(`Failed to get persisted store "${storeId}":`, e); + + return undefined; + } + } + + /** + * @inheritDoc + */ + public async get(): Promise | undefined> { + try { + const ids = await this.getIndex(); + + this.isIndexLoaded = true; + + if (!ids) { + return await this.migrate(); + } + + ids.forEach((storeId) => this.storeIds.add(storeId)); + + const values = await Promise.all(ids.map((storeId) => this.getStore(storeId))); + const result: Record = {}; + + ids.forEach((storeId, index) => { + if (values[index] !== undefined) { + result[storeId] = values[index]; + } + }); + + return result; + } catch (e) { + console.error('Failed to get stores from key-value storage:', e); + + return {}; + } + } + + /** + * Write stores, then update saved stores list + */ + protected async write(changes: Map, removed: string[] = []): Promise { + const isIndexLoaded = await this.loadIndex(); + + await Promise.all([ + ...[...changes].map(([storeId, json]) => this.storage.setItem(this.getKey(storeId), json)), + ...removed.map((storeId) => this.storage.removeItem(this.getKey(storeId))), + ]); + + const newIds = [...changes.keys()].filter((storeId) => !this.storeIds.has(storeId)); + + if (newIds.length === 0 && removed.length === 0) { + return; + } + + newIds.forEach((storeId) => this.storeIds.add(storeId)); + removed.forEach((storeId) => this.storeIds.delete(storeId)); + + // keep the list which can't be read, otherwise other stores are lost + if (isIndexLoaded) { + await this.storage.setItem(this.getIndexKey(), JSON.stringify([...this.storeIds])); + } + } + + /** + * @inheritDoc + */ + public async set(value: Record | undefined): Promise { + // all saved stores: the rest of them are removed + await this.loadIndex(); + + const changes = serializeStores(value ?? {}); + + await this.write( + changes, + [...this.storeIds].filter((storeId) => !changes.has(storeId)), + ); + } + + /** + * @inheritDoc + */ + public async flush(): Promise { + const ids = new Set(this.storeIds); + + try { + (await this.getIndex())?.forEach((storeId) => ids.add(storeId)); + } catch { + // broken list, remove known stores + } + + this.storeIds.clear(); + this.isIndexLoaded = true; + this.isMigrationPending = false; + + await Promise.all([ + ...[...ids].map((storeId) => this.storage.removeItem(this.getKey(storeId))), + this.storage.removeItem(this.getIndexKey()), + this.migrateFrom?.flush(), + ]); + } +} + +export default KeyValueStorage; diff --git a/src/storages/local-storage.ts b/src/storages/local-storage.ts index 0890962..2999883 100644 --- a/src/storages/local-storage.ts +++ b/src/storages/local-storage.ts @@ -1,4 +1,4 @@ -import type { IStorage } from '../types'; +import type { IStorage, IStorageChanges } from '../types'; export interface ILocalStorageOptions { globalKey?: string; @@ -51,6 +51,18 @@ class LocalStorage implements IStorage { set(value: Record | undefined): void { return this.storage.setItem(this.globalKey, JSON.stringify(value ?? {})); } + + /** + * @inheritDoc + */ + saveChanges({ value, toJSON }: IStorageChanges): void { + // keep custom serialization of subclasses + if (this.set !== LocalStorage.prototype.set) { + return this.set(value); + } + + return this.storage.setItem(this.globalKey, toJSON()); + } } export default LocalStorage; diff --git a/src/storages/store-records-storage.ts b/src/storages/store-records-storage.ts new file mode 100644 index 0000000..349b8ce --- /dev/null +++ b/src/storages/store-records-storage.ts @@ -0,0 +1,130 @@ +import type { IStorage, IStorageChanges } from '../types'; + +export interface IStoreRecordsStorageOptions { + /** + * Storage with previously persisted stores (e.g. LocalStorage or AsyncStorage). + * Its data is moved on the first start and removed on flush. + */ + migrateFrom?: IStorage; + /** + * Remove data from `migrateFrom` right after migration. + * Default: false - keep it (e.g. for app version rollback) + */ + shouldRemoveMigrated?: boolean; +} + +/** + * Serialize stores state: store id => store state JSON + */ +const serializeStores = (data: Record): Map => { + const result = new Map(); + + for (const [storeId, state] of Object.entries(data)) { + // undefined for unsupported values, e.g. undefined + const json = JSON.stringify(state) ?? ''; + + if (json) { + result.set(storeId, json); + } + } + + return result; +}; + +/** + * Base storage which saves every persisted store as a separate record + */ +abstract class StoreRecordsStorage implements IStorage { + /** + * Legacy storage + */ + protected migrateFrom?: IStorage; + + /** + * Remove legacy data after migration + */ + protected shouldRemoveMigrated: boolean; + + /** + * Stores moved from legacy storage are not saved yet: the next save writes all stores + */ + protected isMigrationPending = false; + + /** + * @constructor + */ + protected constructor({ migrateFrom, shouldRemoveMigrated }: IStoreRecordsStorageOptions) { + this.migrateFrom = migrateFrom; + this.shouldRemoveMigrated = shouldRemoveMigrated ?? false; + } + + /** + * @inheritDoc + */ + public abstract get(): Promise | undefined>; + + /** + * @inheritDoc + */ + public abstract set(value: Record | undefined): Promise; + + /** + * @inheritDoc + */ + public abstract flush(): Promise; + + /** + * Write stores state JSON + */ + protected abstract write(changes: Map): Promise; + + /** + * @inheritDoc + */ + public saveChanges({ value, changes }: IStorageChanges): Promise { + return this.isMigrationPending ? this.saveMigrated(value) : this.write(changes); + } + + /** + * Move stores from legacy storage + * Legacy data is returned even if it can't be saved: saving is retried on the next change. + */ + protected async migrate(): Promise> { + if (!this.migrateFrom) { + return {}; + } + + const data = (await this.migrateFrom.get()) ?? {}; + + this.isMigrationPending = true; + + try { + await this.saveMigrated(data); + } catch (e) { + console.error('Failed to move persisted stores, retry on the next save:', e); + } + + return data; + } + + /** + * Save all stores, then remove legacy data if needed + */ + protected async saveMigrated(data: Record): Promise { + const changes = serializeStores(data); + + if (changes.size > 0) { + await this.write(changes); + } + + if (this.shouldRemoveMigrated) { + await this.migrateFrom?.flush(); + } + + this.isMigrationPending = false; + } +} + +export { serializeStores }; + +export default StoreRecordsStorage; diff --git a/src/store-state.ts b/src/store-state.ts new file mode 100644 index 0000000..184e450 --- /dev/null +++ b/src/store-state.ts @@ -0,0 +1,71 @@ +import { isObservableObject, isObservableProp, keys, toJS } from 'mobx'; +import { + isPropExcludedFromExport, + isPropObservableExported, + isPropSimpleExported, +} from './make-exported'; +import type { IStorePersisted, TAnyStore } from './types'; + +/** + * Own enumerable store keys. Observable objects also report keys changes to mobx + */ +const getStoreKeys = (store: TAnyStore): string[] => + (isObservableObject(store) ? keys(store) : Object.keys(store)) as string[]; + +/** + * Check if store prop is included in store state + */ +const isExportedProp = (store: TAnyStore, prop: string, withNotExported = false): boolean => + isPropObservableExported(store, prop) || + isPropSimpleExported(store, prop) || + (isObservableProp(store, prop) && !isPropExcludedFromExport(store, prop, withNotExported)); + +/** + * Convert exported props to plain object + * @param store + * @param withNotExported - include props of stores with isNotExported persist option + * @param attributes - only these props, undefined - all + */ +const getExportedProps = ( + store: TAnyStore, + withNotExported: boolean, + attributes?: Set, +): Record => { + const result: Record = {}; + + if (typeof store !== 'object' || store === null) { + return result; + } + + for (const prop of getStoreKeys(store)) { + if ((attributes && !attributes.has(prop)) || !isExportedProp(store, prop, withNotExported)) { + continue; + } + + const value = (store as Record)[prop]; + + result[prop] = isPropObservableExported(store, prop) + ? getExportedProps(value as TAnyStore, false) + : toJS(value); + } + + return result; +}; + +/** + * Get observable store props (fields) + * + * Converts only exported props: plain fields holding other stores are not traversed. + */ +const getObservableProps = (store: TAnyStore, withNotExported = false): Record => + getExportedProps(store, withNotExported); + +/** + * Get store state for persist: only attributes saved in storages + * @param store + * @param attributes - persisted attributes, undefined - all + */ +const getPersistState = (store: IStorePersisted, attributes?: string[]): Record => + store.toJSON?.() ?? getExportedProps(store, true, attributes && new Set(attributes)); + +export { getObservableProps, getPersistState }; diff --git a/src/types.ts b/src/types.ts index 3f19959..36950df 100644 --- a/src/types.ts +++ b/src/types.ts @@ -82,12 +82,34 @@ export type TWakeup = (state: { persistedState?: Record; }) => void; +/** + * Changes of one storage passed to IStorage.saveChanges + */ +export interface IStorageChanges { + /** + * Whole storage state after the changes: store id => store state (same value `set` receives) + */ + value: Record; + /** + * Changed stores: store id => store state JSON + */ + changes: Map; + /** + * Whole state JSON, equal to JSON.stringify(value) but assembled from cached store JSON + */ + toJSON: () => string; +} + export interface IStorage { get: () => Record | undefined | Promise | undefined>; set: ( value: Record | undefined, ) => Record | undefined | Promise | void; flush: () => void | Promise; + /** + * Optional incremental save. When defined, CombinedStorage calls it instead of `set` + */ + saveChanges?: (changes: IStorageChanges) => void | Promise; } export interface IManagerOptions { @@ -105,6 +127,12 @@ export interface IManagerOptions { * empty (default): don't render component if any of the stores not created */ failedCreationStrategy?: 'none' | 'dummy' | 'empty'; + /** + * Batch persisted stores changes and save them at most once per this delay (ms). + * 0 - save on every change. Server side always saves immediately. + * Default: 100 + */ + persistDelay?: number; } export type TAnyStore = IStore | IRelativeStore | IGlobalStore | IStorePersisted; diff --git a/src/wakeup.ts b/src/wakeup.ts index ced31c1..0667322 100644 --- a/src/wakeup.ts +++ b/src/wakeup.ts @@ -17,7 +17,7 @@ function wakeup( deepMerge(this, resState); if (shouldSave) { - void manager.savePersistedStore(this); + manager.schedulePersist(this); } }