[storage] TwoTabs: Announce each write to the other tabs after it commits
This commit is contained in:
@@ -79,6 +79,11 @@ export interface Storage {
|
||||
* here is appended. Nothing is edited or removed. Rejects a file that is not a rose.
|
||||
*/
|
||||
importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>;
|
||||
/**
|
||||
* Hears what another tab of the garden wrote (two-tabs.md): `'log'` or `'place'`,
|
||||
* after it committed. Read storage again on it. Returns the way to stop hearing.
|
||||
*/
|
||||
onChange(listener: (what: Change) => void): () => void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
@@ -188,12 +193,44 @@ class RoseaDatabase extends Dexie {
|
||||
}
|
||||
}
|
||||
|
||||
/** What another tab changed (two-tabs.md W2): only which part, never the data. */
|
||||
export type Change = 'log' | 'place';
|
||||
|
||||
/** The channel every tab of the garden announces its writes on (two-tabs.md W1). */
|
||||
export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`;
|
||||
|
||||
/**
|
||||
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
|
||||
* passes nothing and gets the browser's IndexedDB.
|
||||
* passes nothing and gets the browser's IndexedDB. `settings.channel` names the
|
||||
* channel writes are announced on (null: none), so tests can keep theirs apart.
|
||||
*/
|
||||
export function openStorage(options?: DexieOptions): Storage {
|
||||
export function openStorage(options?: DexieOptions, settings: { readonly channel?: string | null } = {}): Storage {
|
||||
const db = new RoseaDatabase(options);
|
||||
const channelName = settings.channel === undefined ? CHANGES_CHANNEL : settings.channel;
|
||||
// Where BroadcastChannel does not exist, each tab simply keeps its own view (W5).
|
||||
const channel = channelName !== null && typeof BroadcastChannel === 'function' ? new BroadcastChannel(channelName) : null;
|
||||
const listeners = new Set<(what: Change) => void>();
|
||||
if (channel) {
|
||||
channel.onmessage = (message: MessageEvent<unknown>) => {
|
||||
const what = message.data;
|
||||
if (what !== 'log' && what !== 'place') return;
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(what);
|
||||
} catch (error) {
|
||||
console.error('storage: a listener for changes in another tab failed', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
/** Called only after a write committed, so the other tab reads what was written. A tab never hears itself (W3). */
|
||||
const announce = (what: Change): void => {
|
||||
try {
|
||||
channel?.postMessage(what);
|
||||
} catch (error) {
|
||||
console.warn('storage: could not tell the other tabs about a change; they will see it on their next load', error);
|
||||
}
|
||||
};
|
||||
const asIdentity = (row: KeyRow | undefined): Identity | null => {
|
||||
const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null;
|
||||
return id && isIdentity(id) ? id : null;
|
||||
@@ -211,11 +248,13 @@ export function openStorage(options?: DexieOptions): Storage {
|
||||
const plain = asSunsetPlace(place);
|
||||
if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape');
|
||||
await db.profile.put({ key: SUNSET_PLACE, value: plain });
|
||||
announce('place');
|
||||
},
|
||||
async appendCare(event) {
|
||||
const plain = asCareEvent(event);
|
||||
if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape');
|
||||
await db.events.add({ event: plain });
|
||||
announce('log');
|
||||
},
|
||||
async loadCare() {
|
||||
const rows = await db.events.orderBy('id').toArray();
|
||||
@@ -233,6 +272,7 @@ export function openStorage(options?: DexieOptions): Storage {
|
||||
const plain = asSentenceOpened(event);
|
||||
if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape');
|
||||
await db.events.add({ event: plain });
|
||||
announce('log');
|
||||
},
|
||||
async loadOpened() {
|
||||
const rows = await db.events.orderBy('id').toArray();
|
||||
@@ -276,7 +316,7 @@ export function openStorage(options?: DexieOptions): Storage {
|
||||
async importRose(file, currentKey) {
|
||||
const rose = asRoseFile(file);
|
||||
if (rose === null) throw new TypeError('storage: this file does not hold a rose');
|
||||
return db.transaction('rw', db.events, db.profile, async () => {
|
||||
const result = await db.transaction('rw', db.events, db.profile, async () => {
|
||||
const row = await db.profile.get(PAST_KEYS);
|
||||
const past = isKeyList(row?.value) ? row.value : [];
|
||||
const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey);
|
||||
@@ -289,8 +329,17 @@ export function openStorage(options?: DexieOptions): Storage {
|
||||
await db.events.bulkAdd([...added, ...petals].map((event) => ({ event })));
|
||||
return { added: added.length, petals: petals.length };
|
||||
});
|
||||
// After the commit: her keys and her log both changed for the other tabs.
|
||||
announce('log');
|
||||
return result;
|
||||
},
|
||||
onChange(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
close() {
|
||||
listeners.clear();
|
||||
channel?.close();
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { CareEvent, SentenceOpened } from '@rosea/schema';
|
||||
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { openStorage, ROSE_FILE_FORMAT, type Change, type Storage } from '../src/index.js';
|
||||
|
||||
const KEY = 'K'.repeat(87);
|
||||
const OLD = 'O'.repeat(87);
|
||||
const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:rose', messageId: null, clientVersion: '0.1.0' };
|
||||
const petal: SentenceOpened = { kind: 'sentence-opened', ts: 1774944000000, localDay: '2026-03-31', from: KEY, messageId: 'ps-118-24', clientVersion: '0.1.0' };
|
||||
const brno = { kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } } as const;
|
||||
|
||||
let channels = 0;
|
||||
const opened: Storage[] = [];
|
||||
/** Two tabs of one garden: one database, one channel, their own for this test. */
|
||||
function twoTabs(): [Storage, Storage] {
|
||||
const indexedDB = new IDBFactory();
|
||||
const channel = `rosea-test-${++channels}`;
|
||||
const tabs = [openStorage({ indexedDB, IDBKeyRange }, { channel }), openStorage({ indexedDB, IDBKeyRange }, { channel })] as [Storage, Storage];
|
||||
opened.push(...tabs);
|
||||
return tabs;
|
||||
}
|
||||
afterEach(() => {
|
||||
for (const s of opened.splice(0)) s.close();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** Everything `tab` hears in the next `ms`. */
|
||||
function hears(tab: Storage, ms = 150): Promise<Change[]> {
|
||||
const heard: Change[] = [];
|
||||
const stop = tab.onChange((what) => heard.push(what));
|
||||
return new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
stop();
|
||||
resolve(heard);
|
||||
}, ms)
|
||||
);
|
||||
}
|
||||
|
||||
describe('a write is announced to the other tabs (two-tabs.md W1)', () => {
|
||||
it('care: the other tab hears "log", and reading then finds it', async () => {
|
||||
const [a, b] = twoTabs();
|
||||
let found: CareEvent[] = [];
|
||||
const read = new Promise<void>((resolve) =>
|
||||
b.onChange(async () => {
|
||||
found = await b.loadCare();
|
||||
resolve();
|
||||
})
|
||||
);
|
||||
await a.appendCare(weed);
|
||||
await read;
|
||||
expect(found).toEqual([weed]);
|
||||
});
|
||||
|
||||
it('a petal and a rose brought back are "log"; a town is "place"', async () => {
|
||||
const [a, b] = twoTabs();
|
||||
const heard = hears(b);
|
||||
await a.appendOpened(petal);
|
||||
await a.importRose({ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [], opened: [] }, KEY);
|
||||
await a.saveSunsetPlace(brno);
|
||||
expect(await heard).toEqual(['log', 'log', 'place']);
|
||||
});
|
||||
|
||||
it('a tab does not hear itself (W3)', async () => {
|
||||
const [a] = twoTabs();
|
||||
const heard = hears(a);
|
||||
await a.appendCare(weed);
|
||||
expect(await heard).toEqual([]);
|
||||
});
|
||||
|
||||
it('a refused write announces nothing', async () => {
|
||||
const [a, b] = twoTabs();
|
||||
const heard = hears(b);
|
||||
await expect(a.appendCare({ ...weed, note: 'x' } as CareEvent)).rejects.toThrow();
|
||||
await expect(a.importRose('not a rose', KEY)).rejects.toThrow();
|
||||
expect(await heard).toEqual([]);
|
||||
});
|
||||
|
||||
it('a malformed message is ignored; a listener that throws does not stop the others', async () => {
|
||||
const [, b] = twoTabs();
|
||||
const raw = new BroadcastChannel(`rosea-test-${channels}`);
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
b.onChange(() => {
|
||||
throw new Error('a broken listener');
|
||||
});
|
||||
const heard = hears(b);
|
||||
raw.postMessage({ what: 'log', data: 'anything' });
|
||||
raw.postMessage('care');
|
||||
raw.postMessage('place');
|
||||
expect(await heard).toEqual(['place']);
|
||||
expect(error).toHaveBeenCalledOnce();
|
||||
raw.close();
|
||||
});
|
||||
|
||||
it('after unsubscribing, or after close, nothing more is heard', async () => {
|
||||
const [a, b] = twoTabs();
|
||||
const calls: Change[] = [];
|
||||
const stop = b.onChange((w) => calls.push(w));
|
||||
stop();
|
||||
await a.appendCare(weed);
|
||||
b.close();
|
||||
await a.appendCare({ ...weed, ts: weed.ts + 1 });
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('without a channel (W5)', () => {
|
||||
it('storage works as before, and simply hears nothing', async () => {
|
||||
vi.stubGlobal('BroadcastChannel', undefined);
|
||||
const indexedDB = new IDBFactory();
|
||||
const a = openStorage({ indexedDB, IDBKeyRange });
|
||||
const b = openStorage({ indexedDB, IDBKeyRange });
|
||||
opened.push(a, b);
|
||||
const heard = hears(b);
|
||||
await a.appendCare(weed);
|
||||
expect(await b.loadCare()).toEqual([weed]);
|
||||
expect(await heard).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user