@tallyui/database 3.13.0 → 3.14.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 +60 -3
- package/dist/index.js +80 -11
- package/package.json +2 -2
- package/src/connectivity.ts +101 -0
- package/src/index.ts +5 -0
- package/src/replication.ts +23 -2
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,58 @@ 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
|
+
type: 'failure';
|
|
156
|
+
at: number;
|
|
157
|
+
failure: FailureClass;
|
|
158
|
+
}
|
|
159
|
+
/** The OS says the link is down: offline at once, as v2. */
|
|
160
|
+
| {
|
|
161
|
+
type: 'link-down';
|
|
162
|
+
} | {
|
|
163
|
+
type: 'reset-update-required';
|
|
164
|
+
};
|
|
165
|
+
declare const INITIAL_CONNECTIVITY: ConnectivitySnapshot;
|
|
166
|
+
/**
|
|
167
|
+
* v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
|
|
168
|
+
* failures have run for the confirmation window. The latch holds across successes, first sight wins, and only a
|
|
169
|
+
* reset (v2: a fresh engine) clears it. Returns the same object when nothing changes.
|
|
170
|
+
*/
|
|
171
|
+
declare function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot;
|
|
172
|
+
interface ConnectivityTracker {
|
|
173
|
+
/** The current snapshot on subscribe, then each change. */
|
|
174
|
+
readonly snapshot$: Observable<ConnectivitySnapshot>;
|
|
175
|
+
current(): ConnectivitySnapshot;
|
|
176
|
+
recordSuccess(): void;
|
|
177
|
+
/** Classifies with the tracker's connector, reduces, and returns the class. */
|
|
178
|
+
recordFailure(error: unknown): FailureClass;
|
|
179
|
+
linkDown(): void;
|
|
180
|
+
/** Clears the update-required latch, for a re-probe after the store or the till was updated. */
|
|
181
|
+
resetUpdateRequired(): void;
|
|
182
|
+
}
|
|
183
|
+
/** One tracker per connector session; a new one starts clear, as a fresh v2 engine does. */
|
|
184
|
+
declare function createConnectivityTracker(options?: {
|
|
185
|
+
connector?: Pick<TallyConnector, 'classifyFailure'>;
|
|
186
|
+
now?: () => number;
|
|
187
|
+
}): ConnectivityTracker;
|
|
188
|
+
|
|
137
189
|
interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
138
190
|
collection: RxCollection<RxDocType>;
|
|
139
191
|
adapter: ReplicationAdapter<RxDocType, CheckpointType>;
|
|
@@ -146,6 +198,11 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
|
146
198
|
autoStart?: boolean;
|
|
147
199
|
/** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
|
|
148
200
|
maxRetryTimeMs?: number;
|
|
201
|
+
/**
|
|
202
|
+
* Fed with every pull and push outcome. While its update-required latch is set, the pull pauses and the push throws,
|
|
203
|
+
* neither calling the adapter (v2 sends nothing once latched). `resume()` keeps the latch: reset it first.
|
|
204
|
+
*/
|
|
205
|
+
connectivity?: ConnectivityTracker;
|
|
149
206
|
}
|
|
150
207
|
/** RxDB's replication state plus the pull notice and a way to restart after a till error. */
|
|
151
208
|
type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
|
|
@@ -160,7 +217,7 @@ type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState
|
|
|
160
217
|
* Returns the RxReplicationState which exposes observables for monitoring
|
|
161
218
|
* and methods like cancel(), awaitInSync(), reSync().
|
|
162
219
|
*/
|
|
163
|
-
declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
|
|
220
|
+
declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, connectivity, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
|
|
164
221
|
|
|
165
222
|
/**
|
|
166
223
|
* ADR-061: exactly one live tab per store, and a second tab never opens
|
|
@@ -501,4 +558,4 @@ declare function startFingerprintReconcile<Doc>({ adapter, reSync, startDelayMs,
|
|
|
501
558
|
state$: Observable<FingerprintReconcileState>;
|
|
502
559
|
};
|
|
503
560
|
|
|
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 };
|
|
561
|
+
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
|
@@ -236,7 +236,8 @@ function startReplication({
|
|
|
236
236
|
live = true,
|
|
237
237
|
retryTime = 5e3,
|
|
238
238
|
autoStart = true,
|
|
239
|
-
maxRetryTimeMs = MAX_RETRY_TIME_MS
|
|
239
|
+
maxRetryTimeMs = MAX_RETRY_TIME_MS,
|
|
240
|
+
connectivity
|
|
240
241
|
}) {
|
|
241
242
|
let state;
|
|
242
243
|
const notice$ = new BehaviorSubject2(void 0);
|
|
@@ -248,7 +249,7 @@ function startReplication({
|
|
|
248
249
|
if (state) state.retryTime = ms;
|
|
249
250
|
};
|
|
250
251
|
const pullHandler = async (checkpoint, batchSize) => {
|
|
251
|
-
if (tillStopped) {
|
|
252
|
+
if (tillStopped || connectivity?.current().updateRequired) {
|
|
252
253
|
void state?.pause();
|
|
253
254
|
return { documents: [], checkpoint };
|
|
254
255
|
}
|
|
@@ -259,6 +260,7 @@ function startReplication({
|
|
|
259
260
|
}
|
|
260
261
|
try {
|
|
261
262
|
const result = await adapter.pull.handler(checkpoint, batchSize, context);
|
|
263
|
+
connectivity?.recordSuccess();
|
|
262
264
|
failures = 0;
|
|
263
265
|
storeError = void 0;
|
|
264
266
|
storeRetryAt = 0;
|
|
@@ -266,6 +268,7 @@ function startReplication({
|
|
|
266
268
|
setRetryTime(retryTime);
|
|
267
269
|
return result;
|
|
268
270
|
} catch (error) {
|
|
271
|
+
connectivity?.recordFailure(error);
|
|
269
272
|
const kind = errorKind(error);
|
|
270
273
|
if (kind === "transient") {
|
|
271
274
|
const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
|
|
@@ -297,7 +300,18 @@ function startReplication({
|
|
|
297
300
|
batchSize: adapter.pull.batchSize
|
|
298
301
|
},
|
|
299
302
|
push: adapter.push ? {
|
|
300
|
-
handler: (rows) =>
|
|
303
|
+
handler: async (rows) => {
|
|
304
|
+
if (!connectivity) return adapter.push.handler(rows, context);
|
|
305
|
+
if (connectivity.current().updateRequired) throw new Error("update required: push held");
|
|
306
|
+
try {
|
|
307
|
+
const conflicts = await adapter.push.handler(rows, context);
|
|
308
|
+
connectivity.recordSuccess();
|
|
309
|
+
return conflicts;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
connectivity.recordFailure(error);
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
},
|
|
301
315
|
batchSize: adapter.push.batchSize
|
|
302
316
|
} : void 0,
|
|
303
317
|
live,
|
|
@@ -321,8 +335,58 @@ function startReplication({
|
|
|
321
335
|
return Object.assign(replication, { notice$: notice$.asObservable(), resume });
|
|
322
336
|
}
|
|
323
337
|
|
|
324
|
-
// src/
|
|
338
|
+
// src/connectivity.ts
|
|
325
339
|
import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
|
|
340
|
+
import { classifyFailure } from "@tallyui/core";
|
|
341
|
+
var FAILURE_CONFIRMATION_MS = 3e4;
|
|
342
|
+
var FAILURE_CONFIRMATION_TOLERANCE_MS = 1e3;
|
|
343
|
+
var INITIAL_CONNECTIVITY = { state: "online", updateRequired: null, failingSince: null };
|
|
344
|
+
var answered = (snapshot) => snapshot.state === "online" && snapshot.failingSince === null ? snapshot : { ...snapshot, state: "online", failingSince: null };
|
|
345
|
+
function reduceConnectivity(snapshot, event) {
|
|
346
|
+
switch (event.type) {
|
|
347
|
+
case "success":
|
|
348
|
+
return answered(snapshot);
|
|
349
|
+
case "link-down":
|
|
350
|
+
return snapshot.state === "offline" && snapshot.failingSince === null ? snapshot : { ...snapshot, state: "offline", failingSince: null };
|
|
351
|
+
case "reset-update-required":
|
|
352
|
+
return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
|
|
353
|
+
case "failure": {
|
|
354
|
+
const { failure, at } = event;
|
|
355
|
+
if (failure === null) return snapshot;
|
|
356
|
+
if (typeof failure === "object") {
|
|
357
|
+
const next = answered(snapshot);
|
|
358
|
+
return next.updateRequired ? next : { ...next, updateRequired: failure.updateRequired };
|
|
359
|
+
}
|
|
360
|
+
const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
|
|
361
|
+
const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
|
|
362
|
+
const state = confirmed ? failure : snapshot.state;
|
|
363
|
+
return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function createConnectivityTracker(options = {}) {
|
|
368
|
+
const { connector, now = Date.now } = options;
|
|
369
|
+
const subject = new BehaviorSubject3(INITIAL_CONNECTIVITY);
|
|
370
|
+
const dispatch = (event) => {
|
|
371
|
+
const next = reduceConnectivity(subject.getValue(), event);
|
|
372
|
+
if (next !== subject.getValue()) subject.next(next);
|
|
373
|
+
};
|
|
374
|
+
return {
|
|
375
|
+
snapshot$: subject.asObservable(),
|
|
376
|
+
current: () => subject.getValue(),
|
|
377
|
+
recordSuccess: () => dispatch({ type: "success", at: now() }),
|
|
378
|
+
recordFailure: (error) => {
|
|
379
|
+
const failure = classifyFailure(connector, error);
|
|
380
|
+
dispatch({ type: "failure", at: now(), failure });
|
|
381
|
+
return failure;
|
|
382
|
+
},
|
|
383
|
+
linkDown: () => dispatch({ type: "link-down" }),
|
|
384
|
+
resetUpdateRequired: () => dispatch({ type: "reset-update-required" })
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// src/live-tab.ts
|
|
389
|
+
import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
|
|
326
390
|
function isHandoverMessage(data) {
|
|
327
391
|
const msg = data;
|
|
328
392
|
return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
|
|
@@ -340,7 +404,7 @@ function startLiveTab(options) {
|
|
|
340
404
|
events = globalThis,
|
|
341
405
|
now = Date.now
|
|
342
406
|
} = options;
|
|
343
|
-
const state = new
|
|
407
|
+
const state = new BehaviorSubject4("acquiring");
|
|
344
408
|
if (!locks) {
|
|
345
409
|
state.next("live");
|
|
346
410
|
return { state$: state.asObservable(), takeOver: () => Promise.resolve("live"), stop: () => state.complete() };
|
|
@@ -491,7 +555,7 @@ function startLiveTab(options) {
|
|
|
491
555
|
}
|
|
492
556
|
|
|
493
557
|
// src/reconcile.ts
|
|
494
|
-
import { BehaviorSubject as
|
|
558
|
+
import { BehaviorSubject as BehaviorSubject5 } from "rxjs";
|
|
495
559
|
import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core";
|
|
496
560
|
|
|
497
561
|
// src/chunks.ts
|
|
@@ -550,7 +614,7 @@ function startStockReconcile({
|
|
|
550
614
|
const checkAborted = () => {
|
|
551
615
|
if (signal.aborted) throw signal.reason ?? new Error("Stock reconcile stopped");
|
|
552
616
|
};
|
|
553
|
-
const state = new
|
|
617
|
+
const state = new BehaviorSubject5({ running: false, truncated: false });
|
|
554
618
|
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
555
619
|
const lastPass = collection.getLocal(STOCK_LEVELS_LAST_PASS2).catch((error) => {
|
|
556
620
|
if (error?.code !== "LD8") return null;
|
|
@@ -631,7 +695,7 @@ function startStockReconcile({
|
|
|
631
695
|
}
|
|
632
696
|
|
|
633
697
|
// src/catalogue-reconcile.ts
|
|
634
|
-
import { BehaviorSubject as
|
|
698
|
+
import { BehaviorSubject as BehaviorSubject6 } from "rxjs";
|
|
635
699
|
import { errorKind as errorKind2 } from "@tallyui/core";
|
|
636
700
|
import { readFresh as readFresh2 } from "@tallyui/core/rxdb";
|
|
637
701
|
var MASS_DELETE_MINIMUM = 10;
|
|
@@ -682,7 +746,7 @@ function startCatalogueRunner({
|
|
|
682
746
|
const primary = collection.schema.primaryPath;
|
|
683
747
|
const keyOf = (doc) => doc[primary];
|
|
684
748
|
const listed = (keys) => ({ count: keys.length, keys: keys.slice(0, LOG_KEYS) });
|
|
685
|
-
const state = new
|
|
749
|
+
const state = new BehaviorSubject6({ running: false });
|
|
686
750
|
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
687
751
|
const ids = claimed.get(collection) ?? /* @__PURE__ */ new Set();
|
|
688
752
|
claimed.set(collection, ids);
|
|
@@ -939,7 +1003,7 @@ function startCatalogueRunner({
|
|
|
939
1003
|
}
|
|
940
1004
|
|
|
941
1005
|
// src/fingerprint-reconcile.ts
|
|
942
|
-
import { BehaviorSubject as
|
|
1006
|
+
import { BehaviorSubject as BehaviorSubject7 } from "rxjs";
|
|
943
1007
|
function isFingerprintResultCurrent(state) {
|
|
944
1008
|
return state.lastResultAt !== void 0 && state.lastResultAt > (state.lastErrorAt ?? 0);
|
|
945
1009
|
}
|
|
@@ -1004,7 +1068,7 @@ function startFingerprintReconcile({
|
|
|
1004
1068
|
}
|
|
1005
1069
|
});
|
|
1006
1070
|
const toResult = ({ pages, compared, unlisted, complete }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0, complete: complete && pages > 0 });
|
|
1007
|
-
const state = new
|
|
1071
|
+
const state = new BehaviorSubject7({ running: false });
|
|
1008
1072
|
let summary;
|
|
1009
1073
|
let result;
|
|
1010
1074
|
let lastCompleteAt;
|
|
@@ -1082,6 +1146,9 @@ function startIdReconcile({
|
|
|
1082
1146
|
}
|
|
1083
1147
|
export {
|
|
1084
1148
|
CATALOGUE_OFFLINE_GAP_MS,
|
|
1149
|
+
FAILURE_CONFIRMATION_MS,
|
|
1150
|
+
FAILURE_CONFIRMATION_TOLERANCE_MS,
|
|
1151
|
+
INITIAL_CONNECTIVITY,
|
|
1085
1152
|
REQUIRED_MULTI_INSTANCE_BY_ENGINE,
|
|
1086
1153
|
STOCK_LEVELS_COLLECTION,
|
|
1087
1154
|
STOCK_LEVELS_LAST_PASS,
|
|
@@ -1089,11 +1156,13 @@ export {
|
|
|
1089
1156
|
STORAGE_WRITE_STALL_MS,
|
|
1090
1157
|
WEB_STORAGE_ENGINE,
|
|
1091
1158
|
connectorCollection,
|
|
1159
|
+
createConnectivityTracker,
|
|
1092
1160
|
createTallyDatabase,
|
|
1093
1161
|
getStorage,
|
|
1094
1162
|
getStorageHealth,
|
|
1095
1163
|
isFingerprintResultCurrent,
|
|
1096
1164
|
isStorageWorkerFailure,
|
|
1165
|
+
reduceConnectivity,
|
|
1097
1166
|
shouldReconcileAfterGap,
|
|
1098
1167
|
startCatalogueReconcile,
|
|
1099
1168
|
startFingerprintReconcile,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/database",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.14.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.
|
|
33
|
+
"@tallyui/core": "^3.14.0"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
36
|
"build": "tsup",
|
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
| { type: 'failure'; at: number; failure: FailureClass }
|
|
28
|
+
/** The OS says the link is down: offline at once, as v2. */
|
|
29
|
+
| { type: 'link-down' }
|
|
30
|
+
| { type: 'reset-update-required' };
|
|
31
|
+
|
|
32
|
+
export const INITIAL_CONNECTIVITY: ConnectivitySnapshot = { state: 'online', updateRequired: null, failingSince: null };
|
|
33
|
+
|
|
34
|
+
const answered = (snapshot: ConnectivitySnapshot): ConnectivitySnapshot =>
|
|
35
|
+
snapshot.state === 'online' && snapshot.failingSince === null ? snapshot : { ...snapshot, state: 'online', failingSince: null };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
|
|
39
|
+
* failures have run for the confirmation window. The latch holds across successes, first sight wins, and only a
|
|
40
|
+
* reset (v2: a fresh engine) clears it. Returns the same object when nothing changes.
|
|
41
|
+
*/
|
|
42
|
+
export function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot {
|
|
43
|
+
switch (event.type) {
|
|
44
|
+
case 'success':
|
|
45
|
+
return answered(snapshot);
|
|
46
|
+
case 'link-down':
|
|
47
|
+
return snapshot.state === 'offline' && snapshot.failingSince === null ? snapshot : { ...snapshot, state: 'offline', failingSince: null };
|
|
48
|
+
case 'reset-update-required':
|
|
49
|
+
return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
|
|
50
|
+
case 'failure': {
|
|
51
|
+
const { failure, at } = event;
|
|
52
|
+
if (failure === null) return snapshot;
|
|
53
|
+
if (typeof failure === 'object') {
|
|
54
|
+
// The store answered with its refusal, so it is reachable.
|
|
55
|
+
const next = answered(snapshot);
|
|
56
|
+
return next.updateRequired ? next : { ...next, updateRequired: failure.updateRequired };
|
|
57
|
+
}
|
|
58
|
+
// A clock that went back would hold the verdict off for ever: re-anchor instead.
|
|
59
|
+
const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
|
|
60
|
+
const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
|
|
61
|
+
const state = confirmed ? failure : snapshot.state;
|
|
62
|
+
return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ConnectivityTracker {
|
|
68
|
+
/** The current snapshot on subscribe, then each change. */
|
|
69
|
+
readonly snapshot$: Observable<ConnectivitySnapshot>;
|
|
70
|
+
current(): ConnectivitySnapshot;
|
|
71
|
+
recordSuccess(): void;
|
|
72
|
+
/** Classifies with the tracker's connector, reduces, and returns the class. */
|
|
73
|
+
recordFailure(error: unknown): FailureClass;
|
|
74
|
+
linkDown(): void;
|
|
75
|
+
/** Clears the update-required latch, for a re-probe after the store or the till was updated. */
|
|
76
|
+
resetUpdateRequired(): void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One tracker per connector session; a new one starts clear, as a fresh v2 engine does. */
|
|
80
|
+
export function createConnectivityTracker(
|
|
81
|
+
options: { connector?: Pick<TallyConnector, 'classifyFailure'>; now?: () => number } = {},
|
|
82
|
+
): ConnectivityTracker {
|
|
83
|
+
const { connector, now = Date.now } = options;
|
|
84
|
+
const subject = new BehaviorSubject<ConnectivitySnapshot>(INITIAL_CONNECTIVITY);
|
|
85
|
+
const dispatch = (event: ConnectivityEvent) => {
|
|
86
|
+
const next = reduceConnectivity(subject.getValue(), event);
|
|
87
|
+
if (next !== subject.getValue()) subject.next(next);
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
snapshot$: subject.asObservable(),
|
|
91
|
+
current: () => subject.getValue(),
|
|
92
|
+
recordSuccess: () => dispatch({ type: 'success', at: now() }),
|
|
93
|
+
recordFailure: (error) => {
|
|
94
|
+
const failure = classifyFailure(connector, error);
|
|
95
|
+
dispatch({ type: 'failure', at: now(), failure });
|
|
96
|
+
return failure;
|
|
97
|
+
},
|
|
98
|
+
linkDown: () => dispatch({ type: 'link-down' }),
|
|
99
|
+
resetUpdateRequired: () => dispatch({ type: 'reset-update-required' }),
|
|
100
|
+
};
|
|
101
|
+
}
|
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
|
|
package/src/replication.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { BehaviorSubject, type Observable } from 'rxjs';
|
|
|
4
4
|
|
|
5
5
|
import { errorKind, type ReplicationAdapter, type SyncContext, type SyncNotice } from '@tallyui/core';
|
|
6
6
|
|
|
7
|
+
import type { ConnectivityTracker } from './connectivity';
|
|
8
|
+
|
|
7
9
|
/** The longest backoff between pull retries, and a store error's wait: 5 minutes. */
|
|
8
10
|
export const MAX_RETRY_TIME_MS = 5 * 60 * 1000;
|
|
9
11
|
|
|
@@ -58,6 +60,11 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
|
58
60
|
autoStart?: boolean;
|
|
59
61
|
/** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
|
|
60
62
|
maxRetryTimeMs?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Fed with every pull and push outcome. While its update-required latch is set, the pull pauses and the push throws,
|
|
65
|
+
* neither calling the adapter (v2 sends nothing once latched). `resume()` keeps the latch: reset it first.
|
|
66
|
+
*/
|
|
67
|
+
connectivity?: ConnectivityTracker;
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
/** RxDB's replication state plus the pull notice and a way to restart after a till error. */
|
|
@@ -98,6 +105,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
98
105
|
retryTime = 5000,
|
|
99
106
|
autoStart = true,
|
|
100
107
|
maxRetryTimeMs = MAX_RETRY_TIME_MS,
|
|
108
|
+
connectivity,
|
|
101
109
|
}: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
|
|
102
110
|
// Pull errors fall in three classes by who can fix them (errorKind):
|
|
103
111
|
// - till (sign in again): one notice, pause, and an empty page (RxDB stores no
|
|
@@ -119,7 +127,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
119
127
|
if (state) state.retryTime = ms;
|
|
120
128
|
};
|
|
121
129
|
const pullHandler = async (checkpoint: CheckpointType | undefined, batchSize: number) => {
|
|
122
|
-
if (tillStopped) {
|
|
130
|
+
if (tillStopped || connectivity?.current().updateRequired) {
|
|
123
131
|
void state?.pause();
|
|
124
132
|
return { documents: [], checkpoint };
|
|
125
133
|
}
|
|
@@ -130,6 +138,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
130
138
|
}
|
|
131
139
|
try {
|
|
132
140
|
const result = await adapter.pull.handler(checkpoint, batchSize, context);
|
|
141
|
+
connectivity?.recordSuccess();
|
|
133
142
|
failures = 0;
|
|
134
143
|
storeError = undefined;
|
|
135
144
|
storeRetryAt = 0;
|
|
@@ -137,6 +146,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
137
146
|
setRetryTime(retryTime);
|
|
138
147
|
return result;
|
|
139
148
|
} catch (error) {
|
|
149
|
+
connectivity?.recordFailure(error);
|
|
140
150
|
const kind = errorKind(error);
|
|
141
151
|
if (kind === 'transient') {
|
|
142
152
|
const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
|
|
@@ -176,7 +186,18 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
176
186
|
},
|
|
177
187
|
push: adapter.push
|
|
178
188
|
? {
|
|
179
|
-
handler: (rows) =>
|
|
189
|
+
handler: async (rows) => {
|
|
190
|
+
if (!connectivity) return adapter.push!.handler(rows, context);
|
|
191
|
+
if (connectivity.current().updateRequired) throw new Error('update required: push held');
|
|
192
|
+
try {
|
|
193
|
+
const conflicts = await adapter.push!.handler(rows, context);
|
|
194
|
+
connectivity.recordSuccess();
|
|
195
|
+
return conflicts;
|
|
196
|
+
} catch (error) {
|
|
197
|
+
connectivity.recordFailure(error);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
},
|
|
180
201
|
batchSize: adapter.push.batchSize,
|
|
181
202
|
}
|
|
182
203
|
: undefined,
|