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