@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 +164 -31
- package/dist/index.js +555 -148
- package/package.json +3 -3
- package/src/catalogue-reconcile.ts +414 -0
- package/src/chunks.ts +29 -0
- package/src/connector-collection.ts +8 -2
- package/src/create-db.ts +6 -7
- package/src/fingerprint-reconcile.ts +89 -95
- package/src/id-reconcile.ts +50 -101
- package/src/index.ts +5 -1
- package/src/reconcile.ts +19 -6
- package/src/replication.ts +149 -5
- package/src/storage-watchdog.ts +7 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
// src/create-db.ts
|
|
2
2
|
import { createRxDatabase, addRxPlugin as addRxPlugin2 } from "rxdb";
|
|
3
3
|
import { RxDBDevModePlugin } from "rxdb/plugins/dev-mode";
|
|
4
|
-
import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
|
|
4
|
+
import { RxDBLocalDocumentsPlugin as RxDBLocalDocumentsPlugin2 } from "rxdb/plugins/local-documents";
|
|
5
5
|
import { getRxStorageMemory } from "rxdb/plugins/storage-memory";
|
|
6
6
|
import { wrappedValidateAjvStorage } from "rxdb/plugins/validate-ajv";
|
|
7
7
|
|
|
8
8
|
// src/connector-collection.ts
|
|
9
9
|
import { addRxPlugin } from "rxdb";
|
|
10
|
+
import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
|
|
10
11
|
import { RxDBMigrationSchemaPlugin } from "rxdb/plugins/migration-schema";
|
|
11
12
|
function connectorCollection(schema) {
|
|
12
13
|
addRxPlugin(RxDBMigrationSchemaPlugin);
|
|
14
|
+
addRxPlugin(RxDBLocalDocumentsPlugin);
|
|
13
15
|
const migrationStrategies = Object.fromEntries(Array.from({ length: schema.version }, (_, i) => [i + 1, () => null]));
|
|
14
|
-
return { schema, migrationStrategies };
|
|
16
|
+
return { schema, migrationStrategies, localDocuments: true };
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
// src/stock-levels.ts
|
|
@@ -37,10 +39,11 @@ var REQUIRED_MULTI_INSTANCE_BY_ENGINE = { "sqlite-sahpool": false };
|
|
|
37
39
|
|
|
38
40
|
// src/storage-watchdog.ts
|
|
39
41
|
import { BehaviorSubject } from "rxjs";
|
|
42
|
+
import { isRxdbRemoteVersionMismatch } from "@tallyui/core";
|
|
40
43
|
var STORAGE_WRITE_STALL_MS = 1e4;
|
|
41
44
|
var STORAGE_READ_WATCHDOG_MS = 3e4;
|
|
42
45
|
function isStorageWorkerFailure(error) {
|
|
43
|
-
return error instanceof Error && (error.name === "StorageWorkerStartError" || error.message.includes("StorageWorkerStartError"));
|
|
46
|
+
return error instanceof Error && (error.name === "StorageWorkerStartError" || error.message.includes("StorageWorkerStartError") || isRxdbRemoteVersionMismatch(error));
|
|
44
47
|
}
|
|
45
48
|
var READ_METHODS = ["query", "count", "findDocumentsById", "getChangedDocumentsSince"];
|
|
46
49
|
function withStorageWatchdog(storage, options = {}) {
|
|
@@ -129,12 +132,10 @@ function withStorageWatchdog(storage, options = {}) {
|
|
|
129
132
|
|
|
130
133
|
// src/create-db.ts
|
|
131
134
|
var DEV_MODE = process.env.NODE_ENV !== "production";
|
|
132
|
-
addRxPlugin2(
|
|
133
|
-
if (DEV_MODE) {
|
|
134
|
-
addRxPlugin2(RxDBDevModePlugin);
|
|
135
|
-
}
|
|
135
|
+
addRxPlugin2(RxDBLocalDocumentsPlugin2);
|
|
136
136
|
async function createTallyDatabase(options) {
|
|
137
137
|
if (options.multiInstance === true) throw new Error("multiInstance: true is unsupported: TallyUI databases are single-instance (ADR-061).");
|
|
138
|
+
if (DEV_MODE) addRxPlugin2(RxDBDevModePlugin);
|
|
138
139
|
const {
|
|
139
140
|
connector,
|
|
140
141
|
name = `tally_${connector.id}`,
|
|
@@ -188,21 +189,112 @@ function getStorage() {
|
|
|
188
189
|
|
|
189
190
|
// src/replication.ts
|
|
190
191
|
import { replicateRxCollection } from "rxdb/plugins/replication";
|
|
192
|
+
import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
|
|
193
|
+
import { errorKind } from "@tallyui/core";
|
|
194
|
+
var MAX_RETRY_TIME_MS = 5 * 60 * 1e3;
|
|
195
|
+
var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
|
|
196
|
+
var TIMER_SLACK_MS = 10;
|
|
197
|
+
var isDev = () => {
|
|
198
|
+
if (typeof __DEV__ !== "undefined") return Boolean(__DEV__);
|
|
199
|
+
try {
|
|
200
|
+
return process.env.NODE_ENV !== "production";
|
|
201
|
+
} catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
var liveInto = /* @__PURE__ */ new WeakMap();
|
|
206
|
+
var warned = /* @__PURE__ */ new WeakSet();
|
|
207
|
+
function watchShared(adapter, collection) {
|
|
208
|
+
if (!isDev()) return () => {
|
|
209
|
+
};
|
|
210
|
+
const live = liveInto.get(adapter);
|
|
211
|
+
if (!live) liveInto.set(adapter, collection);
|
|
212
|
+
else if (live !== collection && !warned.has(adapter)) {
|
|
213
|
+
warned.add(adapter);
|
|
214
|
+
console.warn("TallyUI: one connector instance is replicating into two databases. Build a connector per store session (createXConnector()); a shared instance can leak queued reconcile work across stores.");
|
|
215
|
+
}
|
|
216
|
+
return () => {
|
|
217
|
+
if (liveInto.get(adapter) === collection) liveInto.delete(adapter);
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function retryAfter(error) {
|
|
221
|
+
const value = error?.retryAfterMs;
|
|
222
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
223
|
+
}
|
|
224
|
+
function noticeFor(error, fixedBy) {
|
|
225
|
+
const fields = error;
|
|
226
|
+
const notice = { code: fields.code, since: Date.now(), fixedBy };
|
|
227
|
+
for (const key of ["software", "minVersion", "fix"]) {
|
|
228
|
+
if (typeof fields[key] === "string") notice[key] = fields[key];
|
|
229
|
+
}
|
|
230
|
+
return notice;
|
|
231
|
+
}
|
|
191
232
|
function startReplication({
|
|
192
233
|
collection,
|
|
193
234
|
adapter,
|
|
194
235
|
context,
|
|
195
236
|
live = true,
|
|
196
237
|
retryTime = 5e3,
|
|
197
|
-
autoStart = true
|
|
238
|
+
autoStart = true,
|
|
239
|
+
maxRetryTimeMs = MAX_RETRY_TIME_MS
|
|
198
240
|
}) {
|
|
241
|
+
let state;
|
|
242
|
+
const notice$ = new BehaviorSubject2(void 0);
|
|
243
|
+
let failures = 0;
|
|
244
|
+
let tillStopped = false;
|
|
245
|
+
let storeError;
|
|
246
|
+
let storeRetryAt = 0;
|
|
247
|
+
const setRetryTime = (ms) => {
|
|
248
|
+
if (state) state.retryTime = ms;
|
|
249
|
+
};
|
|
250
|
+
const pullHandler = async (checkpoint, batchSize) => {
|
|
251
|
+
if (tillStopped) {
|
|
252
|
+
void state?.pause();
|
|
253
|
+
return { documents: [], checkpoint };
|
|
254
|
+
}
|
|
255
|
+
const wait = storeRetryAt - Date.now();
|
|
256
|
+
if (wait > TIMER_SLACK_MS) {
|
|
257
|
+
setRetryTime(wait);
|
|
258
|
+
throw storeError;
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
const result = await adapter.pull.handler(checkpoint, batchSize, context);
|
|
262
|
+
failures = 0;
|
|
263
|
+
storeError = void 0;
|
|
264
|
+
storeRetryAt = 0;
|
|
265
|
+
if (notice$.getValue()?.fixedBy === "store") notice$.next(void 0);
|
|
266
|
+
setRetryTime(retryTime);
|
|
267
|
+
return result;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
const kind = errorKind(error);
|
|
270
|
+
if (kind === "transient") {
|
|
271
|
+
const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
|
|
272
|
+
setRetryTime(Math.min(Math.max(backoff, retryAfter(error)), MAX_RETRY_AFTER_MS));
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
const code = error.code;
|
|
276
|
+
const current = notice$.getValue();
|
|
277
|
+
if (current?.code !== code || current.fixedBy !== kind) notice$.next(noticeFor(error, kind));
|
|
278
|
+
if (kind === "till") {
|
|
279
|
+
tillStopped = true;
|
|
280
|
+
void state?.pause();
|
|
281
|
+
return { documents: [], checkpoint };
|
|
282
|
+
}
|
|
283
|
+
const delay = Math.min(Math.max(maxRetryTimeMs, retryAfter(error)), MAX_RETRY_AFTER_MS);
|
|
284
|
+
storeError = error;
|
|
285
|
+
storeRetryAt = Date.now() + delay;
|
|
286
|
+
setRetryTime(delay);
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
199
290
|
const { version } = collection.schema;
|
|
200
|
-
|
|
291
|
+
const replication = replicateRxCollection({
|
|
201
292
|
collection,
|
|
202
293
|
replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}`,
|
|
203
294
|
pull: {
|
|
204
|
-
handler:
|
|
205
|
-
stream$: adapter.pull.stream
|
|
295
|
+
handler: pullHandler,
|
|
296
|
+
stream$: adapter.pull.stream$,
|
|
297
|
+
batchSize: adapter.pull.batchSize
|
|
206
298
|
},
|
|
207
299
|
push: adapter.push ? {
|
|
208
300
|
handler: (rows) => adapter.push.handler(rows, context),
|
|
@@ -212,10 +304,25 @@ function startReplication({
|
|
|
212
304
|
retryTime,
|
|
213
305
|
autoStart
|
|
214
306
|
});
|
|
307
|
+
state = replication;
|
|
308
|
+
const release = watchShared(adapter, collection);
|
|
309
|
+
replication.canceled$.subscribe((canceled) => {
|
|
310
|
+
if (canceled) release();
|
|
311
|
+
});
|
|
312
|
+
const resume = async () => {
|
|
313
|
+
notice$.next(void 0);
|
|
314
|
+
tillStopped = false;
|
|
315
|
+
storeError = void 0;
|
|
316
|
+
storeRetryAt = 0;
|
|
317
|
+
failures = 0;
|
|
318
|
+
replication.retryTime = retryTime;
|
|
319
|
+
await replication.start();
|
|
320
|
+
};
|
|
321
|
+
return Object.assign(replication, { notice$: notice$.asObservable(), resume });
|
|
215
322
|
}
|
|
216
323
|
|
|
217
324
|
// src/live-tab.ts
|
|
218
|
-
import { BehaviorSubject as
|
|
325
|
+
import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
|
|
219
326
|
function isHandoverMessage(data) {
|
|
220
327
|
const msg = data;
|
|
221
328
|
return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
|
|
@@ -233,7 +340,7 @@ function startLiveTab(options) {
|
|
|
233
340
|
events = globalThis,
|
|
234
341
|
now = Date.now
|
|
235
342
|
} = options;
|
|
236
|
-
const state = new
|
|
343
|
+
const state = new BehaviorSubject3("acquiring");
|
|
237
344
|
if (!locks) {
|
|
238
345
|
state.next("live");
|
|
239
346
|
return { state$: state.asObservable(), takeOver: () => Promise.resolve("live"), stop: () => state.complete() };
|
|
@@ -384,9 +491,32 @@ function startLiveTab(options) {
|
|
|
384
491
|
}
|
|
385
492
|
|
|
386
493
|
// src/reconcile.ts
|
|
387
|
-
import { BehaviorSubject as
|
|
494
|
+
import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
|
|
388
495
|
import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core";
|
|
389
496
|
|
|
497
|
+
// src/chunks.ts
|
|
498
|
+
import { readFresh } from "@tallyui/core/rxdb";
|
|
499
|
+
var BACKGROUND_CHUNK_SIZE = 250;
|
|
500
|
+
function pauseBetweenChunks() {
|
|
501
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
502
|
+
}
|
|
503
|
+
async function* readFreshInChunks(collection, size = BACKGROUND_CHUNK_SIZE) {
|
|
504
|
+
const key = collection.schema.primaryPath;
|
|
505
|
+
let after;
|
|
506
|
+
while (true) {
|
|
507
|
+
if (after !== void 0) await pauseBetweenChunks();
|
|
508
|
+
const chunk = await readFresh(collection, {
|
|
509
|
+
selector: after === void 0 ? {} : { [key]: { $gt: after } },
|
|
510
|
+
sort: [{ [key]: "asc" }],
|
|
511
|
+
limit: size
|
|
512
|
+
});
|
|
513
|
+
if (!chunk.length) return;
|
|
514
|
+
yield chunk;
|
|
515
|
+
if (chunk.length < size) return;
|
|
516
|
+
after = chunk[chunk.length - 1][key];
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
390
520
|
// src/pass-queue.ts
|
|
391
521
|
function createPassQueue(run) {
|
|
392
522
|
let current;
|
|
@@ -420,7 +550,7 @@ function startStockReconcile({
|
|
|
420
550
|
const checkAborted = () => {
|
|
421
551
|
if (signal.aborted) throw signal.reason ?? new Error("Stock reconcile stopped");
|
|
422
552
|
};
|
|
423
|
-
const state = new
|
|
553
|
+
const state = new BehaviorSubject4({ running: false, truncated: false });
|
|
424
554
|
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
425
555
|
const lastPass = collection.getLocal(STOCK_LEVELS_LAST_PASS2).catch((error) => {
|
|
426
556
|
if (error?.code !== "LD8") return null;
|
|
@@ -444,19 +574,29 @@ function startStockReconcile({
|
|
|
444
574
|
pages++;
|
|
445
575
|
for (const [key, value] of page) stock.set(key, value);
|
|
446
576
|
}
|
|
447
|
-
const rows =
|
|
577
|
+
const rows = [];
|
|
578
|
+
for await (const chunk of readFreshInChunks(collection)) {
|
|
579
|
+
checkAborted();
|
|
580
|
+
rows.push(...chunk);
|
|
581
|
+
}
|
|
448
582
|
const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
|
|
449
583
|
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
450
584
|
const upserts = [...stock].filter(([id, value]) => stored.get(id) !== JSON.stringify(value)).map(([id, value]) => ({ id, value, updatedAt }));
|
|
451
585
|
const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
586
|
+
let wroteChunk = false;
|
|
587
|
+
for (let i = 0; i < upserts.length; i += BACKGROUND_CHUNK_SIZE) {
|
|
588
|
+
if (wroteChunk) await pauseBetweenChunks();
|
|
589
|
+
checkAborted();
|
|
590
|
+
const { error } = await collection.bulkUpsert(upserts.slice(i, i + BACKGROUND_CHUNK_SIZE));
|
|
455
591
|
if (error.length) throw error[0];
|
|
592
|
+
wroteChunk = true;
|
|
456
593
|
}
|
|
457
|
-
|
|
458
|
-
|
|
594
|
+
for (let i = 0; i < removals.length; i += BACKGROUND_CHUNK_SIZE) {
|
|
595
|
+
if (wroteChunk) await pauseBetweenChunks();
|
|
596
|
+
checkAborted();
|
|
597
|
+
const { error } = await collection.bulkRemove(removals.slice(i, i + BACKGROUND_CHUNK_SIZE));
|
|
459
598
|
if (error.length) throw error[0];
|
|
599
|
+
wroteChunk = true;
|
|
460
600
|
}
|
|
461
601
|
const completedAt = updatedAt;
|
|
462
602
|
checkAborted();
|
|
@@ -490,179 +630,444 @@ function startStockReconcile({
|
|
|
490
630
|
return { reconcileStock, stop, state$: state.asObservable() };
|
|
491
631
|
}
|
|
492
632
|
|
|
493
|
-
// src/
|
|
494
|
-
import {
|
|
633
|
+
// src/catalogue-reconcile.ts
|
|
634
|
+
import { BehaviorSubject as BehaviorSubject5 } from "rxjs";
|
|
635
|
+
import { errorKind as errorKind2 } from "@tallyui/core";
|
|
636
|
+
import { readFresh as readFresh2 } from "@tallyui/core/rxdb";
|
|
495
637
|
var MASS_DELETE_MINIMUM = 10;
|
|
496
|
-
|
|
638
|
+
var MAX_CHECK_EVERY_MS = 36e5;
|
|
639
|
+
var MIN_CHECK_EVERY_MS = 6e4;
|
|
640
|
+
var FIRST_RETRY_MS = 5 * 6e4;
|
|
641
|
+
var BUDGET_WINDOW_MS = 6e4;
|
|
642
|
+
var LOG_KEYS = 50;
|
|
643
|
+
var CATALOGUE_OFFLINE_GAP_MS = 6 * 36e5;
|
|
644
|
+
function shouldReconcileAfterGap(lastPullAt, now = Date.now(), offlineGapMs = CATALOGUE_OFFLINE_GAP_MS) {
|
|
645
|
+
return lastPullAt !== void 0 && now - lastPullAt > offlineGapMs;
|
|
646
|
+
}
|
|
647
|
+
var claimed = /* @__PURE__ */ new WeakMap();
|
|
648
|
+
function startCatalogueReconcile(options) {
|
|
649
|
+
const { request, state$, stop } = startCatalogueRunner(options);
|
|
650
|
+
return { reconcile: () => {
|
|
651
|
+
request().catch(() => {
|
|
652
|
+
});
|
|
653
|
+
}, state$, stop };
|
|
654
|
+
}
|
|
655
|
+
function startCatalogueRunner({
|
|
497
656
|
collection,
|
|
498
657
|
adapter,
|
|
499
658
|
context,
|
|
500
659
|
reSync,
|
|
501
|
-
|
|
660
|
+
requestsPerMinute = 30,
|
|
661
|
+
confirmChunk = 100,
|
|
502
662
|
intervalMs = 864e5,
|
|
503
|
-
|
|
663
|
+
startDelayMs = 12e4,
|
|
504
664
|
maxDeleteShare = 0.2,
|
|
505
|
-
allowMassDelete = false
|
|
665
|
+
allowMassDelete = false,
|
|
666
|
+
log = () => {
|
|
667
|
+
},
|
|
668
|
+
now = Date.now,
|
|
669
|
+
stateId = "catalogue-reconcile",
|
|
670
|
+
setTimer = (fn, ms) => {
|
|
671
|
+
const timer = setTimeout(fn, ms);
|
|
672
|
+
return () => clearTimeout(timer);
|
|
673
|
+
},
|
|
674
|
+
keepCandidates = false
|
|
506
675
|
}) {
|
|
507
676
|
const controller = new AbortController();
|
|
508
677
|
const { signal } = controller;
|
|
509
678
|
const checkAborted = () => {
|
|
510
|
-
if (signal.aborted) throw signal.reason ?? new Error("
|
|
679
|
+
if (signal.aborted) throw signal.reason ?? new Error("Catalogue reconcile stopped");
|
|
511
680
|
};
|
|
512
|
-
const
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
681
|
+
const ctx = { ...context, signal };
|
|
682
|
+
const primary = collection.schema.primaryPath;
|
|
683
|
+
const keyOf = (doc) => doc[primary];
|
|
684
|
+
const listed = (keys) => ({ count: keys.length, keys: keys.slice(0, LOG_KEYS) });
|
|
685
|
+
const state = new BehaviorSubject5({ running: false });
|
|
686
|
+
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
687
|
+
const ids = claimed.get(collection) ?? /* @__PURE__ */ new Set();
|
|
688
|
+
claimed.set(collection, ids);
|
|
689
|
+
const owner = !ids.has(stateId);
|
|
690
|
+
let memory;
|
|
691
|
+
if (owner) ids.add(stateId);
|
|
692
|
+
else {
|
|
693
|
+
memory = {};
|
|
694
|
+
console.warn(`Catalogue reconcile: "${stateId}" is in use on ${collection.name}; pass a distinct stateId. This gate is kept in memory.`);
|
|
695
|
+
}
|
|
696
|
+
const load = async () => {
|
|
697
|
+
if (memory) return memory;
|
|
698
|
+
try {
|
|
699
|
+
const doc = await collection.getLocal(stateId);
|
|
700
|
+
return doc ? { lastCompletedAt: doc.get("lastCompletedAt"), lastCompleteAt: doc.get("lastCompleteAt"), pass: doc.get("pass") } : {};
|
|
701
|
+
} catch (error) {
|
|
702
|
+
if (typeof collection.getLocal === "function" && error?.code !== "LD8") throw error;
|
|
703
|
+
console.warn(`Catalogue reconcile: ${collection.name} has no local documents (create it with connectorCollection); the gate is kept in memory.`);
|
|
704
|
+
return memory = {};
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
const save = async (value) => {
|
|
708
|
+
if (memory) memory = value;
|
|
709
|
+
else await collection.upsertLocal(stateId, JSON.parse(JSON.stringify(value)));
|
|
710
|
+
};
|
|
711
|
+
load().then(({ lastCompleteAt }) => {
|
|
712
|
+
if (lastCompleteAt !== void 0) update({ lastCompleteAt });
|
|
713
|
+
}).catch(() => {
|
|
714
|
+
});
|
|
715
|
+
const sleep2 = (ms) => new Promise((resolve) => {
|
|
716
|
+
const onAbort = () => {
|
|
717
|
+
cancel();
|
|
718
|
+
resolve();
|
|
719
|
+
};
|
|
720
|
+
const cancel = setTimer(() => {
|
|
721
|
+
signal.removeEventListener("abort", onAbort);
|
|
722
|
+
resolve();
|
|
723
|
+
}, ms);
|
|
724
|
+
signal.addEventListener("abort", onAbort);
|
|
725
|
+
});
|
|
726
|
+
const sent = [];
|
|
727
|
+
const budget = async () => {
|
|
728
|
+
for (; ; ) {
|
|
517
729
|
checkAborted();
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
730
|
+
while (sent.length && sent[0] <= now() - BUDGET_WINDOW_MS) sent.shift();
|
|
731
|
+
if (sent.length < requestsPerMinute) {
|
|
732
|
+
sent.push(now());
|
|
733
|
+
return;
|
|
521
734
|
}
|
|
522
|
-
|
|
523
|
-
for (const row of page) remote.set(row.id, row.variantIds);
|
|
524
|
-
}
|
|
525
|
-
checkAborted();
|
|
526
|
-
const entries = [];
|
|
527
|
-
let localCount = 0;
|
|
528
|
-
let tombstones = 0;
|
|
529
|
-
for (const local of await readFresh(collection, {})) {
|
|
530
|
-
localCount++;
|
|
531
|
-
const id = local[collection.schema.primaryPath];
|
|
532
|
-
const remoteVariantIds = remote.get(id);
|
|
533
|
-
const vanished = remoteVariantIds && adapter.variantIds(local).some((v) => !remoteVariantIds.includes(v));
|
|
534
|
-
if (!remoteVariantIds) tombstones++;
|
|
535
|
-
if (!remoteVariantIds || vanished) entries.push({ id, local });
|
|
536
|
-
}
|
|
537
|
-
checkAborted();
|
|
538
|
-
if (!allowMassDelete && localCount > 0 && (tombstones === localCount || tombstones > MASS_DELETE_MINIMUM && tombstones > maxDeleteShare * localCount)) {
|
|
539
|
-
const share = localCount ? tombstones / localCount : 1;
|
|
540
|
-
console.warn(
|
|
541
|
-
`Id reconcile braked: ${tombstones} of ${localCount} local products (${(share * 100).toFixed(1)}%); nothing was queued. Pass allowMassDelete: true to override.`
|
|
542
|
-
);
|
|
543
|
-
return { pages, queued: 0, truncated: false, braked: true };
|
|
544
|
-
}
|
|
545
|
-
if (entries.length) {
|
|
546
|
-
adapter.enqueue(entries);
|
|
547
|
-
reSync();
|
|
735
|
+
await sleep2(sent[0] + BUDGET_WINDOW_MS - now());
|
|
548
736
|
}
|
|
549
|
-
return { pages, queued: entries.length, truncated: false, braked: false };
|
|
550
|
-
};
|
|
551
|
-
const reconcileIds = createPassQueue(pass);
|
|
552
|
-
const onTimer = () => reconcileIds().catch((error) => console.warn("Id reconcile failed:", error));
|
|
553
|
-
let startTimer;
|
|
554
|
-
let intervalTimer;
|
|
555
|
-
const scheduleInterval = () => {
|
|
556
|
-
intervalTimer = setInterval(onTimer, intervalMs);
|
|
557
|
-
};
|
|
558
|
-
if (startDelayMs === null) scheduleInterval();
|
|
559
|
-
else startTimer = setTimeout(() => {
|
|
560
|
-
onTimer();
|
|
561
|
-
scheduleInterval();
|
|
562
|
-
}, startDelayMs);
|
|
563
|
-
const stop = () => {
|
|
564
|
-
clearTimeout(startTimer);
|
|
565
|
-
clearInterval(intervalTimer);
|
|
566
|
-
context.signal?.removeEventListener("abort", stop);
|
|
567
|
-
controller.abort();
|
|
568
737
|
};
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
return state.lastResultAt !== void 0 && state.lastResultAt > (state.lastErrorAt ?? 0);
|
|
579
|
-
}
|
|
580
|
-
function startFingerprintReconcile({
|
|
581
|
-
collection,
|
|
582
|
-
adapter,
|
|
583
|
-
context,
|
|
584
|
-
reSync,
|
|
585
|
-
startDelayMs = null,
|
|
586
|
-
intervalMs = 864e5,
|
|
587
|
-
maxPages = 100,
|
|
588
|
-
now = Date.now
|
|
589
|
-
}) {
|
|
590
|
-
const controller = new AbortController();
|
|
591
|
-
const { signal } = controller;
|
|
592
|
-
const checkAborted = () => {
|
|
593
|
-
if (signal.aborted) throw signal.reason ?? new Error("Fingerprint reconcile stopped");
|
|
738
|
+
const readByKeys = async (keys) => {
|
|
739
|
+
const found = /* @__PURE__ */ new Map();
|
|
740
|
+
for (let i = 0; i < keys.length; i += BACKGROUND_CHUNK_SIZE) {
|
|
741
|
+
if (i) await pauseBetweenChunks();
|
|
742
|
+
checkAborted();
|
|
743
|
+
const selector = { [primary]: { $in: keys.slice(i, i + BACKGROUND_CHUNK_SIZE) } };
|
|
744
|
+
for (const doc of await readFresh2(collection, { selector })) found.set(keyOf(doc), doc);
|
|
745
|
+
}
|
|
746
|
+
return found;
|
|
594
747
|
};
|
|
595
|
-
const
|
|
596
|
-
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
748
|
+
const braked = (tombstones, localCount) => !allowMassDelete && localCount > 0 && (tombstones === localCount || tombstones > MASS_DELETE_MINIMUM && tombstones > maxDeleteShare * localCount);
|
|
597
749
|
const pass = async () => {
|
|
598
750
|
checkAborted();
|
|
599
|
-
const
|
|
751
|
+
const startedAt = now();
|
|
752
|
+
const saved = await load();
|
|
753
|
+
const resumed = Boolean(saved.pass && saved.pass.cursor !== void 0 && startedAt - saved.pass.startedAt < intervalMs);
|
|
754
|
+
let current = resumed ? { ...saved.pass, uninterrupted: false } : { startedAt, uninterrupted: true };
|
|
755
|
+
await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
|
|
756
|
+
log({ type: "pass-started", resumed });
|
|
757
|
+
const seen = /* @__PURE__ */ new Set();
|
|
758
|
+
let index;
|
|
759
|
+
const buildIndex = async (matchKey) => {
|
|
760
|
+
const built = /* @__PURE__ */ new Map();
|
|
761
|
+
for await (const chunk of readFreshInChunks(collection)) {
|
|
762
|
+
checkAborted();
|
|
763
|
+
for (const doc of chunk) {
|
|
764
|
+
const match = matchKey(doc);
|
|
765
|
+
if (match !== void 0 && !built.has(match)) built.set(match, keyOf(doc));
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return built;
|
|
769
|
+
};
|
|
600
770
|
let pages = 0;
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
771
|
+
let compared = 0;
|
|
772
|
+
let refetched = 0;
|
|
773
|
+
const iterator = adapter.fetchPages(ctx, current.cursor)[Symbol.asyncIterator]();
|
|
774
|
+
try {
|
|
775
|
+
for (; ; ) {
|
|
776
|
+
await budget();
|
|
777
|
+
const next = await iterator.next();
|
|
778
|
+
checkAborted();
|
|
779
|
+
if (next.done) break;
|
|
780
|
+
pages++;
|
|
781
|
+
const { entries, cursor } = next.value;
|
|
782
|
+
const byMatch = adapter.matchKey ? index ??= await buildIndex(adapter.matchKey.bind(adapter)) : void 0;
|
|
783
|
+
const primaries = entries.map((e) => byMatch ? byMatch.get(e.key) : e.key);
|
|
784
|
+
const locals = await readByKeys(primaries.filter((key) => key !== void 0));
|
|
785
|
+
const queue = [];
|
|
786
|
+
entries.forEach(({ key, fingerprint, remote }, i) => {
|
|
787
|
+
seen.add(key);
|
|
788
|
+
const local = primaries[i] === void 0 ? void 0 : locals.get(primaries[i]);
|
|
789
|
+
if (local) compared++;
|
|
790
|
+
if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key: local ? keyOf(local) : key, local, remote });
|
|
791
|
+
});
|
|
792
|
+
checkAborted();
|
|
793
|
+
if (queue.length) {
|
|
794
|
+
const size = adapter.refetchBatchSize;
|
|
795
|
+
const slots = size !== void 0 && size > 0 ? Math.max(1, Math.ceil(queue.length / size)) : 1;
|
|
796
|
+
for (let slot = 0; slot < slots; slot++) await budget();
|
|
797
|
+
adapter.enqueue(queue);
|
|
798
|
+
reSync();
|
|
799
|
+
refetched += queue.length;
|
|
800
|
+
log({ type: "refetched", ...listed(queue.map((e) => e.key)) });
|
|
801
|
+
}
|
|
802
|
+
current = { ...current, cursor };
|
|
803
|
+
await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
|
|
606
804
|
}
|
|
607
|
-
|
|
608
|
-
|
|
805
|
+
} finally {
|
|
806
|
+
iterator.return?.()?.catch(() => {
|
|
807
|
+
});
|
|
609
808
|
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
let
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
809
|
+
let tombstoned = 0;
|
|
810
|
+
let kept = 0;
|
|
811
|
+
let unlisted = 0;
|
|
812
|
+
const keep = (docs, why) => {
|
|
813
|
+
kept += docs.length;
|
|
814
|
+
if (docs.length) log({ type: "kept", ...listed(docs.map(keyOf)), ...why });
|
|
815
|
+
};
|
|
816
|
+
if (!current.uninterrupted) log({ type: "kept", count: 0, keys: [], reason: "resumed-pass" });
|
|
817
|
+
else {
|
|
818
|
+
const candidates = [];
|
|
819
|
+
let localCount = 0;
|
|
820
|
+
for await (const chunk of readFreshInChunks(collection)) {
|
|
821
|
+
checkAborted();
|
|
822
|
+
localCount += chunk.length;
|
|
823
|
+
for (const doc of chunk) {
|
|
824
|
+
const key = adapter.matchKey ? adapter.matchKey(doc) : keyOf(doc);
|
|
825
|
+
if (key === void 0 || !seen.has(key)) candidates.push(doc);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
unlisted = candidates.length;
|
|
829
|
+
let gone = [];
|
|
830
|
+
if (!candidates.length || keepCandidates) {
|
|
831
|
+
} else if (braked(candidates.length, localCount)) {
|
|
832
|
+
const one = candidates.length === 1;
|
|
833
|
+
const message = (one ? "The only product on this till is no longer listed by the online store, so it was kept: removing everything at once needs a check. " : `${candidates.length} products the online store no longer lists were kept on this till: removing that many at once needs a check. `) + `If ${one ? "it was" : "they were"} hidden or removed on purpose, the person who manages this till can allow the removal.`;
|
|
834
|
+
console.warn(`Catalogue reconcile: ${message} (pass allowMassDelete: true to the reconcile runner to apply it)`);
|
|
835
|
+
keep(candidates, { reason: "brake", message });
|
|
836
|
+
} else {
|
|
837
|
+
const confirmed = /* @__PURE__ */ new Set();
|
|
838
|
+
for (let i = 0; i < candidates.length; i += confirmChunk) {
|
|
839
|
+
const chunk = candidates.slice(i, i + confirmChunk);
|
|
840
|
+
await budget();
|
|
841
|
+
for (const key of await adapter.confirmGone(chunk, ctx)) confirmed.add(key);
|
|
842
|
+
checkAborted();
|
|
843
|
+
}
|
|
844
|
+
gone = candidates.filter((doc) => confirmed.has(keyOf(doc)));
|
|
845
|
+
const goneSet = new Set(gone);
|
|
846
|
+
keep(candidates.filter((doc) => !goneSet.has(doc)), { reason: "unconfirmed" });
|
|
847
|
+
}
|
|
848
|
+
if (gone.length) {
|
|
849
|
+
adapter.enqueue(gone.map((local) => ({ key: keyOf(local), local, tombstone: true })));
|
|
850
|
+
reSync();
|
|
851
|
+
tombstoned = gone.length;
|
|
852
|
+
log({ type: "tombstoned", ...listed(gone.map(keyOf)) });
|
|
620
853
|
}
|
|
621
|
-
compared++;
|
|
622
|
-
if (adapter.fingerprint(local) !== remoteFingerprint) entries.push({ id, local, refreshOnly: true });
|
|
623
854
|
}
|
|
624
855
|
checkAborted();
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
856
|
+
const lastCompletedAt = now();
|
|
857
|
+
await save({ lastCompletedAt, lastCompleteAt: current.uninterrupted ? lastCompletedAt : saved.lastCompleteAt });
|
|
858
|
+
const summary = { pages, compared, refetched, tombstoned, kept, unlisted, complete: current.uninterrupted, durationMs: lastCompletedAt - startedAt };
|
|
859
|
+
log({ type: "pass-completed", ...summary });
|
|
860
|
+
return summary;
|
|
861
|
+
};
|
|
862
|
+
let failures = 0;
|
|
863
|
+
let tillStopped = false;
|
|
864
|
+
let cancelRetry;
|
|
865
|
+
const onError = (error) => {
|
|
866
|
+
if (signal.aborted) return log({ type: "stopped", reason: "stopped" });
|
|
867
|
+
const kind = errorKind2(error);
|
|
868
|
+
if (kind === "store") return log({ type: "skipped", reason: "store" });
|
|
869
|
+
const code = error?.code;
|
|
870
|
+
log({ type: "stopped", reason: kind, ...typeof code === "string" && { code } });
|
|
871
|
+
if (kind === "till") {
|
|
872
|
+
tillStopped = true;
|
|
873
|
+
return;
|
|
628
874
|
}
|
|
629
|
-
|
|
875
|
+
const delay = Math.min(Math.max(FIRST_RETRY_MS * 2 ** failures++, retryAfter(error)), MAX_RETRY_AFTER_MS);
|
|
876
|
+
cancelRetry = setTimer(() => {
|
|
877
|
+
cancelRetry = void 0;
|
|
878
|
+
run().catch(() => {
|
|
879
|
+
});
|
|
880
|
+
}, delay);
|
|
630
881
|
};
|
|
631
|
-
const
|
|
882
|
+
const run = createPassQueue(async () => {
|
|
632
883
|
update({ running: true });
|
|
633
884
|
try {
|
|
634
885
|
const result = await pass();
|
|
635
|
-
|
|
886
|
+
failures = 0;
|
|
887
|
+
update({ running: false, lastResult: result, lastResultAt: now(), ...result.complete && { lastCompleteAt: now() } });
|
|
636
888
|
return result;
|
|
637
889
|
} catch (error) {
|
|
638
890
|
update({ running: false, lastError: error, lastErrorAt: now() });
|
|
891
|
+
onError(error);
|
|
639
892
|
throw error;
|
|
640
893
|
}
|
|
894
|
+
});
|
|
895
|
+
const check = async () => {
|
|
896
|
+
if (tillStopped || cancelRetry || state.value.running) return;
|
|
897
|
+
const { lastCompletedAt, pass: pending } = await load();
|
|
898
|
+
if (pending || lastCompletedAt === void 0 || now() - lastCompletedAt >= intervalMs) await run();
|
|
899
|
+
else log({ type: "skipped", reason: "gate" });
|
|
900
|
+
};
|
|
901
|
+
const checkEveryMs = Math.max(MIN_CHECK_EVERY_MS, Math.min(MAX_CHECK_EVERY_MS, intervalMs / 2) || 0);
|
|
902
|
+
let cancelTimer = () => {
|
|
903
|
+
};
|
|
904
|
+
const schedule = (ms) => {
|
|
905
|
+
cancelTimer = setTimer(() => {
|
|
906
|
+
schedule(checkEveryMs);
|
|
907
|
+
check().catch((error) => console.warn("Catalogue reconcile failed:", error));
|
|
908
|
+
}, ms);
|
|
641
909
|
};
|
|
642
|
-
|
|
643
|
-
const onTimer = () => reconcile().catch((error) => console.warn("Fingerprint reconcile failed:", error));
|
|
644
|
-
let startTimer;
|
|
645
|
-
let intervalTimer;
|
|
646
|
-
const scheduleInterval = () => {
|
|
647
|
-
intervalTimer = setInterval(onTimer, intervalMs);
|
|
648
|
-
};
|
|
649
|
-
if (startDelayMs === null) scheduleInterval();
|
|
650
|
-
else startTimer = setTimeout(() => {
|
|
651
|
-
onTimer();
|
|
652
|
-
scheduleInterval();
|
|
653
|
-
}, startDelayMs);
|
|
910
|
+
schedule(startDelayMs ?? checkEveryMs);
|
|
654
911
|
const stop = () => {
|
|
655
|
-
|
|
656
|
-
|
|
912
|
+
cancelTimer();
|
|
913
|
+
cancelRetry?.();
|
|
914
|
+
if (owner) ids.delete(stateId);
|
|
657
915
|
context.signal?.removeEventListener("abort", stop);
|
|
658
916
|
controller.abort();
|
|
659
917
|
state.complete();
|
|
660
918
|
};
|
|
661
919
|
if (context.signal?.aborted) stop();
|
|
662
920
|
else context.signal?.addEventListener("abort", stop);
|
|
921
|
+
const request = () => {
|
|
922
|
+
tillStopped = false;
|
|
923
|
+
cancelRetry?.();
|
|
924
|
+
cancelRetry = void 0;
|
|
925
|
+
return run();
|
|
926
|
+
};
|
|
927
|
+
return { request, state$: state.asObservable(), stop };
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// src/fingerprint-reconcile.ts
|
|
931
|
+
import { BehaviorSubject as BehaviorSubject6 } from "rxjs";
|
|
932
|
+
function isFingerprintResultCurrent(state) {
|
|
933
|
+
return state.lastResultAt !== void 0 && state.lastResultAt > (state.lastErrorAt ?? 0);
|
|
934
|
+
}
|
|
935
|
+
function confirmAll(collection) {
|
|
936
|
+
const primary = collection.schema.primaryPath;
|
|
937
|
+
return async (locals) => locals.map((doc) => doc[primary]);
|
|
938
|
+
}
|
|
939
|
+
async function* skipPages(pages, entries, from = 0) {
|
|
940
|
+
let read = 0;
|
|
941
|
+
for await (const page of pages) {
|
|
942
|
+
read++;
|
|
943
|
+
yield { entries: read <= from ? [] : entries(page), cursor: Math.max(read, from) };
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function startFingerprintReconcile({
|
|
947
|
+
adapter,
|
|
948
|
+
reSync,
|
|
949
|
+
startDelayMs = null,
|
|
950
|
+
maxPages: _ignored,
|
|
951
|
+
stateId = "fingerprint-reconcile",
|
|
952
|
+
...options
|
|
953
|
+
}) {
|
|
954
|
+
let queued = 0;
|
|
955
|
+
let pending = false;
|
|
956
|
+
const { request, stop, state$: catalogue$ } = startCatalogueRunner({
|
|
957
|
+
...options,
|
|
958
|
+
startDelayMs,
|
|
959
|
+
stateId,
|
|
960
|
+
keepCandidates: true,
|
|
961
|
+
// Only touch reSync when something reached the pull.
|
|
962
|
+
reSync: () => {
|
|
963
|
+
if (pending) {
|
|
964
|
+
pending = false;
|
|
965
|
+
reSync();
|
|
966
|
+
}
|
|
967
|
+
},
|
|
968
|
+
log: (event) => {
|
|
969
|
+
if (event.type === "pass-started") queued = 0;
|
|
970
|
+
},
|
|
971
|
+
adapter: {
|
|
972
|
+
fetchPages: (context, from) => skipPages(
|
|
973
|
+
adapter.fetchPages(context),
|
|
974
|
+
(page) => [...page].map(([key, fingerprint]) => ({ key, fingerprint })),
|
|
975
|
+
from
|
|
976
|
+
),
|
|
977
|
+
fingerprint: (doc) => adapter.fingerprint(doc),
|
|
978
|
+
// The feed's request size, so the runner budgets a page's refetch by its requests (#307).
|
|
979
|
+
refetchBatchSize: adapter.refetchBatchSize,
|
|
980
|
+
// It never deletes: keepCandidates only counts the products the listing did not name (`unreported`), before the
|
|
981
|
+
// brake and confirmGone, so this is never called; a call is a runner bug, and it fails the pass loudly.
|
|
982
|
+
confirmGone: async () => {
|
|
983
|
+
throw new Error("The fingerprint reconcile never deletes; confirmGone must not be called.");
|
|
984
|
+
},
|
|
985
|
+
// refreshOnly: a missing re-fetch is skipped, never tombstoned (ADR-060). A product the till lacks is left to the pull.
|
|
986
|
+
enqueue: (entries) => {
|
|
987
|
+
const known = entries.flatMap(({ key, local }) => local ? [{ id: key, local, refreshOnly: true }] : []);
|
|
988
|
+
if (!known.length) return;
|
|
989
|
+
queued += known.length;
|
|
990
|
+
pending = true;
|
|
991
|
+
adapter.enqueue(known);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
const toResult = ({ pages, compared, unlisted, complete }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0, complete: complete && pages > 0 });
|
|
996
|
+
const state = new BehaviorSubject6({ running: false });
|
|
997
|
+
let summary;
|
|
998
|
+
let result;
|
|
999
|
+
catalogue$.subscribe({
|
|
1000
|
+
next: ({ lastResult, ...rest }) => {
|
|
1001
|
+
if (lastResult !== summary) {
|
|
1002
|
+
summary = lastResult;
|
|
1003
|
+
result = lastResult && toResult(lastResult);
|
|
1004
|
+
}
|
|
1005
|
+
state.next(result ? { ...rest, lastResult: result } : rest);
|
|
1006
|
+
},
|
|
1007
|
+
complete: () => state.complete()
|
|
1008
|
+
});
|
|
1009
|
+
const reconcile = () => request().then(toResult);
|
|
663
1010
|
return { reconcile, stop, state$: state.asObservable() };
|
|
664
1011
|
}
|
|
1012
|
+
|
|
1013
|
+
// src/id-reconcile.ts
|
|
1014
|
+
function startIdReconcile({
|
|
1015
|
+
adapter,
|
|
1016
|
+
reSync,
|
|
1017
|
+
startDelayMs = 5e3,
|
|
1018
|
+
maxPages: _ignored,
|
|
1019
|
+
stateId = "id-reconcile",
|
|
1020
|
+
...options
|
|
1021
|
+
}) {
|
|
1022
|
+
const fingerprint = (ids) => [...ids].sort().join("\n");
|
|
1023
|
+
let queued = 0;
|
|
1024
|
+
let braked = false;
|
|
1025
|
+
let pending = false;
|
|
1026
|
+
const { request, stop } = startCatalogueRunner({
|
|
1027
|
+
...options,
|
|
1028
|
+
startDelayMs,
|
|
1029
|
+
stateId,
|
|
1030
|
+
// Only touch reSync when something reached the pull.
|
|
1031
|
+
reSync: () => {
|
|
1032
|
+
if (pending) {
|
|
1033
|
+
pending = false;
|
|
1034
|
+
reSync();
|
|
1035
|
+
}
|
|
1036
|
+
},
|
|
1037
|
+
log: (event) => {
|
|
1038
|
+
if (event.type === "pass-started") {
|
|
1039
|
+
queued = 0;
|
|
1040
|
+
braked = false;
|
|
1041
|
+
}
|
|
1042
|
+
if (event.type === "kept" && event.reason === "brake") braked = true;
|
|
1043
|
+
},
|
|
1044
|
+
adapter: {
|
|
1045
|
+
fetchPages: (context, from) => skipPages(
|
|
1046
|
+
adapter.fetchPages(context),
|
|
1047
|
+
(rows) => rows.map((row) => ({ key: row.id, fingerprint: fingerprint(row.variantIds) })),
|
|
1048
|
+
from
|
|
1049
|
+
),
|
|
1050
|
+
fingerprint: (doc) => fingerprint(adapter.variantIds(doc)),
|
|
1051
|
+
// The feed's request size, so the runner budgets a page's refetch by its requests (#307).
|
|
1052
|
+
refetchBatchSize: adapter.refetchBatchSize,
|
|
1053
|
+
// The proof is the feed's by-id re-read: every candidate is confirmed here and reaches the feed below as a
|
|
1054
|
+
// plain entry, never `tombstone: true`, so the feed tombstones it only when fetchByIds does not return it.
|
|
1055
|
+
confirmGone: confirmAll(options.collection),
|
|
1056
|
+
// The old entry shape. A product the till lacks is left to the pull, as before.
|
|
1057
|
+
enqueue: (entries) => {
|
|
1058
|
+
const known = entries.flatMap(({ key, local }) => local ? [{ id: key, local }] : []);
|
|
1059
|
+
if (!known.length) return;
|
|
1060
|
+
queued += known.length;
|
|
1061
|
+
pending = true;
|
|
1062
|
+
adapter.enqueue(known);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
});
|
|
1066
|
+
const reconcileIds = () => request().then(({ pages, complete }) => ({ pages, queued, truncated: false, braked, complete }));
|
|
1067
|
+
return { reconcileIds, stop };
|
|
1068
|
+
}
|
|
665
1069
|
export {
|
|
1070
|
+
CATALOGUE_OFFLINE_GAP_MS,
|
|
666
1071
|
REQUIRED_MULTI_INSTANCE_BY_ENGINE,
|
|
667
1072
|
STOCK_LEVELS_COLLECTION,
|
|
668
1073
|
STOCK_LEVELS_LAST_PASS,
|
|
@@ -675,6 +1080,8 @@ export {
|
|
|
675
1080
|
getStorageHealth,
|
|
676
1081
|
isFingerprintResultCurrent,
|
|
677
1082
|
isStorageWorkerFailure,
|
|
1083
|
+
shouldReconcileAfterGap,
|
|
1084
|
+
startCatalogueReconcile,
|
|
678
1085
|
startFingerprintReconcile,
|
|
679
1086
|
startIdReconcile,
|
|
680
1087
|
startLiveTab,
|