@tallyui/database 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+
3
+ /**
4
+ * ADR-061: exactly one live tab per store, and a second tab never opens
5
+ * storage. `acquiring` while a hand-over is in flight, `live` while this tab
6
+ * holds the lock, `parked` after handing over, `blocked` when the live tab
7
+ * never answered and the user must close it.
8
+ */
9
+ export type LiveTabState = 'acquiring' | 'live' | 'parked' | 'blocked';
10
+
11
+ type LiveTabChannel = Pick<BroadcastChannel, 'postMessage' | 'close'> & {
12
+ onmessage: ((event: { data: unknown }) => void) | null;
13
+ };
14
+
15
+ interface HandoverMessage {
16
+ type: 'handover-request' | 'handover-ack';
17
+ id: string;
18
+ }
19
+
20
+ function isHandoverMessage(data: unknown): data is HandoverMessage {
21
+ const msg = data as Partial<HandoverMessage> | null;
22
+ return (
23
+ typeof msg === 'object' &&
24
+ msg !== null &&
25
+ (msg.type === 'handover-request' || msg.type === 'handover-ack') &&
26
+ typeof msg.id === 'string'
27
+ );
28
+ }
29
+
30
+ export interface LiveTabOptions {
31
+ /** Store scope; the lock and channel are named `tally-live-tab:<scope>`. */
32
+ scope: string;
33
+ /** Called on the live tab before it hands over: close the database, stop workers. Awaited. */
34
+ onPark: () => void | Promise<void>;
35
+ /** True while a sale, payment or storage write is in flight; the hand-over waits for false. */
36
+ isBusy?: () => boolean;
37
+ /** Longest the live tab defers a hand-over while busy (default 10_000 ms). */
38
+ maxDeferMs?: number;
39
+ /** How long a new tab waits for the live tab to acknowledge (default 3_000 ms). */
40
+ ackTimeoutMs?: number;
41
+ /** Injection for tests and non-browser hosts; default globalThis.navigator?.locks and globalThis.BroadcastChannel. */
42
+ locks?: Pick<LockManager, 'request'>;
43
+ createChannel?: (name: string) => LiveTabChannel;
44
+ /** Injection for tests; default globalThis. Source of `pagehide`/`pageshow`. */
45
+ events?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
46
+ /** Injection for tests; default Date.now. Wall clock for the busy-defer cap below. */
47
+ now?: () => number;
48
+ }
49
+
50
+ export interface LiveTabHandle {
51
+ state$: Observable<LiveTabState>;
52
+ /** Ask the live tab to hand over, and take the lock. Used on start and by the parked screen's "Use here" button. */
53
+ takeOver(): Promise<LiveTabState>;
54
+ /** Release the lock and close the channel (sign-out, unmount). */
55
+ stop(): void;
56
+ }
57
+
58
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * Coordinates one live tab per store (ADR-061) over a Web Lock and a
62
+ * BroadcastChannel, both named `tally-live-tab:<scope>`.
63
+ *
64
+ * On platforms without Web Locks (React Native, Node, tests: `locks` is
65
+ * undefined) a tab is simply live at once, since native and Electron have
66
+ * one window per store.
67
+ */
68
+ export function startLiveTab(options: LiveTabOptions): LiveTabHandle {
69
+ const {
70
+ scope,
71
+ onPark,
72
+ isBusy,
73
+ maxDeferMs = 10_000,
74
+ ackTimeoutMs = 3_000,
75
+ locks = globalThis.navigator?.locks,
76
+ createChannel = (name) => new BroadcastChannel(name) as unknown as LiveTabChannel,
77
+ events = globalThis,
78
+ now = Date.now,
79
+ } = options;
80
+ const state = new BehaviorSubject<LiveTabState>('acquiring');
81
+
82
+ if (!locks) {
83
+ state.next('live');
84
+ return { state$: state.asObservable(), takeOver: () => Promise.resolve('live'), stop: () => state.complete() };
85
+ }
86
+
87
+ const name = `tally-live-tab:${scope}`;
88
+ let channel = createChannel(name);
89
+ let releaseLock: (() => void) | undefined;
90
+ let parking = false;
91
+ let requestCounter = 0;
92
+ let stopped = false;
93
+ let deferBlockedTimer: ReturnType<typeof setTimeout> | undefined;
94
+ // Aborts every locks.request() in flight; resume() swaps in a fresh one for the next round.
95
+ let abortController = new AbortController();
96
+ // Unique per coordinator instance, so two tabs requesting at once never mint the same id
97
+ // (a shared id would let one ack satisfy both waiters).
98
+ const tabToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
99
+ const ackWaiters = new Map<string, () => void>();
100
+
101
+ /** Holds the lock (if granted) until `releaseLock()` resolves the held promise. */
102
+ // `controller` defaults to the one current when called, so a late grant for a round before a resume is told apart from the current round.
103
+ const requestLock = (lockOptions: Omit<LockOptions, 'signal'>, controller = abortController): Promise<boolean> =>
104
+ new Promise<boolean>((resolve, reject) => {
105
+ // Browsers reject `signal` with `ifAvailable` (NotSupportedError), so the probe carries none; a late probe grant is still caught below by `stopped`/the stale-controller check.
106
+ locks
107
+ .request(name, lockOptions.ifAvailable ? lockOptions : { ...lockOptions, signal: controller.signal }, (lock) => {
108
+ // Stopped, or a stale grant from before a suspend/resume: hand the lock straight back (a non-promise return releases it at once) and never go live.
109
+ if (!lock || stopped || controller !== abortController) {
110
+ resolve(false);
111
+ return undefined;
112
+ }
113
+ resolve(true);
114
+ return new Promise<void>((release) => {
115
+ releaseLock = release;
116
+ });
117
+ })
118
+ .catch((error: unknown) => {
119
+ if (controller.signal.aborted) resolve(false);
120
+ else reject(error);
121
+ });
122
+ });
123
+
124
+ const waitForAck = (id: string): Promise<boolean> =>
125
+ new Promise<boolean>((resolve) => {
126
+ const timer = setTimeout(() => {
127
+ ackWaiters.delete(id);
128
+ resolve(false);
129
+ }, ackTimeoutMs);
130
+ ackWaiters.set(id, () => {
131
+ clearTimeout(timer);
132
+ ackWaiters.delete(id);
133
+ resolve(true);
134
+ });
135
+ });
136
+
137
+ const handleHandoverRequest = async (id: string) => {
138
+ if (state.value !== 'live' || parking) return;
139
+ parking = true;
140
+ channel.postMessage({ type: 'handover-ack', id });
141
+ try {
142
+ // Wall clock, not a count of sleeps: this tab is in the background right now, and
143
+ // browsers throttle background timers to ~1 s or more, so each sleep(100) can take
144
+ // far longer than requested and a sleep count would blow well past maxDeferMs.
145
+ const start = now();
146
+ while (isBusy?.() && now() - start < maxDeferMs) await sleep(100);
147
+ try {
148
+ await onPark();
149
+ } catch (error) {
150
+ // Reload is the recovery, so a broken onPark still parks and frees the lock.
151
+ console.warn(`live-tab: onPark failed for scope "${scope}"; parking anyway.`, error);
152
+ }
153
+ } finally {
154
+ releaseLock?.();
155
+ releaseLock = undefined;
156
+ parking = false;
157
+ state.next('parked');
158
+ }
159
+ };
160
+
161
+ const handleChannelMessage = (event: { data: unknown }) => {
162
+ if (!isHandoverMessage(event.data)) return;
163
+ if (event.data.type === 'handover-ack') ackWaiters.get(event.data.id)?.();
164
+ else void handleHandoverRequest(event.data.id);
165
+ };
166
+ channel.onmessage = handleChannelMessage;
167
+
168
+ // Shared by overlapping takeOver() calls, so a double tap doesn't race two
169
+ // hand-over requests against each other (like runners sharing a relay pass).
170
+ let inFlightTakeOver: Promise<LiveTabState> | undefined;
171
+
172
+ const performTakeOver = async (): Promise<LiveTabState> => {
173
+ state.next('acquiring');
174
+ if (await requestLock({ ifAvailable: true })) {
175
+ state.next('live');
176
+ return 'live';
177
+ }
178
+ if (stopped) return state.value;
179
+
180
+ const id = `${tabToken}-${++requestCounter}`;
181
+ // Register the waiter before posting: an ack can arrive synchronously.
182
+ const acked = waitForAck(id);
183
+ channel.postMessage({ type: 'handover-request', id });
184
+ // Queue for the lock at once, racing the ack: the live tab may already be closing
185
+ // (StrictMode's stop-then-restart, a closing page), so a lock that frees within
186
+ // milliseconds is taken straight away instead of waiting out ackTimeoutMs.
187
+ // No deadline on the request itself: only stop() gives up waiting.
188
+ const gotLockPromise = requestLock({});
189
+ const lockFirst = await Promise.race([gotLockPromise.then(() => true), acked.then(() => false)]);
190
+
191
+ if (lockFirst) {
192
+ ackWaiters.delete(id);
193
+ } else if (await acked) {
194
+ // Acked: shown as blocked once the old defer+ack deadline passes, but keeps waiting.
195
+ deferBlockedTimer = setTimeout(() => state.next('blocked'), maxDeferMs + ackTimeoutMs);
196
+ } else {
197
+ state.next('blocked');
198
+ }
199
+ if (stopped) return state.value;
200
+
201
+ const gotLock = await gotLockPromise;
202
+ clearTimeout(deferBlockedTimer);
203
+ deferBlockedTimer = undefined;
204
+ if (stopped) return state.value;
205
+ state.next(gotLock ? 'live' : 'blocked');
206
+ return gotLock ? 'live' : 'blocked';
207
+ };
208
+
209
+ const takeOver = (): Promise<LiveTabState> => {
210
+ // Stopped: nothing left to ask for or hold.
211
+ if (stopped) return Promise.resolve(state.value);
212
+ // Already holding the lock: nothing to ask for, and trying again would
213
+ // fail ifAvailable against our own held lock and post a request nobody answers.
214
+ if (state.value === 'live') return Promise.resolve('live');
215
+ if (!inFlightTakeOver) {
216
+ inFlightTakeOver = performTakeOver().finally(() => {
217
+ inFlightTakeOver = undefined;
218
+ });
219
+ }
220
+ return inFlightTakeOver;
221
+ };
222
+
223
+ // pagehide: release the lock and park, but never complete state$ or touch the listeners.
224
+ const suspend = () => {
225
+ stopped = true;
226
+ abortController.abort();
227
+ releaseLock?.();
228
+ releaseLock = undefined;
229
+ ackWaiters.clear();
230
+ clearTimeout(deferBlockedTimer);
231
+ deferBlockedTimer = undefined;
232
+ channel.onmessage = null;
233
+ channel.close();
234
+ state.next('parked');
235
+ };
236
+
237
+ // bfcache restore: fresh controller and channel for a clean round, then re-acquire.
238
+ const resume = () => {
239
+ abortController = new AbortController();
240
+ channel = createChannel(name);
241
+ channel.onmessage = handleChannelMessage;
242
+ stopped = false;
243
+ void takeOver().catch((error) => {
244
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
245
+ state.next('blocked');
246
+ });
247
+ };
248
+
249
+ const handlePageShow = (event: Event) => {
250
+ if ((event as PageTransitionEvent).persisted && stopped) resume();
251
+ };
252
+
253
+ const handlePageHide = () => {
254
+ suspend();
255
+ // Best-effort, not awaited (pagehide can't wait): frees the OPFS handles for another
256
+ // tab while this page sits in the bfcache; reload is still the recovery if it fails.
257
+ void Promise.resolve().then(onPark).catch((error: unknown) => {
258
+ console.warn(`live-tab: onPark failed for scope "${scope}" on pagehide.`, error);
259
+ });
260
+ };
261
+
262
+ const stop = () => {
263
+ suspend();
264
+ events.removeEventListener?.('pagehide', handlePageHide);
265
+ events.removeEventListener?.('pageshow', handlePageShow);
266
+ state.complete();
267
+ };
268
+
269
+ // A reload or a closing page never sends an ack; pageshow recovers after a bfcache restore.
270
+ events.addEventListener?.('pagehide', handlePageHide);
271
+ events.addEventListener?.('pageshow', handlePageShow);
272
+
273
+ // Start. A rejection here (a real locks.request() error, not an abort) still resolves a state.
274
+ void takeOver().catch((error) => {
275
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
276
+ state.next('blocked');
277
+ });
278
+
279
+ return { state$: state.asObservable(), takeOver, stop };
280
+ }
@@ -0,0 +1,19 @@
1
+ /** Runs `run` for each trigger: idle starts a pass; during a pass, one follow-up is queued (later triggers share it). */
2
+ export function createPassQueue<T>(run: () => Promise<T>): () => Promise<T> {
3
+ let current: Promise<T> | undefined;
4
+ let queued: Promise<T> | undefined;
5
+
6
+ const trigger = (): Promise<T> => {
7
+ if (!current) return (current = run().finally(() => { current = undefined; }));
8
+ if (!queued) {
9
+ // Wait for the in-flight pass to settle, ignoring its rejection here: the
10
+ // caller that started it handles that rejection on its own promise. By the
11
+ // time this fires, `current`'s finally above has already cleared it, so
12
+ // clearing `queued` first and re-triggering starts a fresh pass, not a reuse.
13
+ queued = current.catch(() => {}).then(() => { queued = undefined; return trigger(); });
14
+ }
15
+ return queued;
16
+ };
17
+
18
+ return trigger;
19
+ }
@@ -0,0 +1,150 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import { BehaviorSubject, type Observable } from 'rxjs';
3
+
4
+ import { STOCK_LEVELS_LAST_PASS, type StockReconcileAdapter, type SyncContext } from '@tallyui/core';
5
+
6
+ import { createPassQueue } from './pass-queue';
7
+ import type { StockLevelRow } from './stock-levels';
8
+
9
+ export interface StartStockReconcileOptions {
10
+ /** The `stock_levels` collection. The runner writes nothing else. */
11
+ collection: RxCollection<StockLevelRow>;
12
+ adapter: StockReconcileAdapter;
13
+ context: SyncContext;
14
+ /** Time between passes in ms (default: 300000, 5 minutes) */
15
+ intervalMs?: number;
16
+ /** Most pages one pass reads; beyond it the pass is truncated (default: 100) */
17
+ maxPages?: number;
18
+ }
19
+
20
+ export interface StockReconcileResult {
21
+ pages: number;
22
+ /** Rows inserted or changed */
23
+ written: number;
24
+ /** Rows whose key the backend no longer returns */
25
+ removed: number;
26
+ truncated: boolean;
27
+ /** ISO time of a successful pass; also stored in the `last-pass` local document. */
28
+ completedAt?: string;
29
+ }
30
+
31
+ /** The runner's state. `lastCompletedAt` survives restarts; the rest is in memory. */
32
+ export interface StockReconcileState {
33
+ lastCompletedAt?: string;
34
+ running: boolean;
35
+ truncated: boolean;
36
+ lastError?: unknown;
37
+ }
38
+
39
+ /**
40
+ * Periodically re-read stock into the `stock_levels` overlay collection (ADR-060).
41
+ *
42
+ * Replicated product documents are never written: a local write there makes
43
+ * RxDB's downstream skip the next pulled version of that document.
44
+ *
45
+ * The first pass waits for the interval; the app calls reconcileStock() after
46
+ * first paint and on foreground or resume. A call during a pass queues one
47
+ * follow-up pass (later calls share it), so a change made after the pass
48
+ * read is picked up straight after, not at the next interval. stop() clears
49
+ * the timer and aborts a running pass.
50
+ */
51
+ export function startStockReconcile({
52
+ collection,
53
+ adapter,
54
+ context,
55
+ intervalMs = 300_000,
56
+ maxPages = 100,
57
+ }: StartStockReconcileOptions): {
58
+ reconcileStock(): Promise<StockReconcileResult>;
59
+ stop(): void;
60
+ state$: Observable<StockReconcileState>;
61
+ } {
62
+ const controller = new AbortController();
63
+ const { signal } = controller;
64
+ // React Native's AbortController polyfill has no throwIfAborted() and may have no reason.
65
+ const checkAborted = () => {
66
+ if (signal.aborted) throw signal.reason ?? new Error('Stock reconcile stopped');
67
+ };
68
+ const state = new BehaviorSubject<StockReconcileState>({ running: false, truncated: false });
69
+ const update = (patch: Partial<StockReconcileState>) => state.next({ ...state.value, ...patch });
70
+ // Every pass awaits this, so a collection without local documents (RxDB LD8) fails before fetching.
71
+ const lastPass = collection.getLocal<{ completedAt: string }>(STOCK_LEVELS_LAST_PASS).catch((error) => {
72
+ if (error?.code !== 'LD8') return null;
73
+ throw new Error(`Create "${collection.name}" with stockLevelsCollection (localDocuments: true); stock reconcile stores its last pass there.`, { cause: error });
74
+ });
75
+ // Seed "as of" from the last successful pass before this start, unless a pass already set it.
76
+ lastPass.then((doc) => {
77
+ if (doc && !state.value.lastCompletedAt) update({ lastCompletedAt: doc.get('completedAt') });
78
+ }, () => {});
79
+
80
+ const pass = async (): Promise<StockReconcileResult> => {
81
+ checkAborted();
82
+ await lastPass;
83
+ // Phase 1: read every page. A fetch that throws, is truncated or is
84
+ // aborted writes nothing, so a partial snapshot never removes rows.
85
+ const stock = new Map<string, unknown>();
86
+ let pages = 0;
87
+ for await (const page of adapter.fetchPages({ ...context, signal })) {
88
+ checkAborted();
89
+ if (pages === maxPages) {
90
+ console.warn(`Stock reconcile stopped at the ${maxPages}-page limit; nothing was written.`);
91
+ return { pages, written: 0, removed: 0, truncated: true };
92
+ }
93
+ pages++;
94
+ for (const [key, value] of page) stock.set(key, value);
95
+ }
96
+
97
+ // Phase 2: write only rows that changed; remove keys the backend no longer returns.
98
+ const rows = (await collection.find().exec()).map((doc) => doc.toJSON() as StockLevelRow);
99
+ const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
100
+ const updatedAt = new Date().toISOString();
101
+ const upserts = [...stock]
102
+ .filter(([id, value]) => stored.get(id) !== JSON.stringify(value))
103
+ .map(([id, value]) => ({ id, value, updatedAt }));
104
+ const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
105
+
106
+ checkAborted();
107
+ if (upserts.length) {
108
+ const { error } = await collection.bulkUpsert(upserts);
109
+ if (error.length) throw error[0];
110
+ }
111
+ if (removals.length) {
112
+ const { error } = await collection.bulkRemove(removals);
113
+ if (error.length) throw error[0];
114
+ }
115
+ // Rows written by this pass carry the same time.
116
+ const completedAt = updatedAt;
117
+ checkAborted();
118
+ await collection.upsertLocal(STOCK_LEVELS_LAST_PASS, { completedAt });
119
+ return { pages, written: upserts.length, removed: removals.length, truncated: false, completedAt };
120
+ };
121
+
122
+ const tracked = async (): Promise<StockReconcileResult> => {
123
+ update({ running: true });
124
+ try {
125
+ const result = await pass();
126
+ if (result.truncated) update({ running: false, truncated: true });
127
+ else state.next({ running: false, truncated: false, lastCompletedAt: result.completedAt });
128
+ return result;
129
+ } catch (error) {
130
+ update({ running: false, lastError: error });
131
+ throw error;
132
+ }
133
+ };
134
+ const reconcileStock = createPassQueue(tracked);
135
+ const timer = setInterval(() => {
136
+ reconcileStock().catch((error) => console.warn('Stock reconcile failed:', error));
137
+ }, intervalMs);
138
+
139
+ // stop() and an abort of context.signal both end the runner for good.
140
+ const stop = () => {
141
+ clearInterval(timer);
142
+ context.signal?.removeEventListener('abort', stop);
143
+ controller.abort();
144
+ state.complete();
145
+ };
146
+ if (context.signal?.aborted) stop();
147
+ else context.signal?.addEventListener('abort', stop);
148
+
149
+ return { reconcileStock, stop, state$: state.asObservable() };
150
+ }
@@ -29,9 +29,16 @@ export function startReplication<RxDocType, CheckpointType = any>({
29
29
  retryTime = 5000,
30
30
  autoStart = true,
31
31
  }: StartReplicationOptions<RxDocType, CheckpointType>): RxReplicationState<RxDocType, CheckpointType> {
32
+ // A schema bump drops the documents (createTallyDatabase), so it must also
33
+ // reset the checkpoint: RxDB migrates the old checkpoint with the collection.
34
+ // A new identifier is a fresh meta instance, so the pull starts from nothing
35
+ // (and a combined adapter seeds as on a fresh install). The old meta instance
36
+ // is left orphaned: a few rows, and removing it is out of scope. Version 0
37
+ // keeps the original identifier, so existing installs never resync.
38
+ const { version } = collection.schema;
32
39
  return replicateRxCollection({
33
40
  collection,
34
- replicationIdentifier: `${context.connectorId}-${collection.name}`,
41
+ replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}`,
35
42
  pull: {
36
43
  handler: (checkpoint, batchSize) =>
37
44
  adapter.pull.handler(checkpoint as CheckpointType | undefined, batchSize, context),
@@ -0,0 +1,32 @@
1
+ import type { RxJsonSchema } from 'rxdb';
2
+
3
+ /** Collection holding the stock reconcile overlay (ADR-060). Local only: never replicated. */
4
+ export const STOCK_LEVELS_COLLECTION = 'stock_levels';
5
+
6
+ /** Local document in `stock_levels` holding `{ completedAt }` of the last successful pass. */
7
+ export { STOCK_LEVELS_LAST_PASS } from '@tallyui/core';
8
+
9
+ /** One overlay row: the connector's stock value for one key (Vendure variant id, Medusa inventory item id). */
10
+ export interface StockLevelRow {
11
+ id: string;
12
+ /** The value `fetchPages` gave for this key, stored as is. */
13
+ value: unknown;
14
+ /** ISO 8601 time of the pass that wrote the row. */
15
+ updatedAt: string;
16
+ }
17
+
18
+ export const stockLevelsSchema: RxJsonSchema<StockLevelRow> = {
19
+ version: 0,
20
+ primaryKey: 'id',
21
+ type: 'object',
22
+ properties: {
23
+ id: { type: 'string', maxLength: 255 },
24
+ // Untyped: any JSON value the connector yields.
25
+ value: {},
26
+ updatedAt: { type: 'string' },
27
+ },
28
+ required: ['id', 'value', 'updatedAt'],
29
+ };
30
+
31
+ /** Use this whenever you create `stock_levels` yourself: the runner stores its last pass in local documents. */
32
+ export const stockLevelsCollection = { schema: stockLevelsSchema, localDocuments: true } as const;
@@ -0,0 +1,134 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+ import type { RxStorage } from 'rxdb';
3
+
4
+ /** WCPOS's value (ADR-061): a write pending longer than this is flagged as stalled, never failed. */
5
+ export const STORAGE_WRITE_STALL_MS = 10_000;
6
+
7
+ /** WCPOS's value (ADR-061): two consecutive silent read windows of this length mean the worker is dead. */
8
+ export const STORAGE_READ_WATCHDOG_MS = 30_000;
9
+
10
+ export interface StorageHealth {
11
+ /** 'ok'; 'stalled' while a write has been pending longer than writeStallMs; 'dead' after two silent read windows (reload to recover, ADR-061). */
12
+ status: 'ok' | 'stalled' | 'dead';
13
+ /** Writes pending longer than writeStallMs right now. */
14
+ stalledWrites: number;
15
+ /** When the oldest stalled write started (ms since epoch), if any. */
16
+ stalledSince?: number;
17
+ }
18
+
19
+ export interface StorageWatchdogOptions {
20
+ writeStallMs?: number;
21
+ readWatchdogMs?: number;
22
+ /** Injectable clock, for tests. */
23
+ now?: () => number;
24
+ /** Injectable timer, for tests: runs `fn` once after `ms` and returns a cancel function. */
25
+ setTimer?: (fn: () => void, ms: number) => () => void;
26
+ }
27
+
28
+ /**
29
+ * True for `StorageWorkerStartError` (raised by `@tallyui/storage-sqlite/web`
30
+ * when the worker cannot open the opfs-sahpool pool), matched by `name` or by
31
+ * the substring `StorageWorkerStartError` anywhere in the message. RxDB's
32
+ * remote storage re-throws the worker's error serialised across the worker
33
+ * boundary as a plain `Error` whose message embeds the original name as JSON,
34
+ * so a substring match (`includes`, not `startsWith`) is needed to still
35
+ * recognise it.
36
+ *
37
+ * A worker that crashes mid-call never replies (RxDB `storage-remote`,
38
+ * 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
39
+ */
40
+ export function isStorageWorkerFailure(error: unknown): boolean {
41
+ return error instanceof Error
42
+ && (error.name === 'StorageWorkerStartError' || error.message.includes('StorageWorkerStartError'));
43
+ }
44
+
45
+ const READ_METHODS = ['query', 'count', 'findDocumentsById', 'getChangedDocumentsSince'] as const;
46
+
47
+ /**
48
+ * Wraps a storage so its instances report health on `health$` (ADR-061,
49
+ * following WCPOS). No storage call is ever settled on a clock: a timed-out
50
+ * write may still commit, so a slow write is only flagged as `stalled`, and
51
+ * its promise stays pending until the worker answers. Reads are watched: two
52
+ * consecutive `readWatchdogMs` windows in which reads were pending and no
53
+ * call settled mark the worker `dead` (sticky; the recovery is reload).
54
+ * `createStorageInstance` has no deadline, because the worker and wasm can be
55
+ * slow to download.
56
+ *
57
+ * Instance methods are replaced in place, the way RxDB's own validator wraps
58
+ * `bulkWrite`, so a later wrapper that assigns over ours calls ours, not itself.
59
+ * The `tallyEngine` marker is kept.
60
+ */
61
+ export function withStorageWatchdog(
62
+ storage: RxStorage<any, any>,
63
+ options: StorageWatchdogOptions = {},
64
+ ): RxStorage<any, any> & { health$: Observable<StorageHealth> } {
65
+ const {
66
+ writeStallMs = STORAGE_WRITE_STALL_MS,
67
+ readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
68
+ now = Date.now,
69
+ setTimer = (fn, ms) => { const timer = setTimeout(fn, ms); return () => clearTimeout(timer); },
70
+ } = options;
71
+ const health$ = new BehaviorSubject<StorageHealth>({ status: 'ok', stalledWrites: 0 });
72
+ const stalledStarts: number[] = [];
73
+ let dead = false;
74
+ let pendingReads = 0;
75
+ let silentWindows = 0;
76
+ let settledThisWindow = false;
77
+ let cancelReadTimer: (() => void) | undefined;
78
+
79
+ const emit = () => health$.next({
80
+ status: dead ? 'dead' : stalledStarts.length > 0 ? 'stalled' : 'ok',
81
+ stalledWrites: stalledStarts.length,
82
+ ...(stalledStarts.length > 0 ? { stalledSince: Math.min(...stalledStarts) } : {}),
83
+ });
84
+ const settled = () => { settledThisWindow = true; silentWindows = 0; };
85
+
86
+ // Ticks only while a read is pending, and stops once dead (sticky). A window
87
+ // is silent when nothing settled during it.
88
+ const armReadTimer = () => {
89
+ settledThisWindow = false;
90
+ cancelReadTimer = setTimer(() => {
91
+ cancelReadTimer = undefined;
92
+ silentWindows = settledThisWindow ? 0 : silentWindows + 1;
93
+ if (silentWindows >= 2) { dead = true; emit(); } else armReadTimer();
94
+ }, readWatchdogMs);
95
+ };
96
+
97
+ const watchWrite = <T>(promise: Promise<T>): Promise<T> => {
98
+ const start = now();
99
+ let stalled = false;
100
+ const cancel = setTimer(() => { stalled = true; stalledStarts.push(start); emit(); }, writeStallMs);
101
+ const done = () => {
102
+ cancel();
103
+ settled();
104
+ if (stalled) { stalledStarts.splice(stalledStarts.indexOf(start), 1); emit(); }
105
+ };
106
+ promise.then(done, done);
107
+ return promise;
108
+ };
109
+
110
+ const watchRead = <T>(promise: Promise<T>): Promise<T> => {
111
+ if (pendingReads++ === 0 && !dead) armReadTimer();
112
+ const done = () => {
113
+ settled();
114
+ if (--pendingReads === 0) { cancelReadTimer?.(); cancelReadTimer = undefined; }
115
+ };
116
+ promise.then(done, done);
117
+ return promise;
118
+ };
119
+
120
+ return Object.assign(Object.create(storage), {
121
+ health$: health$.asObservable(),
122
+ async createStorageInstance(params: any) {
123
+ const instance: any = await storage.createStorageInstance(params);
124
+ const originalBulkWrite = instance.bulkWrite.bind(instance);
125
+ instance.bulkWrite = (...args: any[]) => watchWrite(originalBulkWrite(...args));
126
+ for (const method of READ_METHODS) {
127
+ if (typeof instance[method] !== 'function') continue;
128
+ const original = instance[method].bind(instance);
129
+ instance[method] = (...args: any[]) => watchRead(original(...args));
130
+ }
131
+ return instance;
132
+ },
133
+ });
134
+ }
package/src/storage.ts CHANGED
@@ -4,7 +4,8 @@ import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';
4
4
  /**
5
5
  * Returns the appropriate RxDB storage adapter for the current platform.
6
6
  *
7
- * - Web browser: Dexie (IndexedDB)
7
+ * - Web browser: throws with guidance to pass the SQLite-wasm storage
8
+ * explicitly (ADR-061) — there is no default web storage any more.
8
9
  * - React Native: throws with guidance to provide SQLite storage explicitly
9
10
  * - Node/SSR/test: In-memory
10
11
  *
@@ -26,8 +27,13 @@ export function getStorage(): RxStorage<any, any> {
26
27
  );
27
28
  }
28
29
 
29
- // Web browser — use Dexie (IndexedDB)
30
- // Dynamic import avoided here; Dexie is bundled with rxdb.
31
- const { getRxStorageDexie } = require('rxdb/plugins/storage-dexie');
32
- return getRxStorageDexie();
30
+ // Web browser (ADR-061, breaking): the web storage is no longer Dexie.
31
+ // getStorage() can't build it itself — it needs a worker entry the app's
32
+ // own bundler emits — so pass it explicitly.
33
+ throw new Error(
34
+ 'Web storage is RxDB Premium SQLite-wasm, not Dexie (ADR-061). Pass it explicitly, bundling the worker entry:\n' +
35
+ ' import { getRxStorageSQLiteWasm } from "@tallyui/storage-sqlite/web";\n' +
36
+ ' const workerInput = new URL("@tallyui/storage-sqlite/web-worker", import.meta.url);\n' +
37
+ ' createTallyDatabase({ connector, storage: getRxStorageSQLiteWasm({ workerInput }) })'
38
+ );
33
39
  }