@tallyui/database 3.18.0 → 3.19.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 +211 -2
- package/dist/index.js +416 -14
- package/package.json +2 -2
- package/src/index.ts +21 -0
- package/src/replication.ts +7 -1
- package/src/request-metrics-store.ts +122 -0
- package/src/request-metrics.ts +180 -0
- package/src/sync-cadence-runner.ts +93 -0
- package/src/sync-cadence-store.ts +91 -0
- package/src/sync-cadence.ts +79 -0
package/dist/index.js
CHANGED
|
@@ -257,7 +257,8 @@ function startReplication({
|
|
|
257
257
|
retryTime = 5e3,
|
|
258
258
|
autoStart = true,
|
|
259
259
|
maxRetryTimeMs = MAX_RETRY_TIME_MS,
|
|
260
|
-
connectivity
|
|
260
|
+
connectivity,
|
|
261
|
+
pullBatchSize
|
|
261
262
|
}) {
|
|
262
263
|
let state;
|
|
263
264
|
const notice$ = new BehaviorSubject2(void 0);
|
|
@@ -314,7 +315,7 @@ function startReplication({
|
|
|
314
315
|
pull: {
|
|
315
316
|
handler: pullHandler,
|
|
316
317
|
stream$: adapter.pull.stream$?.pipe(filter((event) => event === "RESYNC" || !tillHeld$.getValue())),
|
|
317
|
-
batchSize: adapter.pull.batchSize
|
|
318
|
+
batchSize: pullBatchSize ?? adapter.pull.batchSize
|
|
318
319
|
},
|
|
319
320
|
push: adapter.push ? {
|
|
320
321
|
// A push is held, never thrown or dropped, while latched, held for sign-in or paused: before the send, and
|
|
@@ -431,7 +432,7 @@ function isHandoverMessage(data) {
|
|
|
431
432
|
const msg = data;
|
|
432
433
|
return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
|
|
433
434
|
}
|
|
434
|
-
var sleep = (ms) => new Promise((
|
|
435
|
+
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
435
436
|
function startLiveTab(options) {
|
|
436
437
|
const {
|
|
437
438
|
scope,
|
|
@@ -459,30 +460,30 @@ function startLiveTab(options) {
|
|
|
459
460
|
let abortController = new AbortController();
|
|
460
461
|
const tabToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
461
462
|
const ackWaiters = /* @__PURE__ */ new Map();
|
|
462
|
-
const requestLock = (lockOptions, controller = abortController) => new Promise((
|
|
463
|
+
const requestLock = (lockOptions, controller = abortController) => new Promise((resolve2, reject) => {
|
|
463
464
|
locks.request(name, lockOptions.ifAvailable ? lockOptions : { ...lockOptions, signal: controller.signal }, (lock) => {
|
|
464
465
|
if (!lock || stopped || controller !== abortController) {
|
|
465
|
-
|
|
466
|
+
resolve2(false);
|
|
466
467
|
return void 0;
|
|
467
468
|
}
|
|
468
|
-
|
|
469
|
+
resolve2(true);
|
|
469
470
|
return new Promise((release) => {
|
|
470
471
|
releaseLock = release;
|
|
471
472
|
});
|
|
472
473
|
}).catch((error) => {
|
|
473
|
-
if (controller.signal.aborted)
|
|
474
|
+
if (controller.signal.aborted) resolve2(false);
|
|
474
475
|
else reject(error);
|
|
475
476
|
});
|
|
476
477
|
});
|
|
477
|
-
const waitForAck = (id) => new Promise((
|
|
478
|
+
const waitForAck = (id) => new Promise((resolve2) => {
|
|
478
479
|
const timer2 = setTimeout(() => {
|
|
479
480
|
ackWaiters.delete(id);
|
|
480
|
-
|
|
481
|
+
resolve2(false);
|
|
481
482
|
}, ackTimeoutMs);
|
|
482
483
|
ackWaiters.set(id, () => {
|
|
483
484
|
clearTimeout(timer2);
|
|
484
485
|
ackWaiters.delete(id);
|
|
485
|
-
|
|
486
|
+
resolve2(true);
|
|
486
487
|
});
|
|
487
488
|
});
|
|
488
489
|
const handleHandoverRequest = async (id) => {
|
|
@@ -602,7 +603,7 @@ import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core
|
|
|
602
603
|
import { readFresh } from "@tallyui/core/rxdb";
|
|
603
604
|
var BACKGROUND_CHUNK_SIZE = 250;
|
|
604
605
|
function pauseBetweenChunks() {
|
|
605
|
-
return new Promise((
|
|
606
|
+
return new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
606
607
|
}
|
|
607
608
|
async function* readFreshInChunks(collection, size = BACKGROUND_CHUNK_SIZE) {
|
|
608
609
|
const key = collection.schema.primaryPath;
|
|
@@ -818,14 +819,14 @@ function startCatalogueRunner({
|
|
|
818
819
|
}
|
|
819
820
|
}).catch(() => {
|
|
820
821
|
});
|
|
821
|
-
const sleep2 = (ms) => new Promise((
|
|
822
|
+
const sleep2 = (ms) => new Promise((resolve2) => {
|
|
822
823
|
const onAbort = () => {
|
|
823
824
|
cancel();
|
|
824
|
-
|
|
825
|
+
resolve2();
|
|
825
826
|
};
|
|
826
827
|
const cancel = setTimer(() => {
|
|
827
828
|
signal.removeEventListener("abort", onAbort);
|
|
828
|
-
|
|
829
|
+
resolve2();
|
|
829
830
|
}, ms);
|
|
830
831
|
signal.addEventListener("abort", onAbort);
|
|
831
832
|
});
|
|
@@ -1184,25 +1185,420 @@ function startIdReconcile({
|
|
|
1184
1185
|
const reconcileIds = () => request().then(({ pages, complete }) => ({ pages, queued, truncated: false, braked, complete }));
|
|
1185
1186
|
return { reconcileIds, stop };
|
|
1186
1187
|
}
|
|
1188
|
+
|
|
1189
|
+
// src/sync-cadence.ts
|
|
1190
|
+
var SYNC_CADENCE_PRESETS = {
|
|
1191
|
+
eco: { checkIntervalMs: 3e5, pullBatchSize: 25 },
|
|
1192
|
+
balanced: { checkIntervalMs: 6e4, pullBatchSize: 50 },
|
|
1193
|
+
realtime: { checkIntervalMs: 1e4, pullBatchSize: 75 }
|
|
1194
|
+
};
|
|
1195
|
+
var DEFAULT_SYNC_CADENCE_PRESET = "balanced";
|
|
1196
|
+
var SYNC_CADENCE_LIMITS = {
|
|
1197
|
+
checkIntervalMs: { min: 5e3, max: 3e5 },
|
|
1198
|
+
pullBatchSize: { min: 10, max: 100 }
|
|
1199
|
+
};
|
|
1200
|
+
function isSyncCadencePreset(value) {
|
|
1201
|
+
return typeof value === "string" && Object.prototype.hasOwnProperty.call(SYNC_CADENCE_PRESETS, value);
|
|
1202
|
+
}
|
|
1203
|
+
function clampField(name, value) {
|
|
1204
|
+
const raw = value ?? SYNC_CADENCE_PRESETS[DEFAULT_SYNC_CADENCE_PRESET][name];
|
|
1205
|
+
if (!Number.isFinite(raw)) throw new TypeError(`${name} must be a finite number`);
|
|
1206
|
+
const { min, max } = SYNC_CADENCE_LIMITS[name];
|
|
1207
|
+
return Math.min(max, Math.max(min, Math.trunc(raw)));
|
|
1208
|
+
}
|
|
1209
|
+
function clampSyncCadence(value) {
|
|
1210
|
+
return {
|
|
1211
|
+
checkIntervalMs: clampField("checkIntervalMs", value.checkIntervalMs),
|
|
1212
|
+
pullBatchSize: clampField("pullBatchSize", value.pullBatchSize)
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
function syncCadencePresetFor(value) {
|
|
1216
|
+
for (const name of Object.keys(SYNC_CADENCE_PRESETS)) {
|
|
1217
|
+
const preset = SYNC_CADENCE_PRESETS[name];
|
|
1218
|
+
if (preset.checkIntervalMs === value.checkIntervalMs && preset.pullBatchSize === value.pullBatchSize) return name;
|
|
1219
|
+
}
|
|
1220
|
+
return "custom";
|
|
1221
|
+
}
|
|
1222
|
+
function syncCadencePresetBudget(name) {
|
|
1223
|
+
return {
|
|
1224
|
+
intervalSeconds: Math.round(SYNC_CADENCE_PRESETS[name].checkIntervalMs / 1e3),
|
|
1225
|
+
records: SYNC_CADENCE_PRESETS[name].pullBatchSize
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
function requestsPerHour(checkIntervalMs) {
|
|
1229
|
+
return Math.round(36e5 / checkIntervalMs);
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// src/sync-cadence-store.ts
|
|
1233
|
+
import { distinctUntilChanged, map } from "rxjs";
|
|
1234
|
+
var SYNC_CADENCE_COLLECTION = "sync_cadence";
|
|
1235
|
+
var SYNC_CADENCE_DOC_ID = "default";
|
|
1236
|
+
var syncCadenceSchema = {
|
|
1237
|
+
version: 0,
|
|
1238
|
+
primaryKey: "id",
|
|
1239
|
+
type: "object",
|
|
1240
|
+
additionalProperties: false,
|
|
1241
|
+
properties: {
|
|
1242
|
+
id: { type: "string", maxLength: 64 },
|
|
1243
|
+
preset: { type: "string", enum: ["eco", "balanced", "realtime", "custom"] },
|
|
1244
|
+
checkIntervalMs: {
|
|
1245
|
+
type: "integer",
|
|
1246
|
+
minimum: SYNC_CADENCE_LIMITS.checkIntervalMs.min,
|
|
1247
|
+
maximum: SYNC_CADENCE_LIMITS.checkIntervalMs.max
|
|
1248
|
+
},
|
|
1249
|
+
pullBatchSize: {
|
|
1250
|
+
type: "integer",
|
|
1251
|
+
minimum: SYNC_CADENCE_LIMITS.pullBatchSize.min,
|
|
1252
|
+
maximum: SYNC_CADENCE_LIMITS.pullBatchSize.max
|
|
1253
|
+
},
|
|
1254
|
+
updatedAt: { type: "string" }
|
|
1255
|
+
},
|
|
1256
|
+
required: ["id", "preset", "updatedAt"]
|
|
1257
|
+
};
|
|
1258
|
+
function syncCadenceCollection() {
|
|
1259
|
+
return { schema: syncCadenceSchema };
|
|
1260
|
+
}
|
|
1261
|
+
async function addSyncCadenceCollection(db) {
|
|
1262
|
+
const added = await db.addCollections({ [SYNC_CADENCE_COLLECTION]: syncCadenceCollection() });
|
|
1263
|
+
return added[SYNC_CADENCE_COLLECTION];
|
|
1264
|
+
}
|
|
1265
|
+
function resolve(doc) {
|
|
1266
|
+
if (!doc) return { preset: DEFAULT_SYNC_CADENCE_PRESET, ...SYNC_CADENCE_PRESETS[DEFAULT_SYNC_CADENCE_PRESET] };
|
|
1267
|
+
if (isSyncCadencePreset(doc.preset)) return { preset: doc.preset, ...SYNC_CADENCE_PRESETS[doc.preset] };
|
|
1268
|
+
const { checkIntervalMs, pullBatchSize } = doc;
|
|
1269
|
+
return { preset: "custom", ...clampSyncCadence({ checkIntervalMs, pullBatchSize }) };
|
|
1270
|
+
}
|
|
1271
|
+
async function readSyncCadence(collection) {
|
|
1272
|
+
return resolve(await collection.findOne(SYNC_CADENCE_DOC_ID).exec());
|
|
1273
|
+
}
|
|
1274
|
+
function syncCadence$(collection) {
|
|
1275
|
+
return collection.findOne(SYNC_CADENCE_DOC_ID).$.pipe(
|
|
1276
|
+
map(resolve),
|
|
1277
|
+
distinctUntilChanged((a, b) => a.preset === b.preset && a.checkIntervalMs === b.checkIntervalMs && a.pullBatchSize === b.pullBatchSize)
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
async function setSyncCadence(collection, value, options) {
|
|
1281
|
+
if (typeof value === "string" && !isSyncCadencePreset(value)) {
|
|
1282
|
+
throw new TypeError(`unknown sync cadence preset: ${String(value)}`);
|
|
1283
|
+
}
|
|
1284
|
+
const updatedAt = new Date((options?.now ?? Date.now)()).toISOString();
|
|
1285
|
+
const clamped = typeof value === "string" ? void 0 : clampSyncCadence(value);
|
|
1286
|
+
const preset = clamped ? syncCadencePresetFor(clamped) : value;
|
|
1287
|
+
const doc = { id: SYNC_CADENCE_DOC_ID, preset, ...preset === "custom" ? clamped : {}, updatedAt };
|
|
1288
|
+
await collection.upsert(doc);
|
|
1289
|
+
return resolve(doc);
|
|
1290
|
+
}
|
|
1291
|
+
function resetSyncCadence(collection, options) {
|
|
1292
|
+
return setSyncCadence(collection, DEFAULT_SYNC_CADENCE_PRESET, options);
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/sync-cadence-runner.ts
|
|
1296
|
+
import { BehaviorSubject as BehaviorSubject8 } from "rxjs";
|
|
1297
|
+
function jitteredIntervalMs(intervalMs, random) {
|
|
1298
|
+
return Math.round(intervalMs * (0.8 + 0.4 * random()));
|
|
1299
|
+
}
|
|
1300
|
+
function startSyncCadence({
|
|
1301
|
+
targets,
|
|
1302
|
+
cadence$,
|
|
1303
|
+
connectivity,
|
|
1304
|
+
random = Math.random,
|
|
1305
|
+
now = Date.now
|
|
1306
|
+
}) {
|
|
1307
|
+
const nextDueAtMs$ = new BehaviorSubject8(void 0);
|
|
1308
|
+
let current;
|
|
1309
|
+
let timer2;
|
|
1310
|
+
let stopped = false;
|
|
1311
|
+
const tick = () => {
|
|
1312
|
+
if (connectivity?.current().updateRequired) return;
|
|
1313
|
+
for (const target of targets) {
|
|
1314
|
+
try {
|
|
1315
|
+
if (target.isPaused?.() !== true) target.reSync();
|
|
1316
|
+
} catch {
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
const arm = () => {
|
|
1321
|
+
if (timer2 !== void 0) clearTimeout(timer2);
|
|
1322
|
+
timer2 = void 0;
|
|
1323
|
+
if (stopped || !current) return;
|
|
1324
|
+
const delay = jitteredIntervalMs(current.checkIntervalMs, random);
|
|
1325
|
+
timer2 = setTimeout(() => {
|
|
1326
|
+
timer2 = void 0;
|
|
1327
|
+
tick();
|
|
1328
|
+
arm();
|
|
1329
|
+
}, delay);
|
|
1330
|
+
nextDueAtMs$.next(now() + delay);
|
|
1331
|
+
};
|
|
1332
|
+
const subscription = cadence$.subscribe((cadence) => {
|
|
1333
|
+
if (stopped) return;
|
|
1334
|
+
if (current && current.checkIntervalMs === cadence.checkIntervalMs && current.pullBatchSize === cadence.pullBatchSize) return;
|
|
1335
|
+
current = cadence;
|
|
1336
|
+
arm();
|
|
1337
|
+
});
|
|
1338
|
+
return {
|
|
1339
|
+
nextDueAtMs$: nextDueAtMs$.asObservable(),
|
|
1340
|
+
tickNow: () => {
|
|
1341
|
+
if (stopped) return;
|
|
1342
|
+
tick();
|
|
1343
|
+
arm();
|
|
1344
|
+
},
|
|
1345
|
+
stop: () => {
|
|
1346
|
+
if (stopped) return;
|
|
1347
|
+
stopped = true;
|
|
1348
|
+
if (timer2 !== void 0) clearTimeout(timer2);
|
|
1349
|
+
timer2 = void 0;
|
|
1350
|
+
subscription.unsubscribe();
|
|
1351
|
+
nextDueAtMs$.next(void 0);
|
|
1352
|
+
nextDueAtMs$.complete();
|
|
1353
|
+
}
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// src/request-metrics.ts
|
|
1358
|
+
import { BehaviorSubject as BehaviorSubject9 } from "rxjs";
|
|
1359
|
+
var REQUEST_METRICS_HOUR_MS = 36e5;
|
|
1360
|
+
var REQUEST_METRICS_MAX_BUCKETS = 48;
|
|
1361
|
+
var REQUIRED_NUMBERS = ["hourStartMs", "requests", "bytes", "durationTotalMs", "durationCount", "errors"];
|
|
1362
|
+
var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
|
|
1363
|
+
function isRequestMetricsBucket(value) {
|
|
1364
|
+
if (!value || typeof value !== "object") return false;
|
|
1365
|
+
const bucket = value;
|
|
1366
|
+
if (!REQUIRED_NUMBERS.every((key) => isFiniteNumber(bucket[key]))) return false;
|
|
1367
|
+
return (bucket.loadLast === void 0 || isFiniteNumber(bucket.loadLast)) && (bucket.loadMax === void 0 || isFiniteNumber(bucket.loadMax));
|
|
1368
|
+
}
|
|
1369
|
+
function createRequestMetrics(options = {}) {
|
|
1370
|
+
const now = options.now ?? Date.now;
|
|
1371
|
+
const map2 = /* @__PURE__ */ new Map();
|
|
1372
|
+
const buckets = () => [...map2.values()].sort((a, b) => a.hourStartMs - b.hourStartMs).map((bucket) => ({ ...bucket }));
|
|
1373
|
+
const subject = new BehaviorSubject9([]);
|
|
1374
|
+
const getOrCreateBucket = (atMs) => {
|
|
1375
|
+
const start = Math.floor(atMs / REQUEST_METRICS_HOUR_MS) * REQUEST_METRICS_HOUR_MS;
|
|
1376
|
+
let bucket = map2.get(start);
|
|
1377
|
+
if (!bucket) {
|
|
1378
|
+
bucket = { hourStartMs: start, requests: 0, bytes: 0, durationTotalMs: 0, durationCount: 0, errors: 0 };
|
|
1379
|
+
map2.set(start, bucket);
|
|
1380
|
+
}
|
|
1381
|
+
return bucket;
|
|
1382
|
+
};
|
|
1383
|
+
const commit = () => {
|
|
1384
|
+
const hours = [...map2.keys()].sort((a, b) => a - b);
|
|
1385
|
+
for (const start of hours.slice(0, -REQUEST_METRICS_MAX_BUCKETS)) map2.delete(start);
|
|
1386
|
+
subject.next(buckets());
|
|
1387
|
+
};
|
|
1388
|
+
return {
|
|
1389
|
+
record({ atMs, durationMs, bytes, failed }) {
|
|
1390
|
+
const bucket = getOrCreateBucket(atMs);
|
|
1391
|
+
bucket.requests += 1;
|
|
1392
|
+
if (Number.isFinite(bytes) && bytes >= 0) bucket.bytes += bytes;
|
|
1393
|
+
bucket.durationTotalMs += Math.max(0, durationMs);
|
|
1394
|
+
bucket.durationCount += 1;
|
|
1395
|
+
if (failed) bucket.errors += 1;
|
|
1396
|
+
commit();
|
|
1397
|
+
},
|
|
1398
|
+
recordServerLoad(load1, atMs) {
|
|
1399
|
+
if (!Number.isFinite(load1)) return;
|
|
1400
|
+
const bucket = getOrCreateBucket(atMs ?? now());
|
|
1401
|
+
bucket.loadLast = load1;
|
|
1402
|
+
bucket.loadMax = Math.max(bucket.loadMax ?? load1, load1);
|
|
1403
|
+
commit();
|
|
1404
|
+
},
|
|
1405
|
+
buckets,
|
|
1406
|
+
buckets$: subject.asObservable(),
|
|
1407
|
+
hydrate(persisted) {
|
|
1408
|
+
if (!Array.isArray(persisted)) return;
|
|
1409
|
+
let changed = false;
|
|
1410
|
+
for (const bucket of persisted) {
|
|
1411
|
+
if (!isRequestMetricsBucket(bucket)) continue;
|
|
1412
|
+
changed = true;
|
|
1413
|
+
const existing = map2.get(bucket.hourStartMs);
|
|
1414
|
+
if (!existing) {
|
|
1415
|
+
map2.set(bucket.hourStartMs, { ...bucket });
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
existing.requests += bucket.requests;
|
|
1419
|
+
existing.bytes += bucket.bytes;
|
|
1420
|
+
existing.durationTotalMs += bucket.durationTotalMs;
|
|
1421
|
+
existing.durationCount += bucket.durationCount;
|
|
1422
|
+
existing.errors += bucket.errors;
|
|
1423
|
+
if (bucket.loadMax !== void 0) existing.loadMax = Math.max(existing.loadMax ?? bucket.loadMax, bucket.loadMax);
|
|
1424
|
+
if (existing.loadLast === void 0 && bucket.loadLast !== void 0) existing.loadLast = bucket.loadLast;
|
|
1425
|
+
}
|
|
1426
|
+
if (changed) commit();
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
var defaultIsFailure = (response) => !response.ok && response.status !== 304;
|
|
1431
|
+
function parseServerLoad(raw) {
|
|
1432
|
+
if (raw === null) return void 0;
|
|
1433
|
+
try {
|
|
1434
|
+
const parsed = JSON.parse(raw);
|
|
1435
|
+
return Array.isArray(parsed) && isFiniteNumber(parsed[0]) ? parsed[0] : void 0;
|
|
1436
|
+
} catch {
|
|
1437
|
+
return void 0;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
function meteredFetch(fetch, metrics, options = {}) {
|
|
1441
|
+
const now = options.now ?? Date.now;
|
|
1442
|
+
const isFailure = options.isFailure ?? defaultIsFailure;
|
|
1443
|
+
return async (input, init) => {
|
|
1444
|
+
const start = now();
|
|
1445
|
+
let response;
|
|
1446
|
+
try {
|
|
1447
|
+
response = await fetch(input, init);
|
|
1448
|
+
} catch (error) {
|
|
1449
|
+
const aborted = error?.name === "AbortError" || init?.signal?.aborted === true;
|
|
1450
|
+
metrics.record({ atMs: start, durationMs: now() - start, bytes: 0, failed: !aborted });
|
|
1451
|
+
throw error;
|
|
1452
|
+
}
|
|
1453
|
+
const contentLength = Number(response.headers.get("content-length"));
|
|
1454
|
+
const bytes = Number.isFinite(contentLength) && contentLength >= 0 ? contentLength : 0;
|
|
1455
|
+
metrics.record({ atMs: start, durationMs: now() - start, bytes, failed: isFailure(response) });
|
|
1456
|
+
if (options.serverLoadHeader !== void 0) {
|
|
1457
|
+
const load = parseServerLoad(response.headers.get(options.serverLoadHeader));
|
|
1458
|
+
if (load !== void 0) metrics.recordServerLoad(load, start);
|
|
1459
|
+
}
|
|
1460
|
+
return response;
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/request-metrics-store.ts
|
|
1465
|
+
var REQUEST_METRICS_COLLECTION = "request_metrics";
|
|
1466
|
+
var REQUEST_METRICS_PERSIST_INTERVAL_MS = 3e5;
|
|
1467
|
+
var COUNT = { type: "integer", minimum: 0 };
|
|
1468
|
+
var AMOUNT = { type: "number", minimum: 0 };
|
|
1469
|
+
var requestMetricsSchema = {
|
|
1470
|
+
version: 0,
|
|
1471
|
+
primaryKey: "hour",
|
|
1472
|
+
type: "object",
|
|
1473
|
+
additionalProperties: false,
|
|
1474
|
+
properties: {
|
|
1475
|
+
hour: { type: "string", maxLength: 16 },
|
|
1476
|
+
hourStartMs: COUNT,
|
|
1477
|
+
requests: COUNT,
|
|
1478
|
+
bytes: AMOUNT,
|
|
1479
|
+
durationTotalMs: AMOUNT,
|
|
1480
|
+
durationCount: COUNT,
|
|
1481
|
+
errors: COUNT,
|
|
1482
|
+
loadLast: { type: "number" },
|
|
1483
|
+
loadMax: { type: "number" }
|
|
1484
|
+
},
|
|
1485
|
+
required: ["hour", "hourStartMs", "requests", "bytes", "durationTotalMs", "durationCount", "errors"]
|
|
1486
|
+
};
|
|
1487
|
+
function requestMetricsCollection() {
|
|
1488
|
+
return { schema: requestMetricsSchema };
|
|
1489
|
+
}
|
|
1490
|
+
async function addRequestMetricsCollection(db) {
|
|
1491
|
+
const added = await db.addCollections({ [REQUEST_METRICS_COLLECTION]: requestMetricsCollection() });
|
|
1492
|
+
return added[REQUEST_METRICS_COLLECTION];
|
|
1493
|
+
}
|
|
1494
|
+
var FIELDS = [
|
|
1495
|
+
"hourStartMs",
|
|
1496
|
+
"requests",
|
|
1497
|
+
"bytes",
|
|
1498
|
+
"durationTotalMs",
|
|
1499
|
+
"durationCount",
|
|
1500
|
+
"errors",
|
|
1501
|
+
"loadLast",
|
|
1502
|
+
"loadMax"
|
|
1503
|
+
];
|
|
1504
|
+
function toBucket(source) {
|
|
1505
|
+
const bucket = {};
|
|
1506
|
+
for (const key of FIELDS) if (source[key] !== void 0) bucket[key] = source[key];
|
|
1507
|
+
return bucket;
|
|
1508
|
+
}
|
|
1509
|
+
var sameBucket = (a, b) => FIELDS.every((key) => a[key] === b[key]);
|
|
1510
|
+
function persistRequestMetrics(metrics, collection, options = {}) {
|
|
1511
|
+
const written = /* @__PURE__ */ new Map();
|
|
1512
|
+
const ready = (async () => {
|
|
1513
|
+
const rows = (await collection.find().exec()).map((doc) => toBucket(doc.toJSON()));
|
|
1514
|
+
for (const row of rows) written.set(row.hourStartMs, row);
|
|
1515
|
+
metrics.hydrate(rows);
|
|
1516
|
+
})();
|
|
1517
|
+
ready.catch(() => void 0);
|
|
1518
|
+
const write = async () => {
|
|
1519
|
+
await ready;
|
|
1520
|
+
const buckets = metrics.buckets();
|
|
1521
|
+
const changed = buckets.filter((bucket) => {
|
|
1522
|
+
const last = written.get(bucket.hourStartMs);
|
|
1523
|
+
return !last || !sameBucket(last, bucket);
|
|
1524
|
+
});
|
|
1525
|
+
if (changed.length > 0) {
|
|
1526
|
+
const docs = changed.map((bucket) => ({ hour: String(bucket.hourStartMs), ...toBucket(bucket) }));
|
|
1527
|
+
const result = await collection.bulkUpsert(docs);
|
|
1528
|
+
for (const doc of result.success) written.set(doc.hourStartMs, toBucket(doc.toJSON()));
|
|
1529
|
+
if (result.error.length > 0) throw new Error(`request metrics: ${result.error.length} hour(s) not written`);
|
|
1530
|
+
}
|
|
1531
|
+
if (buckets.length < REQUEST_METRICS_MAX_BUCKETS) return;
|
|
1532
|
+
const oldest = buckets[0].hourStartMs;
|
|
1533
|
+
await collection.find({ selector: { hourStartMs: { $lt: oldest } } }).remove();
|
|
1534
|
+
for (const hour of written.keys()) if (hour < oldest) written.delete(hour);
|
|
1535
|
+
};
|
|
1536
|
+
let tail = Promise.resolve();
|
|
1537
|
+
const enqueue = () => {
|
|
1538
|
+
const run = tail.then(write);
|
|
1539
|
+
tail = run.catch(() => void 0);
|
|
1540
|
+
return run;
|
|
1541
|
+
};
|
|
1542
|
+
let stopping;
|
|
1543
|
+
const timer2 = setInterval(
|
|
1544
|
+
() => void enqueue().catch(() => void 0),
|
|
1545
|
+
options.everyMs ?? REQUEST_METRICS_PERSIST_INTERVAL_MS
|
|
1546
|
+
);
|
|
1547
|
+
return {
|
|
1548
|
+
ready,
|
|
1549
|
+
flush: () => stopping ? Promise.resolve() : enqueue(),
|
|
1550
|
+
stop() {
|
|
1551
|
+
stopping ??= (() => {
|
|
1552
|
+
clearInterval(timer2);
|
|
1553
|
+
return enqueue();
|
|
1554
|
+
})();
|
|
1555
|
+
return stopping;
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1187
1559
|
export {
|
|
1188
1560
|
CATALOGUE_OFFLINE_GAP_MS,
|
|
1561
|
+
DEFAULT_SYNC_CADENCE_PRESET,
|
|
1189
1562
|
FAILURE_CONFIRMATION_MS,
|
|
1190
1563
|
FAILURE_CONFIRMATION_TOLERANCE_MS,
|
|
1191
1564
|
INITIAL_CONNECTIVITY,
|
|
1565
|
+
REQUEST_METRICS_COLLECTION,
|
|
1566
|
+
REQUEST_METRICS_HOUR_MS,
|
|
1567
|
+
REQUEST_METRICS_MAX_BUCKETS,
|
|
1568
|
+
REQUEST_METRICS_PERSIST_INTERVAL_MS,
|
|
1192
1569
|
REQUIRED_MULTI_INSTANCE_BY_ENGINE,
|
|
1193
1570
|
STOCK_LEVELS_COLLECTION,
|
|
1194
1571
|
STOCK_LEVELS_LAST_PASS,
|
|
1195
1572
|
STORAGE_READ_WATCHDOG_MS,
|
|
1196
1573
|
STORAGE_WRITE_STALL_MS,
|
|
1574
|
+
SYNC_CADENCE_COLLECTION,
|
|
1575
|
+
SYNC_CADENCE_DOC_ID,
|
|
1576
|
+
SYNC_CADENCE_LIMITS,
|
|
1577
|
+
SYNC_CADENCE_PRESETS,
|
|
1197
1578
|
WEB_STORAGE_ENGINE,
|
|
1579
|
+
addRequestMetricsCollection,
|
|
1580
|
+
addSyncCadenceCollection,
|
|
1581
|
+
clampSyncCadence,
|
|
1198
1582
|
connectorCollection,
|
|
1199
1583
|
createConnectivityTracker,
|
|
1584
|
+
createRequestMetrics,
|
|
1200
1585
|
createTallyDatabase,
|
|
1201
1586
|
getStorage,
|
|
1202
1587
|
getStorageHealth,
|
|
1203
1588
|
isFingerprintResultCurrent,
|
|
1589
|
+
isRequestMetricsBucket,
|
|
1204
1590
|
isStorageWorkerFailure,
|
|
1591
|
+
isSyncCadencePreset,
|
|
1592
|
+
jitteredIntervalMs,
|
|
1593
|
+
meteredFetch,
|
|
1594
|
+
persistRequestMetrics,
|
|
1595
|
+
readSyncCadence,
|
|
1205
1596
|
reduceConnectivity,
|
|
1597
|
+
requestMetricsCollection,
|
|
1598
|
+
requestMetricsSchema,
|
|
1599
|
+
requestsPerHour,
|
|
1600
|
+
resetSyncCadence,
|
|
1601
|
+
setSyncCadence,
|
|
1206
1602
|
shouldReconcileAfterGap,
|
|
1207
1603
|
startCatalogueReconcile,
|
|
1208
1604
|
startFingerprintReconcile,
|
|
@@ -1210,7 +1606,13 @@ export {
|
|
|
1210
1606
|
startLiveTab,
|
|
1211
1607
|
startReplication,
|
|
1212
1608
|
startStockReconcile,
|
|
1609
|
+
startSyncCadence,
|
|
1213
1610
|
stockLevelsCollection,
|
|
1214
1611
|
stockLevelsSchema,
|
|
1612
|
+
syncCadence$,
|
|
1613
|
+
syncCadenceCollection,
|
|
1614
|
+
syncCadencePresetBudget,
|
|
1615
|
+
syncCadencePresetFor,
|
|
1616
|
+
syncCadenceSchema,
|
|
1215
1617
|
withStorageWatchdog
|
|
1216
1618
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/database",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.19.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.19.0"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
36
|
"build": "tsup",
|
package/src/index.ts
CHANGED
|
@@ -31,3 +31,24 @@ export { startFingerprintReconcile, isFingerprintResultCurrent } from './fingerp
|
|
|
31
31
|
export type { StartFingerprintReconcileOptions, FingerprintReconcileResult, FingerprintReconcileState } from './fingerprint-reconcile';
|
|
32
32
|
export { STOCK_LEVELS_COLLECTION, STOCK_LEVELS_LAST_PASS, stockLevelsCollection, stockLevelsSchema } from './stock-levels';
|
|
33
33
|
export type { StockLevelRow } from './stock-levels';
|
|
34
|
+
export {
|
|
35
|
+
SYNC_CADENCE_PRESETS, DEFAULT_SYNC_CADENCE_PRESET, SYNC_CADENCE_LIMITS, isSyncCadencePreset, clampSyncCadence,
|
|
36
|
+
syncCadencePresetFor, syncCadencePresetBudget, requestsPerHour,
|
|
37
|
+
} from './sync-cadence';
|
|
38
|
+
export type { SyncCadence, SyncCadencePreset, SyncCadenceChoice } from './sync-cadence';
|
|
39
|
+
export {
|
|
40
|
+
SYNC_CADENCE_COLLECTION, SYNC_CADENCE_DOC_ID, syncCadenceSchema, syncCadenceCollection, addSyncCadenceCollection,
|
|
41
|
+
readSyncCadence, syncCadence$, setSyncCadence, resetSyncCadence,
|
|
42
|
+
} from './sync-cadence-store';
|
|
43
|
+
export type { SyncCadenceDoc, SyncCadenceCollection, SyncCadenceProfile } from './sync-cadence-store';
|
|
44
|
+
export { startSyncCadence, jitteredIntervalMs } from './sync-cadence-runner';
|
|
45
|
+
export type { SyncCadenceTarget, StartSyncCadenceOptions, SyncCadenceRunner } from './sync-cadence-runner';
|
|
46
|
+
export {
|
|
47
|
+
REQUEST_METRICS_HOUR_MS, REQUEST_METRICS_MAX_BUCKETS, createRequestMetrics, isRequestMetricsBucket, meteredFetch,
|
|
48
|
+
} from './request-metrics';
|
|
49
|
+
export type { RequestMetricsBucket, RequestAttempt, RequestMetrics, MeteredFetchOptions } from './request-metrics';
|
|
50
|
+
export {
|
|
51
|
+
REQUEST_METRICS_COLLECTION, REQUEST_METRICS_PERSIST_INTERVAL_MS, requestMetricsSchema, requestMetricsCollection,
|
|
52
|
+
addRequestMetricsCollection, persistRequestMetrics,
|
|
53
|
+
} from './request-metrics-store';
|
|
54
|
+
export type { RequestMetricsDoc, RequestMetricsCollection, RequestMetricsPersistence } from './request-metrics-store';
|
package/src/replication.ts
CHANGED
|
@@ -68,6 +68,11 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
|
68
68
|
* pull asks the store again and a held push goes. `resume()` keeps the latch, and the reset keeps a sign-in hold.
|
|
69
69
|
*/
|
|
70
70
|
connectivity?: ConnectivityTracker;
|
|
71
|
+
/**
|
|
72
|
+
* The pull page size, overriding adapter.pull.batchSize (for example the sync cadence profile's pullBatchSize).
|
|
73
|
+
* RxDB fixes it when the replication starts.
|
|
74
|
+
*/
|
|
75
|
+
pullBatchSize?: number;
|
|
71
76
|
}
|
|
72
77
|
|
|
73
78
|
/** RxDB's replication state plus the pull notice and a way to restart after a till error. */
|
|
@@ -134,6 +139,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
134
139
|
autoStart = true,
|
|
135
140
|
maxRetryTimeMs = MAX_RETRY_TIME_MS,
|
|
136
141
|
connectivity,
|
|
142
|
+
pullBatchSize,
|
|
137
143
|
}: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
|
|
138
144
|
// Pull errors fall in three classes by who can fix them (errorKind):
|
|
139
145
|
// - till (sign in again): one notice and an empty page (RxDB stores no
|
|
@@ -212,7 +218,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
212
218
|
pull: {
|
|
213
219
|
handler: pullHandler,
|
|
214
220
|
stream$: adapter.pull.stream$?.pipe(filter(event => event === 'RESYNC' || !tillHeld$.getValue())),
|
|
215
|
-
batchSize: adapter.pull.batchSize,
|
|
221
|
+
batchSize: pullBatchSize ?? adapter.pull.batchSize,
|
|
216
222
|
},
|
|
217
223
|
push: adapter.push
|
|
218
224
|
? {
|