@tallyui/database 2.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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { RxStorage, RxDatabase, RxCollection, RxJsonSchema, MigrationStrategies } from 'rxdb';
2
2
  import { Observable } from 'rxjs';
3
- import { TallyConnector, ReplicationAdapter, SyncContext, StockReconcileAdapter, IdReconcileAdapter, FingerprintReconcileAdapter } from '@tallyui/core';
3
+ import { TallyConnector, ReplicationAdapter, SyncContext, SyncNotice, StockReconcileAdapter, CatalogueReconcileAdapter, IdReconcileAdapter, FingerprintReconcileAdapter } from '@tallyui/core';
4
4
  export { STOCK_LEVELS_LAST_PASS } from '@tallyui/core';
5
5
  import { RxReplicationState } from 'rxdb/plugins/replication';
6
6
 
@@ -33,6 +33,10 @@ interface StorageWatchdogOptions {
33
33
  * so a substring match (`includes`, not `startsWith`) is needed to still
34
34
  * recognise it.
35
35
  *
36
+ * RxDB's RM1 (a stale worker built on another RxDB version, e.g. cached from
37
+ * before an upgrade) is one too: reloading loads the matching worker. The
38
+ * check is `isRxdbRemoteVersionMismatch` from `@tallyui/core`.
39
+ *
36
40
  * A worker that crashes mid-call never replies (RxDB `storage-remote`,
37
41
  * 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
38
42
  */
@@ -77,10 +81,10 @@ interface CreateDatabaseOptions {
77
81
  * `reconcile.stock` also gets the `stock_levels` overlay collection.
78
82
  *
79
83
  * ```ts
80
- * import { woocommerceConnector } from '@tallyui/connector-woocommerce';
84
+ * import { createWooCommerceConnector } from '@tallyui/connector-woocommerce';
81
85
  * import { createTallyDatabase } from '@tallyui/database';
82
86
  *
83
- * const db = await createTallyDatabase({ connector: woocommerceConnector });
87
+ * const db = await createTallyDatabase({ connector: createWooCommerceConnector() });
84
88
  * const products = await db.products.find().exec();
85
89
  * ```
86
90
  */
@@ -96,6 +100,8 @@ declare function getStorageHealth(db: TallyDatabase): Observable<StorageHealth>
96
100
  * The collection config for a connector schema: the schema plus a `v => null`
97
101
  * strategy for every version from 1 to N (`{}` at version 0), so a version
98
102
  * bump drops the documents and replication resyncs them (see ConnectorSchemas).
103
+ * Local documents are on: the catalogue reconcile keeps its gate and resume
104
+ * cursor there (#248), since they are never replicated.
99
105
  *
100
106
  * Use this for any connector collection created outside `createTallyDatabase`
101
107
  * (tests, an app's own database). A connector schema above version 0 needs
@@ -106,6 +112,7 @@ declare function getStorageHealth(db: TallyDatabase): Observable<StorageHealth>
106
112
  declare function connectorCollection<T>(schema: RxJsonSchema<T>): {
107
113
  schema: RxJsonSchema<T>;
108
114
  migrationStrategies: MigrationStrategies;
115
+ localDocuments: true;
109
116
  };
110
117
 
111
118
  /**
@@ -137,14 +144,23 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
137
144
  retryTime?: number;
138
145
  /** Start immediately (default: true) */
139
146
  autoStart?: boolean;
147
+ /** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
148
+ maxRetryTimeMs?: number;
140
149
  }
150
+ /** RxDB's replication state plus the pull notice and a way to restart after a till error. */
151
+ type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
152
+ /** A notice while a till or store error stops the pull; `undefined` otherwise. */
153
+ notice$: Observable<SyncNotice | undefined>;
154
+ /** Clears the notice, the gates and the backoff, and pulls again from the stored checkpoint. */
155
+ resume(): Promise<void>;
156
+ };
141
157
  /**
142
158
  * Start RxDB replication for a single collection using a ReplicationAdapter.
143
159
  *
144
160
  * Returns the RxReplicationState which exposes observables for monitoring
145
161
  * and methods like cancel(), awaitInSync(), reSync().
146
162
  */
147
- declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, }: StartReplicationOptions<RxDocType, CheckpointType>): RxReplicationState<RxDocType, CheckpointType>;
163
+ declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
148
164
 
149
165
  /**
150
166
  * ADR-061: exactly one live tab per store, and a second tab never opens
@@ -250,6 +266,8 @@ interface StockReconcileState {
250
266
  * follow-up pass (later calls share it), so a change made after the pass
251
267
  * read is picked up straight after, not at the next interval. stop() clears
252
268
  * the timer and aborts a running pass.
269
+ * A stop during writes leaves earlier chunks written and `last-pass` unchanged.
270
+ * ADR-060: these server-truth passes are idempotent, so the next pass finishes what a stopped pass left.
253
271
  */
254
272
  declare function startStockReconcile({ collection, adapter, context, intervalMs, maxPages, }: StartStockReconcileOptions): {
255
273
  reconcileStock(): Promise<StockReconcileResult>;
@@ -257,6 +275,107 @@ declare function startStockReconcile({ collection, adapter, context, intervalMs,
257
275
  state$: Observable<StockReconcileState>;
258
276
  };
259
277
 
278
+ /** After a pull gap this long the app should call `reconcile()` (see `shouldReconcileAfterGap`). */
279
+ declare const CATALOGUE_OFFLINE_GAP_MS: number;
280
+ /** What a pass did, for the till's sync log (#248 A3). There is no cashier notice. */
281
+ type CatalogueReconcileEvent = {
282
+ type: 'pass-started';
283
+ resumed: boolean;
284
+ } | {
285
+ type: 'refetched';
286
+ count: number;
287
+ keys: string[];
288
+ } | {
289
+ type: 'tombstoned';
290
+ count: number;
291
+ keys: string[];
292
+ } | {
293
+ type: 'kept';
294
+ count: number;
295
+ keys: string[];
296
+ reason: 'unconfirmed' | 'resumed-pass';
297
+ }
298
+ /** `message` tells the store owner, in plain words and without naming a backend, what was kept and why. */
299
+ | {
300
+ type: 'kept';
301
+ count: number;
302
+ keys: string[];
303
+ reason: 'brake';
304
+ message: string;
305
+ } | ({
306
+ type: 'pass-completed';
307
+ } & CatalogueReconcileSummary) | {
308
+ type: 'stopped';
309
+ reason: 'till' | 'store' | 'transient' | 'stopped';
310
+ code?: string;
311
+ } | {
312
+ type: 'skipped';
313
+ reason: 'gate' | 'store';
314
+ };
315
+ interface CatalogueReconcileSummary {
316
+ pages: number;
317
+ /** Listed documents the till holds. */
318
+ compared: number;
319
+ /** Differing or missing documents handed to the pull. */
320
+ refetched: number;
321
+ tombstoned: number;
322
+ /** Deletion candidates kept: unconfirmed, or held by the brake. */
323
+ kept: number;
324
+ /** Local documents the listing did not name, counted in an uninterrupted pass (0 in a resumed one). */
325
+ unlisted: number;
326
+ durationMs: number;
327
+ }
328
+ /** In memory; the gate itself is persisted. `lastResult` is current when `lastResultAt > (lastErrorAt ?? 0)`. */
329
+ interface CatalogueReconcileState {
330
+ running: boolean;
331
+ lastResult?: CatalogueReconcileSummary;
332
+ lastResultAt?: number;
333
+ lastError?: unknown;
334
+ lastErrorAt?: number;
335
+ }
336
+ interface StartCatalogueReconcileOptions<Doc, Cursor = unknown> {
337
+ /** The replicated collection, created with `connectorCollection` (local documents on). Only read. */
338
+ collection: RxCollection<Doc>;
339
+ adapter: CatalogueReconcileAdapter<Doc, Cursor>;
340
+ context: SyncContext;
341
+ /** The app's `() => replication.reSync()`; called once per page that enqueued anything, and once for the tombstones. */
342
+ reSync: () => void;
343
+ /**
344
+ * Requests allowed in any 60 s window (default 30): each page, each `confirmGone` chunk, and the refetch requests
345
+ * each page that enqueued anything causes (the pull's `fetchByIds`: `ceil(n / adapter.refetchBatchSize)`, or 1 when unset).
346
+ */
347
+ requestsPerMinute?: number;
348
+ /** Most candidates per `confirmGone` call (default 100); each call takes one budget slot. */
349
+ confirmChunk?: number;
350
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
351
+ intervalMs?: number;
352
+ /** The first gate check after start (default 120000); then one every `min(1 hour, intervalMs / 2)`, and at least a minute. */
353
+ startDelayMs?: number;
354
+ /** The brake holds deletion candidates above this share of local documents (and above 10), unless `allowMassDelete`. */
355
+ maxDeleteShare?: number;
356
+ allowMassDelete?: boolean;
357
+ log?: (event: CatalogueReconcileEvent) => void;
358
+ now?: () => number;
359
+ /** The local document holding the gate and cursor (default 'catalogue-reconcile'); one per runner on a collection. */
360
+ stateId?: string;
361
+ /** Tests: schedules `fn` after `ms` and returns its cancel (default setTimeout). */
362
+ setTimer?: (fn: () => void, ms: number) => () => void;
363
+ }
364
+ /** True when the last successful pull is older than `offlineGapMs`: the app should then call `reconcile()`. */
365
+ declare function shouldReconcileAfterGap(lastPullAt: number | undefined, now?: number, offlineGapMs?: number): boolean;
366
+ /**
367
+ * The daily catalogue check (#248, ADR-060). Walks the remote listing page by
368
+ * page within a request budget, refetches what differs through the pull, and
369
+ * deletes only after a pass that ran from first page to last in one go, only
370
+ * what `confirmGone` confirms, and only under the mass-delete brake. Never
371
+ * writes the collection; its gate and cursor live in a local document.
372
+ */
373
+ declare function startCatalogueReconcile<Doc, Cursor = unknown>(options: StartCatalogueReconcileOptions<Doc, Cursor>): {
374
+ reconcile(): void;
375
+ state$: Observable<CatalogueReconcileState>;
376
+ stop(): void;
377
+ };
378
+
260
379
  interface StartIdReconcileOptions<Doc> {
261
380
  /** The replicated products collection. Read only. */
262
381
  collection: RxCollection<Doc>;
@@ -264,20 +383,23 @@ interface StartIdReconcileOptions<Doc> {
264
383
  context: SyncContext;
265
384
  /** The app's `() => replication.reSync()`. */
266
385
  reSync: () => void;
267
- /** Delay before the first pass (default 5000); `null` skips it. */
386
+ /** Delay before the first gate check (default 5000); `null` skips it and checks hourly. */
268
387
  startDelayMs?: number | null;
269
- /** Time between passes in ms (default 86400000, 24 hours). */
388
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
270
389
  intervalMs?: number;
271
- /** Pages read before a pass is truncated (default 100). */
390
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
272
391
  maxPages?: number;
273
392
  /**
274
- * The brake applies once would-be tombstones exceed this share of local
393
+ * The brake applies once tombstones exceed this share of local
275
394
  * products (default 0.2), unless `allowMassDelete` is set.
276
395
  */
277
396
  maxDeleteShare?: number;
278
397
  /** Explicit override for a genuine purge; disables the mass-delete brake. */
279
398
  allowMassDelete?: boolean;
399
+ /** The local document holding this runner's gate (default 'id-reconcile'). */
400
+ stateId?: string;
280
401
  }
402
+ /** `truncated` is always false now that no page cap applies. */
281
403
  interface IdReconcileResult {
282
404
  pages: number;
283
405
  queued: number;
@@ -286,15 +408,14 @@ interface IdReconcileResult {
286
408
  }
287
409
  /**
288
410
  * Compares live product/variant ids against the local `products` collection
289
- * and queues disagreeing documents for the collection's pull (ADR-060). Only
290
- * reads `collection`. A throw, abort, truncation or the mass-delete brake
291
- * (below) queues nothing and skips `reSync`; only a complete, un-braked pass
292
- * acts. One pass runs `startDelayMs` after start, then every `intervalMs`. A
293
- * call during a pass queues one follow-up pass (later calls share it), so a
294
- * change made after the pass read is picked up straight after, not at the
295
- * next interval.
411
+ * and queues disagreeing documents for the collection's pull (ADR-060), as a
412
+ * wrapper over the catalogue runner (#248): a product whose variant ids differ
413
+ * is refetched page by page; a product missing remotely is queued for deletion
414
+ * only after an uninterrupted pass and under the mass-delete brake. Passes
415
+ * follow the persisted daily gate within a request budget. A call during a
416
+ * pass queues one follow-up pass (later calls share it).
296
417
  */
297
- declare function startIdReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, maxDeleteShare, allowMassDelete, }: StartIdReconcileOptions<Doc>): {
418
+ declare function startIdReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartIdReconcileOptions<Doc>): {
298
419
  reconcileIds(): Promise<IdReconcileResult>;
299
420
  stop(): void;
300
421
  };
@@ -306,22 +427,28 @@ interface StartFingerprintReconcileOptions<Doc> {
306
427
  context: SyncContext;
307
428
  /** The app's `() => replication.reSync()`. */
308
429
  reSync: () => void;
309
- /** Delay before the first pass; `null` (default) skips it, since this runner is meant as a nightly backstop. */
430
+ /** Delay before the first gate check; `null` (default) skips it and checks hourly. */
310
431
  startDelayMs?: number | null;
311
- /** Time between passes in ms (default 86400000, 24 hours). */
432
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
312
433
  intervalMs?: number;
313
- /** Pages read before a pass is truncated (default 100). */
434
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
314
435
  maxPages?: number;
315
436
  /** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
316
437
  now?: () => number;
438
+ /**
439
+ * The local document holding this runner's gate (default 'fingerprint-reconcile').
440
+ * Two fingerprint runners on one collection (prices and calculated prices) each need their own.
441
+ */
442
+ stateId?: string;
317
443
  }
318
444
  interface FingerprintReconcileResult {
319
445
  pages: number;
320
446
  compared: number;
321
447
  queued: number;
448
+ /** Always false now that no page cap applies. */
322
449
  truncated: boolean;
323
450
  /**
324
- * Local products the remote side did not report in a complete pass (they are skipped); 0 on a truncated or failed
451
+ * Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
325
452
  * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
326
453
  * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
327
454
  * correctly reports everything as unreported.
@@ -346,19 +473,17 @@ interface FingerprintReconcileState {
346
473
  declare function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean;
347
474
  /**
348
475
  * Compares a remote fingerprint per product against the local `collection`
349
- * and queues disagreeing products for the collection's pull (ADR-060). Only
350
- * reads `collection`. A throw, abort or truncation queues nothing and skips
351
- * `reSync`; only a complete pass acts. Products the remote side doesn't
352
- * report are left alone -- deletions are the id reconcile's job. No pass
353
- * runs at start by default (`startDelayMs: null`); the app may still call
354
- * `reconcile()` on demand. A call during a pass queues one follow-up pass
355
- * (later calls share it), so a change made after the pass read is picked up
356
- * straight after, not at the next interval.
476
+ * and queues disagreeing products for the collection's pull (ADR-060), as a
477
+ * wrapper over the catalogue runner (#248). Never deletes: every entry is
478
+ * `refreshOnly`, and a product the remote side doesn't report is only counted
479
+ * as `unreported`. Passes follow the persisted daily gate within a request
480
+ * budget; the app may still call `reconcile()` on demand. A call during a pass
481
+ * queues one follow-up pass (later calls share it).
357
482
  */
358
- declare function startFingerprintReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, now, }: StartFingerprintReconcileOptions<Doc>): {
483
+ declare function startFingerprintReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartFingerprintReconcileOptions<Doc>): {
359
484
  reconcile(): Promise<FingerprintReconcileResult>;
360
485
  stop(): void;
361
486
  state$: Observable<FingerprintReconcileState>;
362
487
  };
363
488
 
364
- export { type CreateDatabaseOptions, type FingerprintReconcileResult, type FingerprintReconcileState, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, REQUIRED_MULTI_INSTANCE_BY_ENGINE, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type TallyDatabase, WEB_STORAGE_ENGINE, connectorCollection, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isStorageWorkerFailure, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, stockLevelsCollection, stockLevelsSchema, withStorageWatchdog };
489
+ export { CATALOGUE_OFFLINE_GAP_MS, type CatalogueReconcileEvent, type CatalogueReconcileState, type CatalogueReconcileSummary, type CreateDatabaseOptions, type FingerprintReconcileResult, type FingerprintReconcileState, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, REQUIRED_MULTI_INSTANCE_BY_ENGINE, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, type StartCatalogueReconcileOptions, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type TallyDatabase, type TallyReplicationState, WEB_STORAGE_ENGINE, connectorCollection, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isStorageWorkerFailure, shouldReconcileAfterGap, startCatalogueReconcile, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, stockLevelsCollection, stockLevelsSchema, withStorageWatchdog };