@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/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,111 @@ 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; only a result with `complete` has a real count. */
325
+ unlisted: number;
326
+ /** 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). */
327
+ complete: boolean;
328
+ durationMs: number;
329
+ }
330
+ /** In memory; the gate itself is persisted. `lastResult` is current when `lastResultAt > (lastErrorAt ?? 0)`. */
331
+ interface CatalogueReconcileState {
332
+ running: boolean;
333
+ lastResult?: CatalogueReconcileSummary;
334
+ lastResultAt?: number;
335
+ /** When the last complete pass finished (persisted). A result without `complete` is not current. */
336
+ lastCompleteAt?: number;
337
+ lastError?: unknown;
338
+ lastErrorAt?: number;
339
+ }
340
+ interface StartCatalogueReconcileOptions<Doc, Cursor = unknown> {
341
+ /** The replicated collection, created with `connectorCollection` (local documents on). Only read. */
342
+ collection: RxCollection<Doc>;
343
+ adapter: CatalogueReconcileAdapter<Doc, Cursor>;
344
+ context: SyncContext;
345
+ /** The app's `() => replication.reSync()`; called once per page that enqueued anything, and once for the tombstones. */
346
+ reSync: () => void;
347
+ /**
348
+ * Requests allowed in any 60 s window (default 30): each page, each `confirmGone` chunk, and the refetch requests
349
+ * each page that enqueued anything causes (the pull's `fetchByIds`: `ceil(n / adapter.refetchBatchSize)`, or 1 when unset).
350
+ */
351
+ requestsPerMinute?: number;
352
+ /** Most candidates per `confirmGone` call (default 100); each call takes one budget slot. */
353
+ confirmChunk?: number;
354
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
355
+ intervalMs?: number;
356
+ /** The first gate check after start (default 120000); then one every `min(1 hour, intervalMs / 2)`, and at least a minute. */
357
+ startDelayMs?: number;
358
+ /** The brake holds deletion candidates above this share of local documents (and above 10), unless `allowMassDelete`. */
359
+ maxDeleteShare?: number;
360
+ allowMassDelete?: boolean;
361
+ log?: (event: CatalogueReconcileEvent) => void;
362
+ now?: () => number;
363
+ /** The local document holding the gate and cursor (default 'catalogue-reconcile'); one per runner on a collection. */
364
+ stateId?: string;
365
+ /** Tests: schedules `fn` after `ms` and returns its cancel (default setTimeout). */
366
+ setTimer?: (fn: () => void, ms: number) => () => void;
367
+ }
368
+ /** True when the last successful pull is older than `offlineGapMs`: the app should then call `reconcile()`. */
369
+ declare function shouldReconcileAfterGap(lastPullAt: number | undefined, now?: number, offlineGapMs?: number): boolean;
370
+ /**
371
+ * The daily catalogue check (#248, ADR-060). Walks the remote listing page by
372
+ * page within a request budget, refetches what differs through the pull, and
373
+ * deletes only after a pass that ran from first page to last in one go, only
374
+ * what `confirmGone` confirms, and only under the mass-delete brake. Never
375
+ * writes the collection; its gate and cursor live in a local document.
376
+ */
377
+ declare function startCatalogueReconcile<Doc, Cursor = unknown>(options: StartCatalogueReconcileOptions<Doc, Cursor>): {
378
+ reconcile(): void;
379
+ state$: Observable<CatalogueReconcileState>;
380
+ stop(): void;
381
+ };
382
+
260
383
  interface StartIdReconcileOptions<Doc> {
261
384
  /** The replicated products collection. Read only. */
262
385
  collection: RxCollection<Doc>;
@@ -264,37 +387,40 @@ interface StartIdReconcileOptions<Doc> {
264
387
  context: SyncContext;
265
388
  /** The app's `() => replication.reSync()`. */
266
389
  reSync: () => void;
267
- /** Delay before the first pass (default 5000); `null` skips it. */
390
+ /** Delay before the first gate check (default 5000); `null` skips it and checks hourly. */
268
391
  startDelayMs?: number | null;
269
- /** Time between passes in ms (default 86400000, 24 hours). */
392
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
270
393
  intervalMs?: number;
271
- /** Pages read before a pass is truncated (default 100). */
394
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
272
395
  maxPages?: number;
273
396
  /**
274
- * The brake applies once would-be tombstones exceed this share of local
397
+ * The brake applies once tombstones exceed this share of local
275
398
  * products (default 0.2), unless `allowMassDelete` is set.
276
399
  */
277
400
  maxDeleteShare?: number;
278
401
  /** Explicit override for a genuine purge; disables the mass-delete brake. */
279
402
  allowMassDelete?: boolean;
403
+ /** The local document holding this runner's gate (default 'id-reconcile'). */
404
+ stateId?: string;
280
405
  }
406
+ /** `truncated` is always false now that no page cap applies. */
281
407
  interface IdReconcileResult {
282
408
  pages: number;
283
409
  queued: number;
284
410
  truncated: boolean;
285
411
  braked: boolean;
412
+ complete: boolean;
286
413
  }
287
414
  /**
288
415
  * 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.
416
+ * and queues disagreeing documents for the collection's pull (ADR-060), as a
417
+ * wrapper over the catalogue runner (#248): a product whose variant ids differ
418
+ * is refetched page by page; a product missing remotely is queued for deletion
419
+ * only after an uninterrupted pass and under the mass-delete brake. Passes
420
+ * follow the persisted daily gate within a request budget. A call during a
421
+ * pass queues one follow-up pass (later calls share it).
296
422
  */
297
- declare function startIdReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, maxDeleteShare, allowMassDelete, }: StartIdReconcileOptions<Doc>): {
423
+ declare function startIdReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartIdReconcileOptions<Doc>): {
298
424
  reconcileIds(): Promise<IdReconcileResult>;
299
425
  stop(): void;
300
426
  };
@@ -306,22 +432,30 @@ interface StartFingerprintReconcileOptions<Doc> {
306
432
  context: SyncContext;
307
433
  /** The app's `() => replication.reSync()`. */
308
434
  reSync: () => void;
309
- /** Delay before the first pass; `null` (default) skips it, since this runner is meant as a nightly backstop. */
435
+ /** Delay before the first gate check; `null` (default) skips it and checks hourly. */
310
436
  startDelayMs?: number | null;
311
- /** Time between passes in ms (default 86400000, 24 hours). */
437
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
312
438
  intervalMs?: number;
313
- /** Pages read before a pass is truncated (default 100). */
439
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
314
440
  maxPages?: number;
315
441
  /** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
316
442
  now?: () => number;
443
+ /**
444
+ * The local document holding this runner's gate (default 'fingerprint-reconcile').
445
+ * Two fingerprint runners on one collection (prices and calculated prices) each need their own.
446
+ */
447
+ stateId?: string;
317
448
  }
318
449
  interface FingerprintReconcileResult {
319
450
  pages: number;
320
451
  compared: number;
321
452
  queued: number;
453
+ /** Always false now that no page cap applies. */
322
454
  truncated: boolean;
455
+ /** True when `unreported` is a real count: a complete pass that read at least one page. */
456
+ complete: boolean;
323
457
  /**
324
- * Local products the remote side did not report in a complete pass (they are skipped); 0 on a truncated or failed
458
+ * Local products the remote side did not report (`complete` marks a real count); 0 on a resumed
325
459
  * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
326
460
  * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
327
461
  * correctly reports everything as unreported.
@@ -331,7 +465,7 @@ interface FingerprintReconcileResult {
331
465
  unreported: number;
332
466
  }
333
467
  /**
334
- * The runner's state; entirely in memory. The result is current only when
468
+ * The runner's state; `lastCompleteAt` is persisted. The result is current only when
335
469
  * `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
336
470
  * as stale. See `isFingerprintResultCurrent`.
337
471
  */
@@ -339,6 +473,7 @@ interface FingerprintReconcileState {
339
473
  running: boolean;
340
474
  lastResult?: FingerprintReconcileResult;
341
475
  lastResultAt?: number;
476
+ lastCompleteAt?: number;
342
477
  lastError?: unknown;
343
478
  lastErrorAt?: number;
344
479
  }
@@ -346,19 +481,17 @@ interface FingerprintReconcileState {
346
481
  declare function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean;
347
482
  /**
348
483
  * 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.
484
+ * and queues disagreeing products for the collection's pull (ADR-060), as a
485
+ * wrapper over the catalogue runner (#248). Never deletes: every entry is
486
+ * `refreshOnly`, and a product the remote side doesn't report is only counted
487
+ * as `unreported`. Passes follow the persisted daily gate within a request
488
+ * budget; the app may still call `reconcile()` on demand. A call during a pass
489
+ * queues one follow-up pass (later calls share it).
357
490
  */
358
- declare function startFingerprintReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, now, }: StartFingerprintReconcileOptions<Doc>): {
491
+ declare function startFingerprintReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartFingerprintReconcileOptions<Doc>): {
359
492
  reconcile(): Promise<FingerprintReconcileResult>;
360
493
  stop(): void;
361
494
  state$: Observable<FingerprintReconcileState>;
362
495
  };
363
496
 
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 };
497
+ 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 };