@tallyui/database 1.0.0 → 2.0.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/LICENSE +21 -0
- package/dist/index.d.ts +304 -5
- package/dist/index.js +626 -20
- package/package.json +9 -3
- package/src/connector-collection.ts +20 -0
- package/src/create-db.ts +54 -10
- package/src/engine.ts +5 -0
- package/src/fingerprint-reconcile.ts +158 -0
- package/src/id-reconcile.ts +131 -0
- package/src/index.ts +18 -1
- package/src/live-tab.ts +280 -0
- package/src/pass-queue.ts +19 -0
- package/src/reconcile.ts +150 -0
- package/src/replication.ts +8 -1
- package/src/stock-levels.ts +32 -0
- package/src/storage-watchdog.ts +134 -0
- package/src/storage.ts +11 -5
- package/src/replication.test.ts +0 -97
- package/src/storage.test.ts +0 -19
package/dist/index.js
CHANGED
|
@@ -1,36 +1,174 @@
|
|
|
1
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
-
}) : x)(function(x) {
|
|
4
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
-
});
|
|
7
|
-
|
|
8
1
|
// src/create-db.ts
|
|
9
|
-
import { createRxDatabase, addRxPlugin } from "rxdb";
|
|
2
|
+
import { createRxDatabase, addRxPlugin as addRxPlugin2 } from "rxdb";
|
|
10
3
|
import { RxDBDevModePlugin } from "rxdb/plugins/dev-mode";
|
|
4
|
+
import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
|
|
11
5
|
import { getRxStorageMemory } from "rxdb/plugins/storage-memory";
|
|
12
|
-
|
|
13
|
-
|
|
6
|
+
import { wrappedValidateAjvStorage } from "rxdb/plugins/validate-ajv";
|
|
7
|
+
|
|
8
|
+
// src/connector-collection.ts
|
|
9
|
+
import { addRxPlugin } from "rxdb";
|
|
10
|
+
import { RxDBMigrationSchemaPlugin } from "rxdb/plugins/migration-schema";
|
|
11
|
+
function connectorCollection(schema) {
|
|
12
|
+
addRxPlugin(RxDBMigrationSchemaPlugin);
|
|
13
|
+
const migrationStrategies = Object.fromEntries(Array.from({ length: schema.version }, (_, i) => [i + 1, () => null]));
|
|
14
|
+
return { schema, migrationStrategies };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/stock-levels.ts
|
|
18
|
+
import { STOCK_LEVELS_LAST_PASS } from "@tallyui/core";
|
|
19
|
+
var STOCK_LEVELS_COLLECTION = "stock_levels";
|
|
20
|
+
var stockLevelsSchema = {
|
|
21
|
+
version: 0,
|
|
22
|
+
primaryKey: "id",
|
|
23
|
+
type: "object",
|
|
24
|
+
properties: {
|
|
25
|
+
id: { type: "string", maxLength: 255 },
|
|
26
|
+
// Untyped: any JSON value the connector yields.
|
|
27
|
+
value: {},
|
|
28
|
+
updatedAt: { type: "string" }
|
|
29
|
+
},
|
|
30
|
+
required: ["id", "value", "updatedAt"]
|
|
31
|
+
};
|
|
32
|
+
var stockLevelsCollection = { schema: stockLevelsSchema, localDocuments: true };
|
|
33
|
+
|
|
34
|
+
// src/engine.ts
|
|
35
|
+
var WEB_STORAGE_ENGINE = "sqlite-sahpool";
|
|
36
|
+
var REQUIRED_MULTI_INSTANCE_BY_ENGINE = { "sqlite-sahpool": false };
|
|
37
|
+
|
|
38
|
+
// src/storage-watchdog.ts
|
|
39
|
+
import { BehaviorSubject } from "rxjs";
|
|
40
|
+
var STORAGE_WRITE_STALL_MS = 1e4;
|
|
41
|
+
var STORAGE_READ_WATCHDOG_MS = 3e4;
|
|
42
|
+
function isStorageWorkerFailure(error) {
|
|
43
|
+
return error instanceof Error && (error.name === "StorageWorkerStartError" || error.message.includes("StorageWorkerStartError"));
|
|
44
|
+
}
|
|
45
|
+
var READ_METHODS = ["query", "count", "findDocumentsById", "getChangedDocumentsSince"];
|
|
46
|
+
function withStorageWatchdog(storage, options = {}) {
|
|
47
|
+
const {
|
|
48
|
+
writeStallMs = STORAGE_WRITE_STALL_MS,
|
|
49
|
+
readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
|
|
50
|
+
now = Date.now,
|
|
51
|
+
setTimer = (fn, ms) => {
|
|
52
|
+
const timer = setTimeout(fn, ms);
|
|
53
|
+
return () => clearTimeout(timer);
|
|
54
|
+
}
|
|
55
|
+
} = options;
|
|
56
|
+
const health$ = new BehaviorSubject({ status: "ok", stalledWrites: 0 });
|
|
57
|
+
const stalledStarts = [];
|
|
58
|
+
let dead = false;
|
|
59
|
+
let pendingReads = 0;
|
|
60
|
+
let silentWindows = 0;
|
|
61
|
+
let settledThisWindow = false;
|
|
62
|
+
let cancelReadTimer;
|
|
63
|
+
const emit = () => health$.next({
|
|
64
|
+
status: dead ? "dead" : stalledStarts.length > 0 ? "stalled" : "ok",
|
|
65
|
+
stalledWrites: stalledStarts.length,
|
|
66
|
+
...stalledStarts.length > 0 ? { stalledSince: Math.min(...stalledStarts) } : {}
|
|
67
|
+
});
|
|
68
|
+
const settled = () => {
|
|
69
|
+
settledThisWindow = true;
|
|
70
|
+
silentWindows = 0;
|
|
71
|
+
};
|
|
72
|
+
const armReadTimer = () => {
|
|
73
|
+
settledThisWindow = false;
|
|
74
|
+
cancelReadTimer = setTimer(() => {
|
|
75
|
+
cancelReadTimer = void 0;
|
|
76
|
+
silentWindows = settledThisWindow ? 0 : silentWindows + 1;
|
|
77
|
+
if (silentWindows >= 2) {
|
|
78
|
+
dead = true;
|
|
79
|
+
emit();
|
|
80
|
+
} else armReadTimer();
|
|
81
|
+
}, readWatchdogMs);
|
|
82
|
+
};
|
|
83
|
+
const watchWrite = (promise) => {
|
|
84
|
+
const start = now();
|
|
85
|
+
let stalled = false;
|
|
86
|
+
const cancel = setTimer(() => {
|
|
87
|
+
stalled = true;
|
|
88
|
+
stalledStarts.push(start);
|
|
89
|
+
emit();
|
|
90
|
+
}, writeStallMs);
|
|
91
|
+
const done = () => {
|
|
92
|
+
cancel();
|
|
93
|
+
settled();
|
|
94
|
+
if (stalled) {
|
|
95
|
+
stalledStarts.splice(stalledStarts.indexOf(start), 1);
|
|
96
|
+
emit();
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
promise.then(done, done);
|
|
100
|
+
return promise;
|
|
101
|
+
};
|
|
102
|
+
const watchRead = (promise) => {
|
|
103
|
+
if (pendingReads++ === 0 && !dead) armReadTimer();
|
|
104
|
+
const done = () => {
|
|
105
|
+
settled();
|
|
106
|
+
if (--pendingReads === 0) {
|
|
107
|
+
cancelReadTimer?.();
|
|
108
|
+
cancelReadTimer = void 0;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
promise.then(done, done);
|
|
112
|
+
return promise;
|
|
113
|
+
};
|
|
114
|
+
return Object.assign(Object.create(storage), {
|
|
115
|
+
health$: health$.asObservable(),
|
|
116
|
+
async createStorageInstance(params) {
|
|
117
|
+
const instance = await storage.createStorageInstance(params);
|
|
118
|
+
const originalBulkWrite = instance.bulkWrite.bind(instance);
|
|
119
|
+
instance.bulkWrite = (...args) => watchWrite(originalBulkWrite(...args));
|
|
120
|
+
for (const method of READ_METHODS) {
|
|
121
|
+
if (typeof instance[method] !== "function") continue;
|
|
122
|
+
const original = instance[method].bind(instance);
|
|
123
|
+
instance[method] = (...args) => watchRead(original(...args));
|
|
124
|
+
}
|
|
125
|
+
return instance;
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/create-db.ts
|
|
131
|
+
var DEV_MODE = process.env.NODE_ENV !== "production";
|
|
132
|
+
addRxPlugin2(RxDBLocalDocumentsPlugin);
|
|
133
|
+
if (DEV_MODE) {
|
|
134
|
+
addRxPlugin2(RxDBDevModePlugin);
|
|
14
135
|
}
|
|
15
136
|
async function createTallyDatabase(options) {
|
|
137
|
+
if (options.multiInstance === true) throw new Error("multiInstance: true is unsupported: TallyUI databases are single-instance (ADR-061).");
|
|
16
138
|
const {
|
|
17
139
|
connector,
|
|
18
140
|
name = `tally_${connector.id}`,
|
|
19
141
|
storage = getRxStorageMemory()
|
|
20
142
|
} = options;
|
|
143
|
+
const watched = storage?.tallyEngine === WEB_STORAGE_ENGINE ? withStorageWatchdog(storage) : void 0;
|
|
144
|
+
const effectiveStorage = watched ?? storage;
|
|
145
|
+
const collectionConfigs = {};
|
|
146
|
+
for (const [collectionName, schema] of Object.entries(connector.schemas)) {
|
|
147
|
+
collectionConfigs[collectionName] = connectorCollection(schema);
|
|
148
|
+
}
|
|
149
|
+
if (connector.reconcile?.stock) {
|
|
150
|
+
if (STOCK_LEVELS_COLLECTION in collectionConfigs) {
|
|
151
|
+
throw new Error(`Connector "${connector.id}" defines a "${STOCK_LEVELS_COLLECTION}" collection; that name is reserved for the stock reconcile overlay.`);
|
|
152
|
+
}
|
|
153
|
+
collectionConfigs[STOCK_LEVELS_COLLECTION] = stockLevelsCollection;
|
|
154
|
+
}
|
|
21
155
|
const db = await createRxDatabase({
|
|
22
156
|
name,
|
|
23
|
-
storage,
|
|
157
|
+
// Dev mode refuses storage without a schema validator (RxDB error DVM1),
|
|
158
|
+
// and validating is what makes dev mode catch bad connector documents.
|
|
159
|
+
storage: DEV_MODE ? wrappedValidateAjvStorage({ storage: effectiveStorage }) : effectiveStorage,
|
|
24
160
|
multiInstance: false,
|
|
25
|
-
|
|
161
|
+
// RxDB rejects this outside dev mode (DB9); in dev it lets hot reload re-create the same database.
|
|
162
|
+
ignoreDuplicate: DEV_MODE
|
|
26
163
|
});
|
|
27
|
-
|
|
28
|
-
for (const [collectionName, schema] of Object.entries(connector.schemas)) {
|
|
29
|
-
collectionConfigs[collectionName] = { schema };
|
|
30
|
-
}
|
|
164
|
+
if (watched) healthByDatabase.set(db, watched.health$);
|
|
31
165
|
await db.addCollections(collectionConfigs);
|
|
32
166
|
return db;
|
|
33
167
|
}
|
|
168
|
+
var healthByDatabase = /* @__PURE__ */ new WeakMap();
|
|
169
|
+
function getStorageHealth(db) {
|
|
170
|
+
return healthByDatabase.get(db);
|
|
171
|
+
}
|
|
34
172
|
|
|
35
173
|
// src/storage.ts
|
|
36
174
|
import { getRxStorageMemory as getRxStorageMemory2 } from "rxdb/plugins/storage-memory";
|
|
@@ -43,8 +181,9 @@ function getStorage() {
|
|
|
43
181
|
'React Native detected. Pass a storage adapter explicitly:\n import { getRxStorageSQLite } from "@tallyui/storage-sqlite";\n createTallyDatabase({ connector, storage: getRxStorageSQLite({ database }) })'
|
|
44
182
|
);
|
|
45
183
|
}
|
|
46
|
-
|
|
47
|
-
|
|
184
|
+
throw new Error(
|
|
185
|
+
'Web storage is RxDB Premium SQLite-wasm, not Dexie (ADR-061). Pass it explicitly, bundling the worker entry:\n import { getRxStorageSQLiteWasm } from "@tallyui/storage-sqlite/web";\n const workerInput = new URL("@tallyui/storage-sqlite/web-worker", import.meta.url);\n createTallyDatabase({ connector, storage: getRxStorageSQLiteWasm({ workerInput }) })'
|
|
186
|
+
);
|
|
48
187
|
}
|
|
49
188
|
|
|
50
189
|
// src/replication.ts
|
|
@@ -57,9 +196,10 @@ function startReplication({
|
|
|
57
196
|
retryTime = 5e3,
|
|
58
197
|
autoStart = true
|
|
59
198
|
}) {
|
|
199
|
+
const { version } = collection.schema;
|
|
60
200
|
return replicateRxCollection({
|
|
61
201
|
collection,
|
|
62
|
-
replicationIdentifier: `${context.connectorId}-${collection.name}`,
|
|
202
|
+
replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}`,
|
|
63
203
|
pull: {
|
|
64
204
|
handler: (checkpoint, batchSize) => adapter.pull.handler(checkpoint, batchSize, context),
|
|
65
205
|
stream$: adapter.pull.stream$
|
|
@@ -73,8 +213,474 @@ function startReplication({
|
|
|
73
213
|
autoStart
|
|
74
214
|
});
|
|
75
215
|
}
|
|
216
|
+
|
|
217
|
+
// src/live-tab.ts
|
|
218
|
+
import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
|
|
219
|
+
function isHandoverMessage(data) {
|
|
220
|
+
const msg = data;
|
|
221
|
+
return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
|
|
222
|
+
}
|
|
223
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
224
|
+
function startLiveTab(options) {
|
|
225
|
+
const {
|
|
226
|
+
scope,
|
|
227
|
+
onPark,
|
|
228
|
+
isBusy,
|
|
229
|
+
maxDeferMs = 1e4,
|
|
230
|
+
ackTimeoutMs = 3e3,
|
|
231
|
+
locks = globalThis.navigator?.locks,
|
|
232
|
+
createChannel = (name2) => new BroadcastChannel(name2),
|
|
233
|
+
events = globalThis,
|
|
234
|
+
now = Date.now
|
|
235
|
+
} = options;
|
|
236
|
+
const state = new BehaviorSubject2("acquiring");
|
|
237
|
+
if (!locks) {
|
|
238
|
+
state.next("live");
|
|
239
|
+
return { state$: state.asObservable(), takeOver: () => Promise.resolve("live"), stop: () => state.complete() };
|
|
240
|
+
}
|
|
241
|
+
const name = `tally-live-tab:${scope}`;
|
|
242
|
+
let channel = createChannel(name);
|
|
243
|
+
let releaseLock;
|
|
244
|
+
let parking = false;
|
|
245
|
+
let requestCounter = 0;
|
|
246
|
+
let stopped = false;
|
|
247
|
+
let deferBlockedTimer;
|
|
248
|
+
let abortController = new AbortController();
|
|
249
|
+
const tabToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
250
|
+
const ackWaiters = /* @__PURE__ */ new Map();
|
|
251
|
+
const requestLock = (lockOptions, controller = abortController) => new Promise((resolve, reject) => {
|
|
252
|
+
locks.request(name, lockOptions.ifAvailable ? lockOptions : { ...lockOptions, signal: controller.signal }, (lock) => {
|
|
253
|
+
if (!lock || stopped || controller !== abortController) {
|
|
254
|
+
resolve(false);
|
|
255
|
+
return void 0;
|
|
256
|
+
}
|
|
257
|
+
resolve(true);
|
|
258
|
+
return new Promise((release) => {
|
|
259
|
+
releaseLock = release;
|
|
260
|
+
});
|
|
261
|
+
}).catch((error) => {
|
|
262
|
+
if (controller.signal.aborted) resolve(false);
|
|
263
|
+
else reject(error);
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
const waitForAck = (id) => new Promise((resolve) => {
|
|
267
|
+
const timer = setTimeout(() => {
|
|
268
|
+
ackWaiters.delete(id);
|
|
269
|
+
resolve(false);
|
|
270
|
+
}, ackTimeoutMs);
|
|
271
|
+
ackWaiters.set(id, () => {
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
ackWaiters.delete(id);
|
|
274
|
+
resolve(true);
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
const handleHandoverRequest = async (id) => {
|
|
278
|
+
if (state.value !== "live" || parking) return;
|
|
279
|
+
parking = true;
|
|
280
|
+
channel.postMessage({ type: "handover-ack", id });
|
|
281
|
+
try {
|
|
282
|
+
const start = now();
|
|
283
|
+
while (isBusy?.() && now() - start < maxDeferMs) await sleep(100);
|
|
284
|
+
try {
|
|
285
|
+
await onPark();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
console.warn(`live-tab: onPark failed for scope "${scope}"; parking anyway.`, error);
|
|
288
|
+
}
|
|
289
|
+
} finally {
|
|
290
|
+
releaseLock?.();
|
|
291
|
+
releaseLock = void 0;
|
|
292
|
+
parking = false;
|
|
293
|
+
state.next("parked");
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
const handleChannelMessage = (event) => {
|
|
297
|
+
if (!isHandoverMessage(event.data)) return;
|
|
298
|
+
if (event.data.type === "handover-ack") ackWaiters.get(event.data.id)?.();
|
|
299
|
+
else void handleHandoverRequest(event.data.id);
|
|
300
|
+
};
|
|
301
|
+
channel.onmessage = handleChannelMessage;
|
|
302
|
+
let inFlightTakeOver;
|
|
303
|
+
const performTakeOver = async () => {
|
|
304
|
+
state.next("acquiring");
|
|
305
|
+
if (await requestLock({ ifAvailable: true })) {
|
|
306
|
+
state.next("live");
|
|
307
|
+
return "live";
|
|
308
|
+
}
|
|
309
|
+
if (stopped) return state.value;
|
|
310
|
+
const id = `${tabToken}-${++requestCounter}`;
|
|
311
|
+
const acked = waitForAck(id);
|
|
312
|
+
channel.postMessage({ type: "handover-request", id });
|
|
313
|
+
const gotLockPromise = requestLock({});
|
|
314
|
+
const lockFirst = await Promise.race([gotLockPromise.then(() => true), acked.then(() => false)]);
|
|
315
|
+
if (lockFirst) {
|
|
316
|
+
ackWaiters.delete(id);
|
|
317
|
+
} else if (await acked) {
|
|
318
|
+
deferBlockedTimer = setTimeout(() => state.next("blocked"), maxDeferMs + ackTimeoutMs);
|
|
319
|
+
} else {
|
|
320
|
+
state.next("blocked");
|
|
321
|
+
}
|
|
322
|
+
if (stopped) return state.value;
|
|
323
|
+
const gotLock = await gotLockPromise;
|
|
324
|
+
clearTimeout(deferBlockedTimer);
|
|
325
|
+
deferBlockedTimer = void 0;
|
|
326
|
+
if (stopped) return state.value;
|
|
327
|
+
state.next(gotLock ? "live" : "blocked");
|
|
328
|
+
return gotLock ? "live" : "blocked";
|
|
329
|
+
};
|
|
330
|
+
const takeOver = () => {
|
|
331
|
+
if (stopped) return Promise.resolve(state.value);
|
|
332
|
+
if (state.value === "live") return Promise.resolve("live");
|
|
333
|
+
if (!inFlightTakeOver) {
|
|
334
|
+
inFlightTakeOver = performTakeOver().finally(() => {
|
|
335
|
+
inFlightTakeOver = void 0;
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
return inFlightTakeOver;
|
|
339
|
+
};
|
|
340
|
+
const suspend = () => {
|
|
341
|
+
stopped = true;
|
|
342
|
+
abortController.abort();
|
|
343
|
+
releaseLock?.();
|
|
344
|
+
releaseLock = void 0;
|
|
345
|
+
ackWaiters.clear();
|
|
346
|
+
clearTimeout(deferBlockedTimer);
|
|
347
|
+
deferBlockedTimer = void 0;
|
|
348
|
+
channel.onmessage = null;
|
|
349
|
+
channel.close();
|
|
350
|
+
state.next("parked");
|
|
351
|
+
};
|
|
352
|
+
const resume = () => {
|
|
353
|
+
abortController = new AbortController();
|
|
354
|
+
channel = createChannel(name);
|
|
355
|
+
channel.onmessage = handleChannelMessage;
|
|
356
|
+
stopped = false;
|
|
357
|
+
void takeOver().catch((error) => {
|
|
358
|
+
console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
|
|
359
|
+
state.next("blocked");
|
|
360
|
+
});
|
|
361
|
+
};
|
|
362
|
+
const handlePageShow = (event) => {
|
|
363
|
+
if (event.persisted && stopped) resume();
|
|
364
|
+
};
|
|
365
|
+
const handlePageHide = () => {
|
|
366
|
+
suspend();
|
|
367
|
+
void Promise.resolve().then(onPark).catch((error) => {
|
|
368
|
+
console.warn(`live-tab: onPark failed for scope "${scope}" on pagehide.`, error);
|
|
369
|
+
});
|
|
370
|
+
};
|
|
371
|
+
const stop = () => {
|
|
372
|
+
suspend();
|
|
373
|
+
events.removeEventListener?.("pagehide", handlePageHide);
|
|
374
|
+
events.removeEventListener?.("pageshow", handlePageShow);
|
|
375
|
+
state.complete();
|
|
376
|
+
};
|
|
377
|
+
events.addEventListener?.("pagehide", handlePageHide);
|
|
378
|
+
events.addEventListener?.("pageshow", handlePageShow);
|
|
379
|
+
void takeOver().catch((error) => {
|
|
380
|
+
console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
|
|
381
|
+
state.next("blocked");
|
|
382
|
+
});
|
|
383
|
+
return { state$: state.asObservable(), takeOver, stop };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// src/reconcile.ts
|
|
387
|
+
import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
|
|
388
|
+
import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core";
|
|
389
|
+
|
|
390
|
+
// src/pass-queue.ts
|
|
391
|
+
function createPassQueue(run) {
|
|
392
|
+
let current;
|
|
393
|
+
let queued;
|
|
394
|
+
const trigger = () => {
|
|
395
|
+
if (!current) return current = run().finally(() => {
|
|
396
|
+
current = void 0;
|
|
397
|
+
});
|
|
398
|
+
if (!queued) {
|
|
399
|
+
queued = current.catch(() => {
|
|
400
|
+
}).then(() => {
|
|
401
|
+
queued = void 0;
|
|
402
|
+
return trigger();
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
return queued;
|
|
406
|
+
};
|
|
407
|
+
return trigger;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// src/reconcile.ts
|
|
411
|
+
function startStockReconcile({
|
|
412
|
+
collection,
|
|
413
|
+
adapter,
|
|
414
|
+
context,
|
|
415
|
+
intervalMs = 3e5,
|
|
416
|
+
maxPages = 100
|
|
417
|
+
}) {
|
|
418
|
+
const controller = new AbortController();
|
|
419
|
+
const { signal } = controller;
|
|
420
|
+
const checkAborted = () => {
|
|
421
|
+
if (signal.aborted) throw signal.reason ?? new Error("Stock reconcile stopped");
|
|
422
|
+
};
|
|
423
|
+
const state = new BehaviorSubject3({ running: false, truncated: false });
|
|
424
|
+
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
425
|
+
const lastPass = collection.getLocal(STOCK_LEVELS_LAST_PASS2).catch((error) => {
|
|
426
|
+
if (error?.code !== "LD8") return null;
|
|
427
|
+
throw new Error(`Create "${collection.name}" with stockLevelsCollection (localDocuments: true); stock reconcile stores its last pass there.`, { cause: error });
|
|
428
|
+
});
|
|
429
|
+
lastPass.then((doc) => {
|
|
430
|
+
if (doc && !state.value.lastCompletedAt) update({ lastCompletedAt: doc.get("completedAt") });
|
|
431
|
+
}, () => {
|
|
432
|
+
});
|
|
433
|
+
const pass = async () => {
|
|
434
|
+
checkAborted();
|
|
435
|
+
await lastPass;
|
|
436
|
+
const stock = /* @__PURE__ */ new Map();
|
|
437
|
+
let pages = 0;
|
|
438
|
+
for await (const page of adapter.fetchPages({ ...context, signal })) {
|
|
439
|
+
checkAborted();
|
|
440
|
+
if (pages === maxPages) {
|
|
441
|
+
console.warn(`Stock reconcile stopped at the ${maxPages}-page limit; nothing was written.`);
|
|
442
|
+
return { pages, written: 0, removed: 0, truncated: true };
|
|
443
|
+
}
|
|
444
|
+
pages++;
|
|
445
|
+
for (const [key, value] of page) stock.set(key, value);
|
|
446
|
+
}
|
|
447
|
+
const rows = (await collection.find().exec()).map((doc) => doc.toJSON());
|
|
448
|
+
const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
|
|
449
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
450
|
+
const upserts = [...stock].filter(([id, value]) => stored.get(id) !== JSON.stringify(value)).map(([id, value]) => ({ id, value, updatedAt }));
|
|
451
|
+
const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
|
|
452
|
+
checkAborted();
|
|
453
|
+
if (upserts.length) {
|
|
454
|
+
const { error } = await collection.bulkUpsert(upserts);
|
|
455
|
+
if (error.length) throw error[0];
|
|
456
|
+
}
|
|
457
|
+
if (removals.length) {
|
|
458
|
+
const { error } = await collection.bulkRemove(removals);
|
|
459
|
+
if (error.length) throw error[0];
|
|
460
|
+
}
|
|
461
|
+
const completedAt = updatedAt;
|
|
462
|
+
checkAborted();
|
|
463
|
+
await collection.upsertLocal(STOCK_LEVELS_LAST_PASS2, { completedAt });
|
|
464
|
+
return { pages, written: upserts.length, removed: removals.length, truncated: false, completedAt };
|
|
465
|
+
};
|
|
466
|
+
const tracked = async () => {
|
|
467
|
+
update({ running: true });
|
|
468
|
+
try {
|
|
469
|
+
const result = await pass();
|
|
470
|
+
if (result.truncated) update({ running: false, truncated: true });
|
|
471
|
+
else state.next({ running: false, truncated: false, lastCompletedAt: result.completedAt });
|
|
472
|
+
return result;
|
|
473
|
+
} catch (error) {
|
|
474
|
+
update({ running: false, lastError: error });
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
const reconcileStock = createPassQueue(tracked);
|
|
479
|
+
const timer = setInterval(() => {
|
|
480
|
+
reconcileStock().catch((error) => console.warn("Stock reconcile failed:", error));
|
|
481
|
+
}, intervalMs);
|
|
482
|
+
const stop = () => {
|
|
483
|
+
clearInterval(timer);
|
|
484
|
+
context.signal?.removeEventListener("abort", stop);
|
|
485
|
+
controller.abort();
|
|
486
|
+
state.complete();
|
|
487
|
+
};
|
|
488
|
+
if (context.signal?.aborted) stop();
|
|
489
|
+
else context.signal?.addEventListener("abort", stop);
|
|
490
|
+
return { reconcileStock, stop, state$: state.asObservable() };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// src/id-reconcile.ts
|
|
494
|
+
import { readFresh } from "@tallyui/core/rxdb";
|
|
495
|
+
var MASS_DELETE_MINIMUM = 10;
|
|
496
|
+
function startIdReconcile({
|
|
497
|
+
collection,
|
|
498
|
+
adapter,
|
|
499
|
+
context,
|
|
500
|
+
reSync,
|
|
501
|
+
startDelayMs = 5e3,
|
|
502
|
+
intervalMs = 864e5,
|
|
503
|
+
maxPages = 100,
|
|
504
|
+
maxDeleteShare = 0.2,
|
|
505
|
+
allowMassDelete = false
|
|
506
|
+
}) {
|
|
507
|
+
const controller = new AbortController();
|
|
508
|
+
const { signal } = controller;
|
|
509
|
+
const checkAborted = () => {
|
|
510
|
+
if (signal.aborted) throw signal.reason ?? new Error("Id reconcile stopped");
|
|
511
|
+
};
|
|
512
|
+
const pass = async () => {
|
|
513
|
+
checkAborted();
|
|
514
|
+
const remote = /* @__PURE__ */ new Map();
|
|
515
|
+
let pages = 0;
|
|
516
|
+
for await (const page of adapter.fetchPages({ ...context, signal })) {
|
|
517
|
+
checkAborted();
|
|
518
|
+
if (pages === maxPages) {
|
|
519
|
+
console.warn(`Id reconcile stopped at the ${maxPages}-page limit; nothing was queued.`);
|
|
520
|
+
return { pages, queued: 0, truncated: true, braked: false };
|
|
521
|
+
}
|
|
522
|
+
pages++;
|
|
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();
|
|
548
|
+
}
|
|
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
|
+
};
|
|
569
|
+
if (context.signal?.aborted) stop();
|
|
570
|
+
else context.signal?.addEventListener("abort", stop);
|
|
571
|
+
return { reconcileIds, stop };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// src/fingerprint-reconcile.ts
|
|
575
|
+
import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
|
|
576
|
+
import { readFresh as readFresh2 } from "@tallyui/core/rxdb";
|
|
577
|
+
function isFingerprintResultCurrent(state) {
|
|
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");
|
|
594
|
+
};
|
|
595
|
+
const state = new BehaviorSubject4({ running: false });
|
|
596
|
+
const update = (patch) => state.next({ ...state.value, ...patch });
|
|
597
|
+
const pass = async () => {
|
|
598
|
+
checkAborted();
|
|
599
|
+
const remote = /* @__PURE__ */ new Map();
|
|
600
|
+
let pages = 0;
|
|
601
|
+
for await (const page of adapter.fetchPages({ ...context, signal })) {
|
|
602
|
+
checkAborted();
|
|
603
|
+
if (pages === maxPages) {
|
|
604
|
+
console.warn(`Fingerprint reconcile stopped at the ${maxPages}-page limit; nothing was queued.`);
|
|
605
|
+
return { pages, compared: 0, queued: 0, truncated: true, unreported: 0 };
|
|
606
|
+
}
|
|
607
|
+
pages++;
|
|
608
|
+
for (const [id, fingerprint] of page) remote.set(id, fingerprint);
|
|
609
|
+
}
|
|
610
|
+
checkAborted();
|
|
611
|
+
const entries = [];
|
|
612
|
+
let compared = 0;
|
|
613
|
+
let unreported = 0;
|
|
614
|
+
for (const local of await readFresh2(collection, {})) {
|
|
615
|
+
const id = local[collection.schema.primaryPath];
|
|
616
|
+
const remoteFingerprint = remote.get(id);
|
|
617
|
+
if (remoteFingerprint === void 0) {
|
|
618
|
+
if (pages > 0) unreported++;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
compared++;
|
|
622
|
+
if (adapter.fingerprint(local) !== remoteFingerprint) entries.push({ id, local, refreshOnly: true });
|
|
623
|
+
}
|
|
624
|
+
checkAborted();
|
|
625
|
+
if (entries.length) {
|
|
626
|
+
adapter.enqueue(entries);
|
|
627
|
+
reSync();
|
|
628
|
+
}
|
|
629
|
+
return { pages, compared, queued: entries.length, truncated: false, unreported };
|
|
630
|
+
};
|
|
631
|
+
const tracked = async () => {
|
|
632
|
+
update({ running: true });
|
|
633
|
+
try {
|
|
634
|
+
const result = await pass();
|
|
635
|
+
update({ running: false, lastResult: result, lastResultAt: now() });
|
|
636
|
+
return result;
|
|
637
|
+
} catch (error) {
|
|
638
|
+
update({ running: false, lastError: error, lastErrorAt: now() });
|
|
639
|
+
throw error;
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
const reconcile = createPassQueue(tracked);
|
|
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);
|
|
654
|
+
const stop = () => {
|
|
655
|
+
clearTimeout(startTimer);
|
|
656
|
+
clearInterval(intervalTimer);
|
|
657
|
+
context.signal?.removeEventListener("abort", stop);
|
|
658
|
+
controller.abort();
|
|
659
|
+
state.complete();
|
|
660
|
+
};
|
|
661
|
+
if (context.signal?.aborted) stop();
|
|
662
|
+
else context.signal?.addEventListener("abort", stop);
|
|
663
|
+
return { reconcile, stop, state$: state.asObservable() };
|
|
664
|
+
}
|
|
76
665
|
export {
|
|
666
|
+
REQUIRED_MULTI_INSTANCE_BY_ENGINE,
|
|
667
|
+
STOCK_LEVELS_COLLECTION,
|
|
668
|
+
STOCK_LEVELS_LAST_PASS,
|
|
669
|
+
STORAGE_READ_WATCHDOG_MS,
|
|
670
|
+
STORAGE_WRITE_STALL_MS,
|
|
671
|
+
WEB_STORAGE_ENGINE,
|
|
672
|
+
connectorCollection,
|
|
77
673
|
createTallyDatabase,
|
|
78
674
|
getStorage,
|
|
79
|
-
|
|
675
|
+
getStorageHealth,
|
|
676
|
+
isFingerprintResultCurrent,
|
|
677
|
+
isStorageWorkerFailure,
|
|
678
|
+
startFingerprintReconcile,
|
|
679
|
+
startIdReconcile,
|
|
680
|
+
startLiveTab,
|
|
681
|
+
startReplication,
|
|
682
|
+
startStockReconcile,
|
|
683
|
+
stockLevelsCollection,
|
|
684
|
+
stockLevelsSchema,
|
|
685
|
+
withStorageWatchdog
|
|
80
686
|
};
|