@tallyui/database 3.13.0 → 3.15.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, SyncNotice, StockReconcileAdapter, CatalogueReconcileAdapter, IdReconcileAdapter, FingerprintReconcileAdapter } from '@tallyui/core';
3
+ import { TallyConnector, FailureClass, ConnectivityState, UpdateRequired, 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
 
@@ -134,6 +134,62 @@ declare const REQUIRED_MULTI_INSTANCE_BY_ENGINE: {
134
134
  readonly 'sqlite-sahpool': false;
135
135
  };
136
136
 
137
+ /**
138
+ * How long requests must keep failing, with no success, before the verdict leaves `online`: v2's
139
+ * `WEBSITE_UNAVAILABLE_CONFIRMATION_MS` (`packages/hooks/src/website-unavailable-confirmation.ts`). One 502 or one
140
+ * timeout must not tell the cashier the store is down (WCPOS #1669).
141
+ */
142
+ declare const FAILURE_CONFIRMATION_MS = 30000;
143
+ /** v2's `WEBSITE_UNAVAILABLE_CONFIRMATION_TOLERANCE_MS`: a retry one window later may land a little early. */
144
+ declare const FAILURE_CONFIRMATION_TOLERANCE_MS = 1000;
145
+ /** `failingSince` is when the current run of failures started, `null` once the store last answered. */
146
+ interface ConnectivitySnapshot {
147
+ state: ConnectivityState;
148
+ updateRequired: UpdateRequired | null;
149
+ failingSince: number | null;
150
+ }
151
+ type ConnectivityEvent = {
152
+ type: 'success';
153
+ at: number;
154
+ }
155
+ /** `answered`: the store sent a response (a 401, a 404, a 5xx), so the network is up whatever `failure` says. */
156
+ | {
157
+ type: 'failure';
158
+ at: number;
159
+ failure: FailureClass;
160
+ answered?: boolean;
161
+ }
162
+ /** The OS says the link is down: offline at once, as v2. */
163
+ | {
164
+ type: 'link-down';
165
+ } | {
166
+ type: 'reset-update-required';
167
+ };
168
+ declare const INITIAL_CONNECTIVITY: ConnectivitySnapshot;
169
+ /**
170
+ * v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
171
+ * failures have run for the confirmation window. Any answer from the store ends offline. The latch holds across
172
+ * successes, first sight wins, and only a reset (v2: a fresh engine, which re-probes) clears it. Returns the same
173
+ * object when nothing changes.
174
+ */
175
+ declare function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot;
176
+ interface ConnectivityTracker {
177
+ /** The current snapshot on subscribe, then each change. */
178
+ readonly snapshot$: Observable<ConnectivitySnapshot>;
179
+ current(): ConnectivitySnapshot;
180
+ recordSuccess(): void;
181
+ /** Classifies with the tracker's connector, reduces, and returns the class. A numeric `status` on the error is an answer. */
182
+ recordFailure(error: unknown): FailureClass;
183
+ linkDown(): void;
184
+ /** Clears the update-required latch once the store or the till was updated; a replication it feeds re-probes. */
185
+ resetUpdateRequired(): void;
186
+ }
187
+ /** One tracker per connector session; a new one starts clear, as a fresh v2 engine does. */
188
+ declare function createConnectivityTracker(options?: {
189
+ connector?: Pick<TallyConnector, 'classifyFailure'>;
190
+ now?: () => number;
191
+ }): ConnectivityTracker;
192
+
137
193
  interface StartReplicationOptions<RxDocType, CheckpointType = any> {
138
194
  collection: RxCollection<RxDocType>;
139
195
  adapter: ReplicationAdapter<RxDocType, CheckpointType>;
@@ -146,6 +202,12 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
146
202
  autoStart?: boolean;
147
203
  /** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
148
204
  maxRetryTimeMs?: number;
205
+ /**
206
+ * Fed with every pull and push outcome. While its update-required latch is set, the pull returns empty pages and a
207
+ * push waits, neither calling the adapter (v2 sends nothing once latched). `resetUpdateRequired()` re-probes: the
208
+ * pull asks the store again and a held push goes. `resume()` keeps the latch.
209
+ */
210
+ connectivity?: ConnectivityTracker;
149
211
  }
150
212
  /** RxDB's replication state plus the pull notice and a way to restart after a till error. */
151
213
  type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
@@ -160,7 +222,7 @@ type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState
160
222
  * Returns the RxReplicationState which exposes observables for monitoring
161
223
  * and methods like cancel(), awaitInSync(), reSync().
162
224
  */
163
- declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
225
+ declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, connectivity, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
164
226
 
165
227
  /**
166
228
  * ADR-061: exactly one live tab per store, and a second tab never opens
@@ -501,4 +563,4 @@ declare function startFingerprintReconcile<Doc>({ adapter, reSync, startDelayMs,
501
563
  state$: Observable<FingerprintReconcileState>;
502
564
  };
503
565
 
504
- 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 };
566
+ export { CATALOGUE_OFFLINE_GAP_MS, type CatalogueReconcileEvent, type CatalogueReconcileState, type CatalogueReconcileSummary, type ConnectivityEvent, type ConnectivitySnapshot, type ConnectivityTracker, type CreateDatabaseOptions, FAILURE_CONFIRMATION_MS, FAILURE_CONFIRMATION_TOLERANCE_MS, type FingerprintReconcileResult, type FingerprintReconcileState, INITIAL_CONNECTIVITY, 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, createConnectivityTracker, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isStorageWorkerFailure, reduceConnectivity, shouldReconcileAfterGap, startCatalogueReconcile, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, stockLevelsCollection, stockLevelsSchema, withStorageWatchdog };
package/dist/index.js CHANGED
@@ -52,8 +52,8 @@ function withStorageWatchdog(storage, options = {}) {
52
52
  readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
53
53
  now = Date.now,
54
54
  setTimer = (fn, ms) => {
55
- const timer = setTimeout(fn, ms);
56
- return () => clearTimeout(timer);
55
+ const timer2 = setTimeout(fn, ms);
56
+ return () => clearTimeout(timer2);
57
57
  }
58
58
  } = options;
59
59
  const health$ = new BehaviorSubject({ status: "ok", stalledWrites: 0 });
@@ -189,7 +189,16 @@ function getStorage() {
189
189
 
190
190
  // src/replication.ts
191
191
  import { replicateRxCollection } from "rxdb/plugins/replication";
192
- import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
192
+ import { errorToPlainJson, newRxError, toArray } from "rxdb";
193
+ import {
194
+ BehaviorSubject as BehaviorSubject2,
195
+ EMPTY,
196
+ filter,
197
+ firstValueFrom,
198
+ fromEvent,
199
+ merge,
200
+ timer
201
+ } from "rxjs";
193
202
  import { errorKind } from "@tallyui/core";
194
203
  var MAX_RETRY_TIME_MS = 5 * 60 * 1e3;
195
204
  var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
@@ -221,6 +230,17 @@ function retryAfter(error) {
221
230
  const value = error?.retryAfterMs;
222
231
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
223
232
  }
233
+ async function hold(events, ready, wake$ = EMPTY) {
234
+ const done = () => events.canceled.getValue() || ready();
235
+ if (done()) return;
236
+ await firstValueFrom(merge(events.paused, events.canceled, wake$).pipe(filter(done)), { defaultValue: void 0 });
237
+ }
238
+ function retryWait(events, ms) {
239
+ if (events.canceled.getValue()) return Promise.resolve();
240
+ const offline = typeof window === "object" && typeof window.addEventListener === "function" && !navigator.onLine;
241
+ const wake$ = merge(timer(ms), events.canceled.pipe(filter(Boolean)), offline ? fromEvent(window, "online") : EMPTY);
242
+ return firstValueFrom(wake$, { defaultValue: void 0 });
243
+ }
224
244
  function noticeFor(error, fixedBy) {
225
245
  const fields = error;
226
246
  const notice = { code: fields.code, since: Date.now(), fixedBy };
@@ -236,7 +256,8 @@ function startReplication({
236
256
  live = true,
237
257
  retryTime = 5e3,
238
258
  autoStart = true,
239
- maxRetryTimeMs = MAX_RETRY_TIME_MS
259
+ maxRetryTimeMs = MAX_RETRY_TIME_MS,
260
+ connectivity
240
261
  }) {
241
262
  let state;
242
263
  const notice$ = new BehaviorSubject2(void 0);
@@ -252,6 +273,7 @@ function startReplication({
252
273
  void state?.pause();
253
274
  return { documents: [], checkpoint };
254
275
  }
276
+ if (connectivity?.current().updateRequired) return { documents: [], checkpoint };
255
277
  const wait = storeRetryAt - Date.now();
256
278
  if (wait > TIMER_SLACK_MS) {
257
279
  setRetryTime(wait);
@@ -259,6 +281,7 @@ function startReplication({
259
281
  }
260
282
  try {
261
283
  const result = await adapter.pull.handler(checkpoint, batchSize, context);
284
+ connectivity?.recordSuccess();
262
285
  failures = 0;
263
286
  storeError = void 0;
264
287
  storeRetryAt = 0;
@@ -266,6 +289,7 @@ function startReplication({
266
289
  setRetryTime(retryTime);
267
290
  return result;
268
291
  } catch (error) {
292
+ connectivity?.recordFailure(error);
269
293
  const kind = errorKind(error);
270
294
  if (kind === "transient") {
271
295
  const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
@@ -297,7 +321,31 @@ function startReplication({
297
321
  batchSize: adapter.pull.batchSize
298
322
  },
299
323
  push: adapter.push ? {
300
- handler: (rows) => adapter.push.handler(rows, context),
324
+ // A push is held, never thrown or dropped, while latched or paused: before the send, and after it until
325
+ // the pause ends. RxDB 17.5 drops a paused push's answer (plugins/replication/index.js 269, upstream.js
326
+ // 287), so its rows go twice. And the pages queued behind it (upstream.js 90-100) then find no rows and
327
+ // store the up checkpoint anyway (upstream.js 211), so those rows never go. A failed push is retried
328
+ // here, never thrown: RxDB's own retry wait (index.js 266) ends unsent if paused by then, with the same
329
+ // loss. Only a cancel ends a hold, with nothing sent.
330
+ handler: async (rows) => {
331
+ const events = state.internalReplicationState.events;
332
+ const isLatched = () => Boolean(connectivity?.current().updateRequired);
333
+ for (; ; ) {
334
+ await hold(events, () => !isLatched() && !events.paused.getValue(), connectivity?.snapshot$);
335
+ if (events.canceled.getValue()) return [];
336
+ const sent = await adapter.push.handler(rows, context).then((conflicts) => ({ conflicts }), (error) => {
337
+ connectivity?.recordFailure(error);
338
+ const errors = toArray(error).map(errorToPlainJson);
339
+ events.error.next(newRxError("RC_PUSH", { pushRows: rows, errors, direction: "push" }));
340
+ });
341
+ if (sent) {
342
+ connectivity?.recordSuccess();
343
+ await hold(events, () => !events.paused.getValue());
344
+ return sent.conflicts;
345
+ }
346
+ await retryWait(events, state.retryTime ?? retryTime);
347
+ }
348
+ },
301
349
  batchSize: adapter.push.batchSize
302
350
  } : void 0,
303
351
  live,
@@ -306,8 +354,15 @@ function startReplication({
306
354
  });
307
355
  state = replication;
308
356
  const release = watchShared(adapter, collection);
357
+ let latched = Boolean(connectivity?.current().updateRequired);
358
+ const probe = connectivity?.snapshot$.subscribe(({ updateRequired }) => {
359
+ if (latched && !updateRequired && !tillStopped && !replication.isPaused()) replication.reSync();
360
+ latched = updateRequired !== null;
361
+ });
309
362
  replication.canceled$.subscribe((canceled) => {
310
- if (canceled) release();
363
+ if (!canceled) return;
364
+ release();
365
+ probe?.unsubscribe();
311
366
  });
312
367
  const resume = async () => {
313
368
  notice$.next(void 0);
@@ -321,8 +376,60 @@ function startReplication({
321
376
  return Object.assign(replication, { notice$: notice$.asObservable(), resume });
322
377
  }
323
378
 
324
- // src/live-tab.ts
379
+ // src/connectivity.ts
325
380
  import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
381
+ import { classifyFailure } from "@tallyui/core";
382
+ var FAILURE_CONFIRMATION_MS = 3e4;
383
+ var FAILURE_CONFIRMATION_TOLERANCE_MS = 1e3;
384
+ var INITIAL_CONNECTIVITY = { state: "online", updateRequired: null, failingSince: null };
385
+ var answered = (snapshot) => snapshot.state === "online" && snapshot.failingSince === null ? snapshot : { ...snapshot, state: "online", failingSince: null };
386
+ function reduceConnectivity(snapshot, event) {
387
+ switch (event.type) {
388
+ case "success":
389
+ return answered(snapshot);
390
+ case "link-down":
391
+ return snapshot.state === "offline" && snapshot.failingSince === null ? snapshot : { ...snapshot, state: "offline", failingSince: null };
392
+ case "reset-update-required":
393
+ return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
394
+ case "failure": {
395
+ const { failure, at } = event;
396
+ if (failure === null) return event.answered ? answered(snapshot) : snapshot;
397
+ if (typeof failure === "object") {
398
+ const next = answered(snapshot);
399
+ return next.updateRequired ? next : { ...next, updateRequired: failure.updateRequired };
400
+ }
401
+ const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
402
+ const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
403
+ const verdict = confirmed ? failure : snapshot.state;
404
+ const state = event.answered && verdict === "offline" ? "degraded" : verdict;
405
+ return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
406
+ }
407
+ }
408
+ }
409
+ function createConnectivityTracker(options = {}) {
410
+ const { connector, now = Date.now } = options;
411
+ const subject = new BehaviorSubject3(INITIAL_CONNECTIVITY);
412
+ const dispatch = (event) => {
413
+ const next = reduceConnectivity(subject.getValue(), event);
414
+ if (next !== subject.getValue()) subject.next(next);
415
+ };
416
+ return {
417
+ snapshot$: subject.asObservable(),
418
+ current: () => subject.getValue(),
419
+ recordSuccess: () => dispatch({ type: "success", at: now() }),
420
+ recordFailure: (error) => {
421
+ const failure = classifyFailure(connector, error);
422
+ const answered2 = typeof error?.status === "number";
423
+ dispatch({ type: "failure", at: now(), failure, answered: answered2 });
424
+ return failure;
425
+ },
426
+ linkDown: () => dispatch({ type: "link-down" }),
427
+ resetUpdateRequired: () => dispatch({ type: "reset-update-required" })
428
+ };
429
+ }
430
+
431
+ // src/live-tab.ts
432
+ import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
326
433
  function isHandoverMessage(data) {
327
434
  const msg = data;
328
435
  return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
@@ -340,7 +447,7 @@ function startLiveTab(options) {
340
447
  events = globalThis,
341
448
  now = Date.now
342
449
  } = options;
343
- const state = new BehaviorSubject3("acquiring");
450
+ const state = new BehaviorSubject4("acquiring");
344
451
  if (!locks) {
345
452
  state.next("live");
346
453
  return { state$: state.asObservable(), takeOver: () => Promise.resolve("live"), stop: () => state.complete() };
@@ -371,12 +478,12 @@ function startLiveTab(options) {
371
478
  });
372
479
  });
373
480
  const waitForAck = (id) => new Promise((resolve) => {
374
- const timer = setTimeout(() => {
481
+ const timer2 = setTimeout(() => {
375
482
  ackWaiters.delete(id);
376
483
  resolve(false);
377
484
  }, ackTimeoutMs);
378
485
  ackWaiters.set(id, () => {
379
- clearTimeout(timer);
486
+ clearTimeout(timer2);
380
487
  ackWaiters.delete(id);
381
488
  resolve(true);
382
489
  });
@@ -491,7 +598,7 @@ function startLiveTab(options) {
491
598
  }
492
599
 
493
600
  // src/reconcile.ts
494
- import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
601
+ import { BehaviorSubject as BehaviorSubject5 } from "rxjs";
495
602
  import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core";
496
603
 
497
604
  // src/chunks.ts
@@ -550,7 +657,7 @@ function startStockReconcile({
550
657
  const checkAborted = () => {
551
658
  if (signal.aborted) throw signal.reason ?? new Error("Stock reconcile stopped");
552
659
  };
553
- const state = new BehaviorSubject4({ running: false, truncated: false });
660
+ const state = new BehaviorSubject5({ running: false, truncated: false });
554
661
  const update = (patch) => state.next({ ...state.value, ...patch });
555
662
  const lastPass = collection.getLocal(STOCK_LEVELS_LAST_PASS2).catch((error) => {
556
663
  if (error?.code !== "LD8") return null;
@@ -616,11 +723,11 @@ function startStockReconcile({
616
723
  }
617
724
  };
618
725
  const reconcileStock = createPassQueue(tracked);
619
- const timer = setInterval(() => {
726
+ const timer2 = setInterval(() => {
620
727
  reconcileStock().catch((error) => console.warn("Stock reconcile failed:", error));
621
728
  }, intervalMs);
622
729
  const stop = () => {
623
- clearInterval(timer);
730
+ clearInterval(timer2);
624
731
  context.signal?.removeEventListener("abort", stop);
625
732
  controller.abort();
626
733
  state.complete();
@@ -631,7 +738,7 @@ function startStockReconcile({
631
738
  }
632
739
 
633
740
  // src/catalogue-reconcile.ts
634
- import { BehaviorSubject as BehaviorSubject5 } from "rxjs";
741
+ import { BehaviorSubject as BehaviorSubject6 } from "rxjs";
635
742
  import { errorKind as errorKind2 } from "@tallyui/core";
636
743
  import { readFresh as readFresh2 } from "@tallyui/core/rxdb";
637
744
  var MASS_DELETE_MINIMUM = 10;
@@ -668,8 +775,8 @@ function startCatalogueRunner({
668
775
  now = Date.now,
669
776
  stateId = "catalogue-reconcile",
670
777
  setTimer = (fn, ms) => {
671
- const timer = setTimeout(fn, ms);
672
- return () => clearTimeout(timer);
778
+ const timer2 = setTimeout(fn, ms);
779
+ return () => clearTimeout(timer2);
673
780
  },
674
781
  keepCandidates = false
675
782
  }) {
@@ -682,7 +789,7 @@ function startCatalogueRunner({
682
789
  const primary = collection.schema.primaryPath;
683
790
  const keyOf = (doc) => doc[primary];
684
791
  const listed = (keys) => ({ count: keys.length, keys: keys.slice(0, LOG_KEYS) });
685
- const state = new BehaviorSubject5({ running: false });
792
+ const state = new BehaviorSubject6({ running: false });
686
793
  const update = (patch) => state.next({ ...state.value, ...patch });
687
794
  const ids = claimed.get(collection) ?? /* @__PURE__ */ new Set();
688
795
  claimed.set(collection, ids);
@@ -939,7 +1046,7 @@ function startCatalogueRunner({
939
1046
  }
940
1047
 
941
1048
  // src/fingerprint-reconcile.ts
942
- import { BehaviorSubject as BehaviorSubject6 } from "rxjs";
1049
+ import { BehaviorSubject as BehaviorSubject7 } from "rxjs";
943
1050
  function isFingerprintResultCurrent(state) {
944
1051
  return state.lastResultAt !== void 0 && state.lastResultAt > (state.lastErrorAt ?? 0);
945
1052
  }
@@ -1004,7 +1111,7 @@ function startFingerprintReconcile({
1004
1111
  }
1005
1112
  });
1006
1113
  const toResult = ({ pages, compared, unlisted, complete }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0, complete: complete && pages > 0 });
1007
- const state = new BehaviorSubject6({ running: false });
1114
+ const state = new BehaviorSubject7({ running: false });
1008
1115
  let summary;
1009
1116
  let result;
1010
1117
  let lastCompleteAt;
@@ -1082,6 +1189,9 @@ function startIdReconcile({
1082
1189
  }
1083
1190
  export {
1084
1191
  CATALOGUE_OFFLINE_GAP_MS,
1192
+ FAILURE_CONFIRMATION_MS,
1193
+ FAILURE_CONFIRMATION_TOLERANCE_MS,
1194
+ INITIAL_CONNECTIVITY,
1085
1195
  REQUIRED_MULTI_INSTANCE_BY_ENGINE,
1086
1196
  STOCK_LEVELS_COLLECTION,
1087
1197
  STOCK_LEVELS_LAST_PASS,
@@ -1089,11 +1199,13 @@ export {
1089
1199
  STORAGE_WRITE_STALL_MS,
1090
1200
  WEB_STORAGE_ENGINE,
1091
1201
  connectorCollection,
1202
+ createConnectivityTracker,
1092
1203
  createTallyDatabase,
1093
1204
  getStorage,
1094
1205
  getStorageHealth,
1095
1206
  isFingerprintResultCurrent,
1096
1207
  isStorageWorkerFailure,
1208
+ reduceConnectivity,
1097
1209
  shouldReconcileAfterGap,
1098
1210
  startCatalogueReconcile,
1099
1211
  startFingerprintReconcile,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/database",
3
- "version": "3.13.0",
3
+ "version": "3.15.0",
4
4
  "type": "module",
5
5
  "description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
6
6
  "main": "./dist/index.js",
@@ -30,7 +30,7 @@
30
30
  "rxjs": "7.8.2"
31
31
  },
32
32
  "peerDependencies": {
33
- "@tallyui/core": "^3.13.0"
33
+ "@tallyui/core": "^3.15.0"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "tsup",
@@ -0,0 +1,107 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+
3
+ import { classifyFailure, type ConnectivityState, type FailureClass, type TallyConnector, type UpdateRequired } from '@tallyui/core';
4
+
5
+ // The seam (ADR-084 decision 1): this tracker fills what WCPOS v2's `@wcpos/sync-engine` takes as its
6
+ // `RxdbSyncEnginePorts.connectivity` port and its transport's update-required latch (`engine-transport.ts`), so a
7
+ // later switch to those packages replaces this file, not its callers.
8
+
9
+ /**
10
+ * How long requests must keep failing, with no success, before the verdict leaves `online`: v2's
11
+ * `WEBSITE_UNAVAILABLE_CONFIRMATION_MS` (`packages/hooks/src/website-unavailable-confirmation.ts`). One 502 or one
12
+ * timeout must not tell the cashier the store is down (WCPOS #1669).
13
+ */
14
+ export const FAILURE_CONFIRMATION_MS = 30_000;
15
+ /** v2's `WEBSITE_UNAVAILABLE_CONFIRMATION_TOLERANCE_MS`: a retry one window later may land a little early. */
16
+ export const FAILURE_CONFIRMATION_TOLERANCE_MS = 1_000;
17
+
18
+ /** `failingSince` is when the current run of failures started, `null` once the store last answered. */
19
+ export interface ConnectivitySnapshot {
20
+ state: ConnectivityState;
21
+ updateRequired: UpdateRequired | null;
22
+ failingSince: number | null;
23
+ }
24
+
25
+ export type ConnectivityEvent =
26
+ | { type: 'success'; at: number }
27
+ /** `answered`: the store sent a response (a 401, a 404, a 5xx), so the network is up whatever `failure` says. */
28
+ | { type: 'failure'; at: number; failure: FailureClass; answered?: boolean }
29
+ /** The OS says the link is down: offline at once, as v2. */
30
+ | { type: 'link-down' }
31
+ | { type: 'reset-update-required' };
32
+
33
+ export const INITIAL_CONNECTIVITY: ConnectivitySnapshot = { state: 'online', updateRequired: null, failingSince: null };
34
+
35
+ const answered = (snapshot: ConnectivitySnapshot): ConnectivitySnapshot =>
36
+ snapshot.state === 'online' && snapshot.failingSince === null ? snapshot : { ...snapshot, state: 'online', failingSince: null };
37
+
38
+ /**
39
+ * v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
40
+ * failures have run for the confirmation window. Any answer from the store ends offline. The latch holds across
41
+ * successes, first sight wins, and only a reset (v2: a fresh engine, which re-probes) clears it. Returns the same
42
+ * object when nothing changes.
43
+ */
44
+ export function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot {
45
+ switch (event.type) {
46
+ case 'success':
47
+ return answered(snapshot);
48
+ case 'link-down':
49
+ return snapshot.state === 'offline' && snapshot.failingSince === null ? snapshot : { ...snapshot, state: 'offline', failingSince: null };
50
+ case 'reset-update-required':
51
+ return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
52
+ case 'failure': {
53
+ const { failure, at } = event;
54
+ // An answer that says nothing about connectivity (a 401, a 404) still proves the store is reachable.
55
+ if (failure === null) return event.answered ? answered(snapshot) : snapshot;
56
+ if (typeof failure === 'object') {
57
+ // The store answered with its refusal, so it is reachable.
58
+ const next = answered(snapshot);
59
+ return next.updateRequired ? next : { ...next, updateRequired: failure.updateRequired };
60
+ }
61
+ // A clock that went back would hold the verdict off for ever: re-anchor instead.
62
+ const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
63
+ const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
64
+ const verdict = confirmed ? failure : snapshot.state;
65
+ // An answer is never offline: a 5xx while offline is degraded at once.
66
+ const state = event.answered && verdict === 'offline' ? 'degraded' : verdict;
67
+ return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
68
+ }
69
+ }
70
+ }
71
+
72
+ export interface ConnectivityTracker {
73
+ /** The current snapshot on subscribe, then each change. */
74
+ readonly snapshot$: Observable<ConnectivitySnapshot>;
75
+ current(): ConnectivitySnapshot;
76
+ recordSuccess(): void;
77
+ /** Classifies with the tracker's connector, reduces, and returns the class. A numeric `status` on the error is an answer. */
78
+ recordFailure(error: unknown): FailureClass;
79
+ linkDown(): void;
80
+ /** Clears the update-required latch once the store or the till was updated; a replication it feeds re-probes. */
81
+ resetUpdateRequired(): void;
82
+ }
83
+
84
+ /** One tracker per connector session; a new one starts clear, as a fresh v2 engine does. */
85
+ export function createConnectivityTracker(
86
+ options: { connector?: Pick<TallyConnector, 'classifyFailure'>; now?: () => number } = {},
87
+ ): ConnectivityTracker {
88
+ const { connector, now = Date.now } = options;
89
+ const subject = new BehaviorSubject<ConnectivitySnapshot>(INITIAL_CONNECTIVITY);
90
+ const dispatch = (event: ConnectivityEvent) => {
91
+ const next = reduceConnectivity(subject.getValue(), event);
92
+ if (next !== subject.getValue()) subject.next(next);
93
+ };
94
+ return {
95
+ snapshot$: subject.asObservable(),
96
+ current: () => subject.getValue(),
97
+ recordSuccess: () => dispatch({ type: 'success', at: now() }),
98
+ recordFailure: (error) => {
99
+ const failure = classifyFailure(connector, error);
100
+ const answered = typeof (error as { status?: unknown } | null | undefined)?.status === 'number';
101
+ dispatch({ type: 'failure', at: now(), failure, answered });
102
+ return failure;
103
+ },
104
+ linkDown: () => dispatch({ type: 'link-down' }),
105
+ resetUpdateRequired: () => dispatch({ type: 'reset-update-required' }),
106
+ };
107
+ }
package/src/index.ts CHANGED
@@ -11,6 +11,11 @@ export type { StorageHealth, StorageWatchdogOptions } from './storage-watchdog';
11
11
  export { startReplication } from './replication';
12
12
  export type { StartReplicationOptions, TallyReplicationState } from './replication';
13
13
 
14
+ export {
15
+ createConnectivityTracker, reduceConnectivity, INITIAL_CONNECTIVITY, FAILURE_CONFIRMATION_MS, FAILURE_CONFIRMATION_TOLERANCE_MS,
16
+ } from './connectivity';
17
+ export type { ConnectivityEvent, ConnectivitySnapshot, ConnectivityTracker } from './connectivity';
18
+
14
19
  export { startLiveTab } from './live-tab';
15
20
  export type { LiveTabState, LiveTabOptions, LiveTabHandle } from './live-tab';
16
21
 
@@ -1,9 +1,13 @@
1
1
  import { replicateRxCollection, type RxReplicationState } from 'rxdb/plugins/replication';
2
- import type { RxCollection } from 'rxdb';
3
- import { BehaviorSubject, type Observable } from 'rxjs';
2
+ import { errorToPlainJson, newRxError, toArray, type RxCollection, type RxError } from 'rxdb';
3
+ import {
4
+ BehaviorSubject, EMPTY, filter, firstValueFrom, fromEvent, merge, timer, type Observable, type Subject, type Subscription,
5
+ } from 'rxjs';
4
6
 
5
7
  import { errorKind, type ReplicationAdapter, type SyncContext, type SyncNotice } from '@tallyui/core';
6
8
 
9
+ import type { ConnectivityTracker } from './connectivity';
10
+
7
11
  /** The longest backoff between pull retries, and a store error's wait: 5 minutes. */
8
12
  export const MAX_RETRY_TIME_MS = 5 * 60 * 1000;
9
13
 
@@ -58,6 +62,12 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
58
62
  autoStart?: boolean;
59
63
  /** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
60
64
  maxRetryTimeMs?: number;
65
+ /**
66
+ * Fed with every pull and push outcome. While its update-required latch is set, the pull returns empty pages and a
67
+ * push waits, neither calling the adapter (v2 sends nothing once latched). `resetUpdateRequired()` re-probes: the
68
+ * pull asks the store again and a held push goes. `resume()` keeps the latch.
69
+ */
70
+ connectivity?: ConnectivityTracker;
61
71
  }
62
72
 
63
73
  /** RxDB's replication state plus the pull notice and a way to restart after a till error. */
@@ -74,6 +84,31 @@ export function retryAfter(error: unknown): number {
74
84
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
75
85
  }
76
86
 
87
+ /** The subjects of RxDB's protocol state the push reads, and its error feed (17.5 types/replication-protocol.d.ts 200-219). */
88
+ type ProtocolEvents = { paused: BehaviorSubject<boolean>; canceled: BehaviorSubject<boolean>; error: Subject<RxError> };
89
+
90
+ /**
91
+ * Resolves once `ready()` holds or the replication is cancelled, waking on a pause change, the cancel and `wake$`.
92
+ * The protocol's own `canceled` is set before a cancel awaits anything (17.5 replication-protocol/index.js 216), and
93
+ * completes after, hence the check first and the default value.
94
+ */
95
+ async function hold(events: ProtocolEvents, ready: () => boolean, wake$: Observable<unknown> = EMPTY) {
96
+ const done = () => events.canceled.getValue() || ready();
97
+ if (done()) return;
98
+ await firstValueFrom(merge(events.paused, events.canceled, wake$).pipe(filter(done)), { defaultValue: undefined });
99
+ }
100
+
101
+ /**
102
+ * RxDB's own push retry wait (17.5 plugins/replication/replication-helper.js 51-65): `ms`, cut short by the browser's
103
+ * `online` event while it is offline, and here also by a cancel.
104
+ */
105
+ function retryWait(events: ProtocolEvents, ms: number) {
106
+ if (events.canceled.getValue()) return Promise.resolve();
107
+ const offline = typeof window === 'object' && typeof window.addEventListener === 'function' && !navigator.onLine;
108
+ const wake$ = merge(timer(ms), events.canceled.pipe(filter(Boolean)), offline ? fromEvent(window, 'online') : EMPTY);
109
+ return firstValueFrom(wake$, { defaultValue: undefined });
110
+ }
111
+
77
112
  /** The notice for a till or store error, with the error's string `software`, `minVersion` and `fix`. */
78
113
  function noticeFor(error: unknown, fixedBy: 'till' | 'store'): SyncNotice {
79
114
  const fields = error as Record<string, unknown>;
@@ -98,6 +133,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
98
133
  retryTime = 5000,
99
134
  autoStart = true,
100
135
  maxRetryTimeMs = MAX_RETRY_TIME_MS,
136
+ connectivity,
101
137
  }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
102
138
  // Pull errors fall in three classes by who can fix them (errorKind):
103
139
  // - till (sign in again): one notice, pause, and an empty page (RxDB stores no
@@ -123,6 +159,9 @@ export function startReplication<RxDocType, CheckpointType = any>({
123
159
  void state?.pause();
124
160
  return { documents: [], checkpoint };
125
161
  }
162
+ // Latched: an empty page, no request, and no pause. A pause while a push is in flight makes RxDB drop that push's
163
+ // answer and send its rows again after the restart (17.5 replication-protocol/upstream.js), a doubled write.
164
+ if (connectivity?.current().updateRequired) return { documents: [], checkpoint };
126
165
  const wait = storeRetryAt - Date.now();
127
166
  if (wait > TIMER_SLACK_MS) {
128
167
  setRetryTime(wait);
@@ -130,6 +169,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
130
169
  }
131
170
  try {
132
171
  const result = await adapter.pull.handler(checkpoint, batchSize, context);
172
+ connectivity?.recordSuccess();
133
173
  failures = 0;
134
174
  storeError = undefined;
135
175
  storeRetryAt = 0;
@@ -137,6 +177,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
137
177
  setRetryTime(retryTime);
138
178
  return result;
139
179
  } catch (error) {
180
+ connectivity?.recordFailure(error);
140
181
  const kind = errorKind(error);
141
182
  if (kind === 'transient') {
142
183
  const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
@@ -176,7 +217,32 @@ export function startReplication<RxDocType, CheckpointType = any>({
176
217
  },
177
218
  push: adapter.push
178
219
  ? {
179
- handler: (rows) => adapter.push!.handler(rows, context),
220
+ // A push is held, never thrown or dropped, while latched or paused: before the send, and after it until
221
+ // the pause ends. RxDB 17.5 drops a paused push's answer (plugins/replication/index.js 269, upstream.js
222
+ // 287), so its rows go twice. And the pages queued behind it (upstream.js 90-100) then find no rows and
223
+ // store the up checkpoint anyway (upstream.js 211), so those rows never go. A failed push is retried
224
+ // here, never thrown: RxDB's own retry wait (index.js 266) ends unsent if paused by then, with the same
225
+ // loss. Only a cancel ends a hold, with nothing sent.
226
+ handler: async (rows) => {
227
+ const events = state!.internalReplicationState!.events as ProtocolEvents;
228
+ const isLatched = () => Boolean(connectivity?.current().updateRequired);
229
+ for (;;) {
230
+ await hold(events, () => !isLatched() && !events.paused.getValue(), connectivity?.snapshot$);
231
+ if (events.canceled.getValue()) return [];
232
+ const sent = await adapter.push!.handler(rows, context).then(conflicts => ({ conflicts }), (error: unknown) => {
233
+ connectivity?.recordFailure(error);
234
+ // RxDB's own push error (index.js 260-265), on the feed its error$ forwards (index.js 281).
235
+ const errors = toArray(error as Error).map(errorToPlainJson);
236
+ events.error.next(newRxError('RC_PUSH', { pushRows: rows, errors, direction: 'push' }));
237
+ });
238
+ if (sent) {
239
+ connectivity?.recordSuccess();
240
+ await hold(events, () => !events.paused.getValue());
241
+ return sent.conflicts;
242
+ }
243
+ await retryWait(events, state!.retryTime ?? retryTime);
244
+ }
245
+ },
180
246
  batchSize: adapter.push.batchSize,
181
247
  }
182
248
  : undefined,
@@ -187,7 +253,20 @@ export function startReplication<RxDocType, CheckpointType = any>({
187
253
  state = replication;
188
254
  // Cancelled or, for a one-shot replication, completed: RxDB cancels it either way.
189
255
  const release = watchShared(adapter, collection);
190
- replication.canceled$.subscribe((canceled) => { if (canceled) release(); });
256
+ // The re-probe (v2: a fresh engine re-probes the store, so only it clears the latch; apps/main/lib/create-app-engine.ts):
257
+ // when the latch is reset, pull again from the checkpoint and re-run the push.
258
+ let latched = Boolean(connectivity?.current().updateRequired);
259
+ // Not while paused: an upstream pass run while paused sends nothing yet stores its checkpoint (upstream.js 211,
260
+ // 287), and RxDB's start() re-syncs after a pause anyway (plugins/replication/index.js 110).
261
+ const probe: Subscription | undefined = connectivity?.snapshot$.subscribe(({ updateRequired }) => {
262
+ if (latched && !updateRequired && !tillStopped && !replication.isPaused()) replication.reSync();
263
+ latched = updateRequired !== null;
264
+ });
265
+ replication.canceled$.subscribe((canceled) => {
266
+ if (!canceled) return;
267
+ release();
268
+ probe?.unsubscribe();
269
+ });
191
270
  const resume = async () => {
192
271
  notice$.next(undefined);
193
272
  tillStopped = false;