@tallyui/database 2.0.0 → 3.0.0-next.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/database",
3
- "version": "2.0.0",
3
+ "version": "3.0.0-next.1",
4
4
  "type": "module",
5
5
  "description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
6
6
  "main": "./dist/index.js",
@@ -25,11 +25,11 @@
25
25
  "directory": "packages/database"
26
26
  },
27
27
  "dependencies": {
28
- "rxdb": "16.21.1",
28
+ "rxdb": "17.5.0",
29
29
  "rxjs": "7.8.2"
30
30
  },
31
31
  "peerDependencies": {
32
- "@tallyui/core": "2.0.0"
32
+ "@tallyui/core": "^3.0.0-next.1"
33
33
  },
34
34
  "scripts": {
35
35
  "build": "tsup",
@@ -0,0 +1,414 @@
1
+ import type { MangoQuery, RxCollection } from 'rxdb';
2
+ import { BehaviorSubject, type Observable } from 'rxjs';
3
+
4
+ import { errorKind, type CatalogueReconcileAdapter, type SyncContext } from '@tallyui/core';
5
+ import { readFresh } from '@tallyui/core/rxdb';
6
+
7
+ import { BACKGROUND_CHUNK_SIZE, pauseBetweenChunks, readFreshInChunks } from './chunks';
8
+ import { createPassQueue } from './pass-queue';
9
+ import { MAX_RETRY_AFTER_MS, retryAfter } from './replication';
10
+
11
+ /**
12
+ * Below this count of tombstones the brake never applies, whatever
13
+ * `maxDeleteShare` says: in a small shop, deleting 2 of 5 products is normal.
14
+ */
15
+ const MASS_DELETE_MINIMUM = 10;
16
+ /** The longest time between gate checks; a shorter interval checks at half of it (see `checkEveryMs`). */
17
+ const MAX_CHECK_EVERY_MS = 3_600_000;
18
+ /** The shortest time between gate checks, whatever `intervalMs` says. */
19
+ const MIN_CHECK_EVERY_MS = 60_000;
20
+ /** A transient error's first retry; it doubles, up to MAX_RETRY_AFTER_MS (1 hour). */
21
+ const FIRST_RETRY_MS = 5 * 60_000;
22
+ /** The request budget's window. */
23
+ const BUDGET_WINDOW_MS = 60_000;
24
+ /** Most keys one log event lists; `count` is always the full number. */
25
+ const LOG_KEYS = 50;
26
+ /** After a pull gap this long the app should call `reconcile()` (see `shouldReconcileAfterGap`). */
27
+ export const CATALOGUE_OFFLINE_GAP_MS = 6 * 3_600_000;
28
+
29
+ /** What a pass did, for the till's sync log (#248 A3). There is no cashier notice. */
30
+ export type CatalogueReconcileEvent =
31
+ | { type: 'pass-started'; resumed: boolean }
32
+ | { type: 'refetched'; count: number; keys: string[] }
33
+ | { type: 'tombstoned'; count: number; keys: string[] }
34
+ | { type: 'kept'; count: number; keys: string[]; reason: 'unconfirmed' | 'resumed-pass' }
35
+ /** `message` tells the store owner, in plain words and without naming a backend, what was kept and why. */
36
+ | { type: 'kept'; count: number; keys: string[]; reason: 'brake'; message: string }
37
+ | ({ type: 'pass-completed' } & CatalogueReconcileSummary)
38
+ | { type: 'stopped'; reason: 'till' | 'store' | 'transient' | 'stopped'; code?: string }
39
+ | { type: 'skipped'; reason: 'gate' | 'store' };
40
+
41
+ export interface CatalogueReconcileSummary {
42
+ pages: number;
43
+ /** Listed documents the till holds. */
44
+ compared: number;
45
+ /** Differing or missing documents handed to the pull. */
46
+ refetched: number;
47
+ tombstoned: number;
48
+ /** Deletion candidates kept: unconfirmed, or held by the brake. */
49
+ kept: number;
50
+ /** Local documents the listing did not name; only a result with `complete` has a real count. */
51
+ unlisted: number;
52
+ /** True when the pass ran from its first page to its last in one go, so `unlisted` is a real count; false for a resumed pass, whose `unlisted` is 0 and must not be shown as current (medusapos/app#160). */
53
+ complete: boolean;
54
+ durationMs: number;
55
+ }
56
+
57
+ /** In memory; the gate itself is persisted. `lastResult` is current when `lastResultAt > (lastErrorAt ?? 0)`. */
58
+ export interface CatalogueReconcileState {
59
+ running: boolean;
60
+ lastResult?: CatalogueReconcileSummary;
61
+ lastResultAt?: number;
62
+ /** When the last complete pass finished (persisted). A result without `complete` is not current. */
63
+ lastCompleteAt?: number;
64
+ lastError?: unknown;
65
+ lastErrorAt?: number;
66
+ }
67
+
68
+ export interface StartCatalogueReconcileOptions<Doc, Cursor = unknown> {
69
+ /** The replicated collection, created with `connectorCollection` (local documents on). Only read. */
70
+ collection: RxCollection<Doc>;
71
+ adapter: CatalogueReconcileAdapter<Doc, Cursor>;
72
+ context: SyncContext;
73
+ /** The app's `() => replication.reSync()`; called once per page that enqueued anything, and once for the tombstones. */
74
+ reSync: () => void;
75
+ /**
76
+ * Requests allowed in any 60 s window (default 30): each page, each `confirmGone` chunk, and the refetch requests
77
+ * each page that enqueued anything causes (the pull's `fetchByIds`: `ceil(n / adapter.refetchBatchSize)`, or 1 when unset).
78
+ */
79
+ requestsPerMinute?: number;
80
+ /** Most candidates per `confirmGone` call (default 100); each call takes one budget slot. */
81
+ confirmChunk?: number;
82
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
83
+ intervalMs?: number;
84
+ /** The first gate check after start (default 120000); then one every `min(1 hour, intervalMs / 2)`, and at least a minute. */
85
+ startDelayMs?: number;
86
+ /** The brake holds deletion candidates above this share of local documents (and above 10), unless `allowMassDelete`. */
87
+ maxDeleteShare?: number;
88
+ allowMassDelete?: boolean;
89
+ log?: (event: CatalogueReconcileEvent) => void;
90
+ now?: () => number;
91
+ /** The local document holding the gate and cursor (default 'catalogue-reconcile'); one per runner on a collection. */
92
+ stateId?: string;
93
+ /** Tests: schedules `fn` after `ms` and returns its cancel (default setTimeout). */
94
+ setTimer?: (fn: () => void, ms: number) => () => void;
95
+ }
96
+
97
+ /** True when the last successful pull is older than `offlineGapMs`: the app should then call `reconcile()`. */
98
+ export function shouldReconcileAfterGap(lastPullAt: number | undefined, now = Date.now(), offlineGapMs = CATALOGUE_OFFLINE_GAP_MS): boolean {
99
+ return lastPullAt !== undefined && now - lastPullAt > offlineGapMs;
100
+ }
101
+
102
+ interface PassState { startedAt: number; cursor?: unknown; uninterrupted: boolean }
103
+ interface Persisted { lastCompletedAt?: number; lastCompleteAt?: number; pass?: PassState }
104
+
105
+ // The state ids in use per collection: two runners sharing one would share a cursor.
106
+ const claimed = new WeakMap<object, Set<string>>();
107
+
108
+ /**
109
+ * The daily catalogue check (#248, ADR-060). Walks the remote listing page by
110
+ * page within a request budget, refetches what differs through the pull, and
111
+ * deletes only after a pass that ran from first page to last in one go, only
112
+ * what `confirmGone` confirms, and only under the mass-delete brake. Never
113
+ * writes the collection; its gate and cursor live in a local document.
114
+ */
115
+ export function startCatalogueReconcile<Doc, Cursor = unknown>(options: StartCatalogueReconcileOptions<Doc, Cursor>): {
116
+ reconcile(): void;
117
+ state$: Observable<CatalogueReconcileState>;
118
+ stop(): void;
119
+ } {
120
+ const { request, state$, stop } = startCatalogueRunner(options);
121
+ // The runner logs and schedules every failure; only the wrappers need the promise.
122
+ return { reconcile: () => { request().catch(() => {}); }, state$, stop };
123
+ }
124
+
125
+ /** The runner behind `startCatalogueReconcile` and the id and fingerprint wrappers; `request()` resolves with the pass. */
126
+ export function startCatalogueRunner<Doc, Cursor = unknown>({
127
+ collection, adapter, context, reSync, requestsPerMinute = 30, confirmChunk = 100, intervalMs = 86_400_000, startDelayMs = 120_000,
128
+ maxDeleteShare = 0.2, allowMassDelete = false, log = () => {}, now = Date.now, stateId = 'catalogue-reconcile',
129
+ setTimer = (fn, ms) => { const timer = setTimeout(fn, ms); return () => clearTimeout(timer); }, keepCandidates = false,
130
+ }: Omit<StartCatalogueReconcileOptions<Doc, Cursor>, 'startDelayMs'> & {
131
+ /** `null`: no start check, only the periodic ones. */
132
+ startDelayMs?: number | null;
133
+ /**
134
+ * Never delete (the fingerprint wrapper): candidates are only counted as `unlisted`, before the
135
+ * brake and confirmGone, so nothing is logged about them and no budget slot is taken.
136
+ */
137
+ keepCandidates?: boolean;
138
+ }) {
139
+ const controller = new AbortController();
140
+ const { signal } = controller;
141
+ // React Native's AbortController polyfill has no throwIfAborted() and may have no reason.
142
+ const checkAborted = () => { if (signal.aborted) throw signal.reason ?? new Error('Catalogue reconcile stopped'); };
143
+ const ctx = { ...context, signal };
144
+ const primary = collection.schema.primaryPath as string;
145
+ const keyOf = (doc: Doc) => (doc as Record<string, unknown>)[primary] as string;
146
+ const listed = (keys: string[]) => ({ count: keys.length, keys: keys.slice(0, LOG_KEYS) });
147
+ const state = new BehaviorSubject<CatalogueReconcileState>({ running: false });
148
+ const update = (patch: Partial<CatalogueReconcileState>) => state.next({ ...state.value, ...patch });
149
+
150
+ // The gate and cursor: a local document, never replicated. A collection without local
151
+ // documents, or a state id another runner holds, keeps them in memory instead.
152
+ const ids = claimed.get(collection) ?? new Set<string>();
153
+ claimed.set(collection, ids);
154
+ const owner = !ids.has(stateId);
155
+ let memory: Persisted | undefined;
156
+ if (owner) ids.add(stateId);
157
+ else {
158
+ memory = {};
159
+ console.warn(`Catalogue reconcile: "${stateId}" is in use on ${collection.name}; pass a distinct stateId. This gate is kept in memory.`);
160
+ }
161
+ const load = async (): Promise<Persisted> => {
162
+ if (memory) return memory;
163
+ try {
164
+ const doc = await collection.getLocal<Persisted>(stateId);
165
+ return doc ? { lastCompletedAt: doc.get('lastCompletedAt'), lastCompleteAt: doc.get('lastCompleteAt'), pass: doc.get('pass') } : {};
166
+ } catch (error) {
167
+ // LD8: local documents are off; no getLocal at all: the plugin was never added.
168
+ if (typeof collection.getLocal === 'function' && (error as { code?: unknown } | null)?.code !== 'LD8') throw error;
169
+ console.warn(`Catalogue reconcile: ${collection.name} has no local documents (create it with connectorCollection); the gate is kept in memory.`);
170
+ return (memory = {});
171
+ }
172
+ };
173
+ // JSON drops undefined fields and proves the cursor serialisable.
174
+ const save = async (value: Persisted) => {
175
+ if (memory) memory = value;
176
+ else await collection.upsertLocal(stateId, JSON.parse(JSON.stringify(value)));
177
+ };
178
+ load().then(({ lastCompleteAt }) => { if (lastCompleteAt !== undefined) update({ lastCompleteAt }); }).catch(() => {});
179
+
180
+ const sleep = (ms: number) => new Promise<void>((resolve) => {
181
+ const onAbort = () => { cancel(); resolve(); };
182
+ const cancel = setTimer(() => { signal.removeEventListener('abort', onAbort); resolve(); }, ms);
183
+ signal.addEventListener('abort', onAbort);
184
+ });
185
+ // The request budget: a sliding window of adapter calls, so no 60 s window holds more than
186
+ // requestsPerMinute. Each page, each confirmGone call and each of a page's refetch requests counts as one. It bounds the pass, not a page cap.
187
+ const sent: number[] = [];
188
+ const budget = async () => {
189
+ for (;;) {
190
+ checkAborted();
191
+ while (sent.length && sent[0] <= now() - BUDGET_WINDOW_MS) sent.shift();
192
+ if (sent.length < requestsPerMinute) { sent.push(now()); return; }
193
+ await sleep(sent[0] + BUDGET_WINDOW_MS - now());
194
+ }
195
+ };
196
+ // Local copies of one page's keys, read fresh in bounded chunks that yield between reads.
197
+ const readByKeys = async (keys: string[]) => {
198
+ const found = new Map<string, Doc>();
199
+ for (let i = 0; i < keys.length; i += BACKGROUND_CHUNK_SIZE) {
200
+ if (i) await pauseBetweenChunks();
201
+ checkAborted();
202
+ const selector = { [primary]: { $in: keys.slice(i, i + BACKGROUND_CHUNK_SIZE) } };
203
+ for (const doc of await readFresh(collection, { selector } as MangoQuery<Doc>)) found.set(keyOf(doc), doc);
204
+ }
205
+ return found;
206
+ };
207
+ // A wrong channel token or a permissions change must never empty a shop's catalogue.
208
+ const braked = (tombstones: number, localCount: number) => !allowMassDelete && localCount > 0
209
+ && (tombstones === localCount || (tombstones > MASS_DELETE_MINIMUM && tombstones > maxDeleteShare * localCount));
210
+
211
+ const pass = async (): Promise<CatalogueReconcileSummary> => {
212
+ checkAborted();
213
+ const startedAt = now();
214
+ const saved = await load();
215
+ // A stored pass that finished no page has no cursor. Restarting it re-reads from the first page,
216
+ // so it runs uninterrupted. A resumed pass never deletes: earlier keys are not kept.
217
+ const resumed = Boolean(saved.pass && saved.pass.cursor !== undefined && startedAt - saved.pass.startedAt < intervalMs);
218
+ let current: PassState = resumed ? { ...saved.pass!, uninterrupted: false } : { startedAt, uninterrupted: true };
219
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
220
+ log({ type: 'pass-started', resumed });
221
+
222
+ // The listing's keys; with adapter.matchKey these are match keys, not primary keys (#313).
223
+ const seen = new Set<string>();
224
+ // With matchKey: match key to primary key, built at the first page of each pass (a resumed one too). Strings only.
225
+ let index: Map<string, string> | undefined;
226
+ const buildIndex = async (matchKey: (doc: Doc) => string | undefined) => {
227
+ const built = new Map<string, string>();
228
+ for await (const chunk of readFreshInChunks(collection)) {
229
+ checkAborted();
230
+ for (const doc of chunk) {
231
+ const match = matchKey(doc);
232
+ // On a duplicate match key the first document wins.
233
+ if (match !== undefined && !built.has(match)) built.set(match, keyOf(doc));
234
+ }
235
+ }
236
+ return built;
237
+ };
238
+ let pages = 0;
239
+ let compared = 0;
240
+ let refetched = 0;
241
+ const iterator = adapter.fetchPages(ctx, current.cursor as Cursor)[Symbol.asyncIterator]();
242
+ try {
243
+ for (;;) {
244
+ await budget();
245
+ const next = await iterator.next();
246
+ checkAborted();
247
+ if (next.done) break;
248
+ pages++;
249
+ const { entries, cursor } = next.value;
250
+ const byMatch = adapter.matchKey ? (index ??= await buildIndex(adapter.matchKey.bind(adapter))) : undefined;
251
+ const primaries = entries.map((e) => (byMatch ? byMatch.get(e.key) : e.key));
252
+ const locals = await readByKeys(primaries.filter((key): key is string => key !== undefined));
253
+ const queue: Array<{ key: string; local?: Doc; remote?: unknown }> = [];
254
+ entries.forEach(({ key, fingerprint, remote }, i) => {
255
+ seen.add(key);
256
+ const local = primaries[i] === undefined ? undefined : locals.get(primaries[i]!);
257
+ if (local) compared++;
258
+ // A remote-only entry keeps the listing's key.
259
+ if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key: local ? keyOf(local) : key, local, remote });
260
+ });
261
+ checkAborted();
262
+ if (queue.length) {
263
+ // The refetch this page causes runs in the pull, outside the runner: its slots, one per fetchByIds request
264
+ // (#307), are taken before it is enqueued. A size that is unset or not positive counts as one request.
265
+ const size = adapter.refetchBatchSize;
266
+ const slots = size !== undefined && size > 0 ? Math.max(1, Math.ceil(queue.length / size)) : 1;
267
+ for (let slot = 0; slot < slots; slot++) await budget();
268
+ adapter.enqueue(queue);
269
+ reSync();
270
+ refetched += queue.length;
271
+ log({ type: 'refetched', ...listed(queue.map((e) => e.key)) });
272
+ }
273
+ current = { ...current, cursor };
274
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
275
+ }
276
+ } finally {
277
+ iterator.return?.()?.catch(() => {});
278
+ }
279
+
280
+ let tombstoned = 0;
281
+ let kept = 0;
282
+ let unlisted = 0;
283
+ const keep = (docs: Doc[], why: { reason: 'unconfirmed' } | { reason: 'brake'; message: string }) => {
284
+ kept += docs.length;
285
+ if (docs.length) log({ type: 'kept', ...listed(docs.map(keyOf)), ...why });
286
+ };
287
+ if (!current.uninterrupted) log({ type: 'kept', count: 0, keys: [], reason: 'resumed-pass' });
288
+ else {
289
+ // Local documents the listing never named are candidates; only confirmed ones may go.
290
+ const candidates: Doc[] = [];
291
+ let localCount = 0;
292
+ for await (const chunk of readFreshInChunks(collection)) {
293
+ checkAborted();
294
+ localCount += chunk.length;
295
+ for (const doc of chunk) {
296
+ const key = adapter.matchKey ? adapter.matchKey(doc) : keyOf(doc);
297
+ if (key === undefined || !seen.has(key)) candidates.push(doc);
298
+ }
299
+ }
300
+ unlisted = candidates.length;
301
+ // The brake applies to the candidates, before confirmGone: a broken listing never sends
302
+ // thousands of confirmation requests, and whatever confirmGone confirms stays under it.
303
+ let gone: Doc[] = [];
304
+ if (!candidates.length || keepCandidates) {
305
+ // Nothing to prove, or nothing will ever be deleted: the candidates are only counted.
306
+ } else if (braked(candidates.length, localCount)) {
307
+ // One candidate brakes only when it is the till's whole catalogue (see braked).
308
+ const one = candidates.length === 1;
309
+ const message = (one
310
+ ? 'The only product on this till is no longer listed by the online store, so it was kept: removing everything at once needs a check. '
311
+ : `${candidates.length} products the online store no longer lists were kept on this till: removing that many at once needs a check. `)
312
+ + `If ${one ? 'it was' : 'they were'} hidden or removed on purpose, the person who manages this till can allow the removal.`;
313
+ console.warn(`Catalogue reconcile: ${message} (pass allowMassDelete: true to the reconcile runner to apply it)`);
314
+ keep(candidates, { reason: 'brake', message });
315
+ } else {
316
+ // In chunks of confirmChunk, each taking one budget slot, so a connector never bursts.
317
+ const confirmed = new Set<string>();
318
+ for (let i = 0; i < candidates.length; i += confirmChunk) {
319
+ const chunk = candidates.slice(i, i + confirmChunk);
320
+ await budget();
321
+ for (const key of await adapter.confirmGone(chunk, ctx)) confirmed.add(key);
322
+ checkAborted();
323
+ }
324
+ gone = candidates.filter((doc) => confirmed.has(keyOf(doc)));
325
+ const goneSet = new Set(gone);
326
+ keep(candidates.filter((doc) => !goneSet.has(doc)), { reason: 'unconfirmed' });
327
+ }
328
+ if (gone.length) {
329
+ adapter.enqueue(gone.map((local) => ({ key: keyOf(local), local, tombstone: true })));
330
+ reSync();
331
+ tombstoned = gone.length;
332
+ log({ type: 'tombstoned', ...listed(gone.map(keyOf)) });
333
+ }
334
+ }
335
+
336
+ checkAborted();
337
+ const lastCompletedAt = now();
338
+ await save({ lastCompletedAt, lastCompleteAt: current.uninterrupted ? lastCompletedAt : saved.lastCompleteAt });
339
+ const summary = { pages, compared, refetched, tombstoned, kept, unlisted, complete: current.uninterrupted, durationMs: lastCompletedAt - startedAt };
340
+ log({ type: 'pass-completed', ...summary });
341
+ return summary;
342
+ };
343
+
344
+ // Errors by who can fix them (errorKind). A stopped pass keeps its cursor and resumes.
345
+ let failures = 0;
346
+ let tillStopped = false;
347
+ let cancelRetry: (() => void) | undefined;
348
+ const onError = (error: unknown) => {
349
+ if (signal.aborted) return log({ type: 'stopped', reason: 'stopped' });
350
+ const kind = errorKind(error);
351
+ // store: skipped until the next hourly check.
352
+ if (kind === 'store') return log({ type: 'skipped', reason: 'store' });
353
+ const code = (error as { code?: unknown } | null)?.code;
354
+ log({ type: 'stopped', reason: kind, ...(typeof code === 'string' && { code }) });
355
+ // till: no timer retries it; reconcile() (after sign-in) or the next start does.
356
+ if (kind === 'till') { tillStopped = true; return; }
357
+ // transient: a backoff from 5 minutes, doubling to an hour, or a longer valid retryAfterMs.
358
+ const delay = Math.min(Math.max(FIRST_RETRY_MS * 2 ** failures++, retryAfter(error)), MAX_RETRY_AFTER_MS);
359
+ cancelRetry = setTimer(() => { cancelRetry = undefined; run().catch(() => {}); }, delay);
360
+ };
361
+ const run = createPassQueue(async () => {
362
+ update({ running: true });
363
+ try {
364
+ const result = await pass();
365
+ failures = 0;
366
+ update({ running: false, lastResult: result, lastResultAt: now(), ...(result.complete && { lastCompleteAt: now() }) });
367
+ return result;
368
+ } catch (error) {
369
+ update({ running: false, lastError: error, lastErrorAt: now() });
370
+ onError(error);
371
+ throw error;
372
+ }
373
+ });
374
+
375
+ // The gate: a pass is due when none has completed within intervalMs, or one is pending resume.
376
+ const check = async () => {
377
+ if (tillStopped || cancelRetry || state.value.running) return;
378
+ const { lastCompletedAt, pass: pending } = await load();
379
+ if (pending || lastCompletedAt === undefined || now() - lastCompletedAt >= intervalMs) await run();
380
+ else log({ type: 'skipped', reason: 'gate' });
381
+ };
382
+ // Hourly, or at half the interval when that is shorter, so a 30-minute runner runs every 30 minutes.
383
+ // Never under a minute: a 0 or NaN interval would otherwise re-arm the check on every tick (NaN || 0 floors too).
384
+ const checkEveryMs = Math.max(MIN_CHECK_EVERY_MS, Math.min(MAX_CHECK_EVERY_MS, intervalMs / 2) || 0);
385
+ let cancelTimer = () => {};
386
+ const schedule = (ms: number) => {
387
+ cancelTimer = setTimer(() => {
388
+ schedule(checkEveryMs);
389
+ check().catch((error) => console.warn('Catalogue reconcile failed:', error));
390
+ }, ms);
391
+ };
392
+ schedule(startDelayMs ?? checkEveryMs);
393
+
394
+ // stop() and an abort of context.signal both end the runner for good.
395
+ const stop = () => {
396
+ cancelTimer();
397
+ cancelRetry?.();
398
+ if (owner) ids.delete(stateId);
399
+ context.signal?.removeEventListener('abort', stop);
400
+ controller.abort();
401
+ state.complete();
402
+ };
403
+ if (context.signal?.aborted) stop();
404
+ else context.signal?.addEventListener('abort', stop);
405
+
406
+ /** Requests a pass now: it clears a till stop and a pending retry, and folds into a running pass. */
407
+ const request = () => {
408
+ tillStopped = false;
409
+ cancelRetry?.();
410
+ cancelRetry = undefined;
411
+ return run();
412
+ };
413
+ return { request, state$: state.asObservable(), stop };
414
+ }
package/src/chunks.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { MangoQuery, RxCollection } from 'rxdb';
2
+ import { readFresh } from '@tallyui/core/rxdb';
3
+
4
+ /** Most documents per background-check storage read or write, so an app query waits behind at most one chunk.
5
+ * Perf spike: a 5,260-row write held the worker for 5.7 s. */
6
+ export const BACKGROUND_CHUNK_SIZE = 250;
7
+
8
+ /** Let the app's queued work run before the next chunk. */
9
+ export function pauseBetweenChunks(): Promise<void> {
10
+ return new Promise((resolve) => setTimeout(resolve, 0));
11
+ }
12
+
13
+ /** Read fresh storage data in ascending primary-key chunks, yielding to the event loop between reads. */
14
+ export async function* readFreshInChunks<T>(collection: RxCollection<T>, size = BACKGROUND_CHUNK_SIZE): AsyncGenerator<T[]> {
15
+ const key = collection.schema.primaryPath;
16
+ let after: string | undefined;
17
+ while (true) {
18
+ if (after !== undefined) await pauseBetweenChunks();
19
+ const chunk = await readFresh(collection, {
20
+ selector: after === undefined ? {} : { [key]: { $gt: after } },
21
+ sort: [{ [key]: 'asc' }],
22
+ limit: size,
23
+ } as MangoQuery<T>);
24
+ if (!chunk.length) return;
25
+ yield chunk;
26
+ if (chunk.length < size) return;
27
+ after = (chunk[chunk.length - 1] as Record<string, unknown>)[key] as string;
28
+ }
29
+ }
@@ -1,10 +1,13 @@
1
1
  import { addRxPlugin, type MigrationStrategies, type RxJsonSchema } from 'rxdb';
2
+ import { RxDBLocalDocumentsPlugin } from 'rxdb/plugins/local-documents';
2
3
  import { RxDBMigrationSchemaPlugin } from 'rxdb/plugins/migration-schema';
3
4
 
4
5
  /**
5
6
  * The collection config for a connector schema: the schema plus a `v => null`
6
7
  * strategy for every version from 1 to N (`{}` at version 0), so a version
7
8
  * bump drops the documents and replication resyncs them (see ConnectorSchemas).
9
+ * Local documents are on: the catalogue reconcile keeps its gate and resume
10
+ * cursor there (#248), since they are never replicated.
8
11
  *
9
12
  * Use this for any connector collection created outside `createTallyDatabase`
10
13
  * (tests, an app's own database). A connector schema above version 0 needs
@@ -12,9 +15,12 @@ import { RxDBMigrationSchemaPlugin } from 'rxdb/plugins/migration-schema';
12
15
  * "plugin missing". Never for local-only collections (`stock_levels`,
13
16
  * `pos_orders`): a drop would lose local data.
14
17
  */
15
- export function connectorCollection<T>(schema: RxJsonSchema<T>): { schema: RxJsonSchema<T>; migrationStrategies: MigrationStrategies } {
18
+ export function connectorCollection<T>(schema: RxJsonSchema<T>): {
19
+ schema: RxJsonSchema<T>; migrationStrategies: MigrationStrategies; localDocuments: true;
20
+ } {
16
21
  // addRxPlugin ignores a plugin it already has.
17
22
  addRxPlugin(RxDBMigrationSchemaPlugin);
23
+ addRxPlugin(RxDBLocalDocumentsPlugin);
18
24
  const migrationStrategies = Object.fromEntries(Array.from({ length: schema.version }, (_, i) => [i + 1, () => null]));
19
- return { schema, migrationStrategies };
25
+ return { schema, migrationStrategies, localDocuments: true };
20
26
  }
package/src/create-db.ts CHANGED
@@ -15,11 +15,6 @@ import { withStorageWatchdog, type StorageHealth } from './storage-watchdog';
15
15
  const DEV_MODE = process.env.NODE_ENV !== 'production';
16
16
  addRxPlugin(RxDBLocalDocumentsPlugin);
17
17
 
18
- // Enable dev mode in non-production
19
- if (DEV_MODE) {
20
- addRxPlugin(RxDBDevModePlugin);
21
- }
22
-
23
18
  /**
24
19
  * The shape of a Tally database — keyed by collection name.
25
20
  */
@@ -44,15 +39,19 @@ export interface CreateDatabaseOptions {
44
39
  * `reconcile.stock` also gets the `stock_levels` overlay collection.
45
40
  *
46
41
  * ```ts
47
- * import { woocommerceConnector } from '@tallyui/connector-woocommerce';
42
+ * import { createWooCommerceConnector } from '@tallyui/connector-woocommerce';
48
43
  * import { createTallyDatabase } from '@tallyui/database';
49
44
  *
50
- * const db = await createTallyDatabase({ connector: woocommerceConnector });
45
+ * const db = await createTallyDatabase({ connector: createWooCommerceConnector() });
51
46
  * const products = await db.products.find().exec();
52
47
  * ```
53
48
  */
54
49
  export async function createTallyDatabase(options: CreateDatabaseOptions): Promise<TallyDatabase> {
55
50
  if ((options as { multiInstance?: unknown }).multiInstance === true) throw new Error('multiInstance: true is unsupported: TallyUI databases are single-instance (ADR-061).');
51
+ // Dev mode in non-production, added here rather than at import: in a browser its init reads RxDB's
52
+ // premium flag, which RxDB caches, so at import it could cache false before the app's storage
53
+ // (getRxStorageSQLiteWasm) sets it, and RxDB 17's 13-collection cap would apply.
54
+ if (DEV_MODE) addRxPlugin(RxDBDevModePlugin);
56
55
  const {
57
56
  connector,
58
57
  name = `tally_${connector.id}`,