@tallyui/database 3.20.1 → 4.0.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 CHANGED
@@ -131,9 +131,31 @@ declare function getStorage(): RxStorage<any, any>;
131
131
  declare const WEB_STORAGE_ENGINE: "sqlite-sahpool";
132
132
  /** multiInstance each web engine requires: opfs-sahpool holds exclusive OPFS handles, so a second instance cannot exist. */
133
133
  declare const REQUIRED_MULTI_INSTANCE_BY_ENGINE: {
134
- readonly 'sqlite-sahpool': false;
134
+ readonly "sqlite-sahpool": false;
135
135
  };
136
136
 
137
+ interface CollectionSize {
138
+ docs: number;
139
+ bytes: number;
140
+ }
141
+ interface MeasureCollectionOptions {
142
+ pageSize?: number;
143
+ signal?: AbortSignal;
144
+ }
145
+ /**
146
+ * Counts a collection's live documents and sums their data size in bytes.
147
+ *
148
+ * The size is the logical data size: each document's UTF-8 JSON without RxDB's metadata, not the
149
+ * bytes on disk (no indexes, pages or WAL). Deleted documents are not counted.
150
+ *
151
+ * It reads every live document, a page at a time, so run it on demand, never on mount or in a hot
152
+ * path. `signal` cancels it between pages.
153
+ *
154
+ * The pages are not one snapshot: a document written or removed while the walk runs may be missed
155
+ * or counted, so under concurrent writes the totals are approximate.
156
+ */
157
+ declare function measureCollectionBytes<T>(collection: RxCollection<T>, options?: MeasureCollectionOptions): Promise<CollectionSize>;
158
+
137
159
  /**
138
160
  * How long requests must keep failing, with no success, before the verdict leaves `online`: v2's
139
161
  * `WEBSITE_UNAVAILABLE_CONFIRMATION_MS` (`packages/hooks/src/website-unavailable-confirmation.ts`). One 502 or one
@@ -213,6 +235,8 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
213
235
  * RxDB fixes it when the replication starts.
214
236
  */
215
237
  pullBatchSize?: number;
238
+ /** The reset generation (`resetCollection`); default 0. From 1 the identifier ends `-g${generation}`, a fresh checkpoint. Read it with `replicationGeneration(collection)` before every start of a collection that was ever reset. */
239
+ generation?: number;
216
240
  }
217
241
  /** RxDB's replication state plus the pull notice and a way to restart after a till error. */
218
242
  type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
@@ -227,7 +251,24 @@ type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState
227
251
  * Returns the RxReplicationState which exposes observables for monitoring
228
252
  * and methods like cancel(), awaitInSync(), reSync().
229
253
  */
230
- declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, connectivity, pullBatchSize, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
254
+ declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, connectivity, pullBatchSize, generation, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
255
+
256
+ /** The local document (on the collection itself) that holds its reset generation. */
257
+ declare const REPLICATION_GENERATION_DOC = "tally-replication-generation";
258
+ /** The collection's reset generation: 0 when it was never reset. Throws when the collection has no local documents. */
259
+ declare function replicationGeneration<RxDocType>(collection: RxCollection<RxDocType>): Promise<number>;
260
+ interface ResetCollectionOptions<RxDocType, CheckpointType = unknown> extends StartReplicationOptions<RxDocType, CheckpointType> {
261
+ /** The running replication `startReplication` returned for these options. */
262
+ state: TallyReplicationState<RxDocType, CheckpointType>;
263
+ /** Local documents to remove with the data: the catalogue reconcile state. Default `['catalogue-reconcile']`. */
264
+ reconcileStateIds?: string[];
265
+ }
266
+ /**
267
+ * Clears the collection and downloads it again from the start, under the next generation. It returns the new
268
+ * replication. Stop the collection's catalogue runner first and start it again afterwards. It refuses a collection
269
+ * whose adapter pushes, since local writes would be lost.
270
+ */
271
+ declare function resetCollection<RxDocType, CheckpointType = unknown>(options: ResetCollectionOptions<RxDocType, CheckpointType>): Promise<TallyReplicationState<RxDocType, CheckpointType>>;
231
272
 
232
273
  /**
233
274
  * ADR-061: exactly one live tab per store, and a second tab never opens
@@ -665,7 +706,8 @@ declare function resetSyncCadence(collection: SyncCadenceCollection, options?: {
665
706
 
666
707
  /** What a tick asks to check again. RxDB's replication state (and TallyReplicationState) fits as is. */
667
708
  interface SyncCadenceTarget {
668
- reSync(): void;
709
+ /** A returned promise that rejects counts the tick as an error. */
710
+ reSync(): void | PromiseLike<unknown>;
669
711
  isPaused?(): boolean;
670
712
  }
671
713
  interface StartSyncCadenceOptions {
@@ -675,9 +717,14 @@ interface StartSyncCadenceOptions {
675
717
  connectivity?: ConnectivityTracker;
676
718
  /** Injectable for tests; default Math.random. */
677
719
  random?: () => number;
678
- /** Injectable for tests; default Date.now. Only used for nextDueAtMs$. */
720
+ /** Injectable for tests; default Date.now. Only used for nextDueAtMs$ and lastTick. */
679
721
  now?: () => number;
680
722
  }
723
+ /** One finished tick: when it finished (the `now()` clock) and whether every target's reSync went through. v2's lane `lastTick`. */
724
+ interface SyncCadenceTick {
725
+ atMs: number;
726
+ status: 'ok' | 'error';
727
+ }
681
728
  interface SyncCadenceRunner {
682
729
  /** When the next tick is due (the `now()` clock), or undefined before the first cadence value and after stop. */
683
730
  readonly nextDueAtMs$: Observable<number | undefined>;
@@ -686,14 +733,22 @@ interface SyncCadenceRunner {
686
733
  /** Clears the timer, unsubscribes from cadence$, and emits undefined then completes nextDueAtMs$. Idempotent. */
687
734
  stop(): void;
688
735
  }
736
+ interface SyncCadenceTicker extends SyncCadenceRunner {
737
+ /** The last finished tick on subscribe, then each new one; null before the first. Completes on stop. */
738
+ readonly lastTick$: Observable<SyncCadenceTick | null>;
739
+ /** The last finished tick, or null before the first. Still readable after stop. */
740
+ lastTick(): SyncCadenceTick | null;
741
+ }
689
742
  /** v2's ±20 % jitter (sync-engine change-signal/tick-cadence.ts). Exported for tests and for a "next check in" line. */
690
743
  declare function jitteredIntervalMs(intervalMs: number, random: () => number): number;
691
744
  /**
692
745
  * Opt-in polling beside startReplication: on each jittered tick, `reSync()` on every target that is not paused. A new
693
746
  * cadence value re-arms the timer from now, as v2's reconfigure does. A tick is skipped while connectivity's
694
747
  * update-required latch is set, never for offline or degraded: the replication's own backoff and holds decide those.
748
+ * The last finished tick is on `lastTick$`/`lastTick()`; a target may return a promise from `reSync()`, and a rejection
749
+ * counts as an error.
695
750
  */
696
- declare function startSyncCadence({ targets, cadence$, connectivity, random, now, }: StartSyncCadenceOptions): SyncCadenceRunner;
751
+ declare function startSyncCadence({ targets, cadence$, connectivity, random, now, }: StartSyncCadenceOptions): SyncCadenceTicker;
697
752
 
698
753
  declare const REQUEST_METRICS_HOUR_MS = 3600000;
699
754
  /** Hourly buckets kept: the newest 48 that exist, by count not age (an idle hour makes no bucket). v2 metrics.ts:4. */
@@ -772,4 +827,4 @@ declare function persistRequestMetrics(metrics: RequestMetrics, collection: Requ
772
827
  everyMs?: number;
773
828
  }): RequestMetricsPersistence;
774
829
 
775
- export { CATALOGUE_OFFLINE_GAP_MS, type CatalogueReconcileEvent, type CatalogueReconcileState, type CatalogueReconcileSummary, type ConnectivityEvent, type ConnectivitySnapshot, type ConnectivityTracker, type CreateDatabaseOptions, DEFAULT_SYNC_CADENCE_PRESET, FAILURE_CONFIRMATION_MS, FAILURE_CONFIRMATION_TOLERANCE_MS, type FingerprintReconcileResult, type FingerprintReconcileState, INITIAL_CONNECTIVITY, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, type MeteredFetchOptions, REQUEST_METRICS_COLLECTION, REQUEST_METRICS_HOUR_MS, REQUEST_METRICS_MAX_BUCKETS, REQUEST_METRICS_PERSIST_INTERVAL_MS, REQUIRED_MULTI_INSTANCE_BY_ENGINE, type RequestAttempt, type RequestMetrics, type RequestMetricsBucket, type RequestMetricsCollection, type RequestMetricsDoc, type RequestMetricsPersistence, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, SYNC_CADENCE_COLLECTION, SYNC_CADENCE_DOC_ID, SYNC_CADENCE_LIMITS, SYNC_CADENCE_PRESETS, type StartCatalogueReconcileOptions, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StartSyncCadenceOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type SyncCadence, type SyncCadenceChoice, type SyncCadenceCollection, type SyncCadenceDoc, type SyncCadencePreset, type SyncCadenceProfile, type SyncCadenceRunner, type SyncCadenceTarget, type TallyDatabase, type TallyReplicationState, WEB_STORAGE_ENGINE, addRequestMetricsCollection, addSyncCadenceCollection, clampSyncCadence, connectorCollection, createConnectivityTracker, createRequestMetrics, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isRequestMetricsBucket, isStorageWorkerFailure, isSyncCadencePreset, jitteredIntervalMs, meteredFetch, persistRequestMetrics, readSyncCadence, reduceConnectivity, requestMetricsCollection, requestMetricsSchema, requestsPerHour, resetSyncCadence, setSyncCadence, shouldReconcileAfterGap, startCatalogueReconcile, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, startSyncCadence, stockLevelsCollection, stockLevelsSchema, syncCadence$, syncCadenceCollection, syncCadencePresetBudget, syncCadencePresetFor, syncCadenceSchema, withStorageWatchdog };
830
+ export { CATALOGUE_OFFLINE_GAP_MS, type CatalogueReconcileEvent, type CatalogueReconcileState, type CatalogueReconcileSummary, type CollectionSize, type ConnectivityEvent, type ConnectivitySnapshot, type ConnectivityTracker, type CreateDatabaseOptions, DEFAULT_SYNC_CADENCE_PRESET, FAILURE_CONFIRMATION_MS, FAILURE_CONFIRMATION_TOLERANCE_MS, type FingerprintReconcileResult, type FingerprintReconcileState, INITIAL_CONNECTIVITY, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, type MeasureCollectionOptions, type MeteredFetchOptions, REPLICATION_GENERATION_DOC, REQUEST_METRICS_COLLECTION, REQUEST_METRICS_HOUR_MS, REQUEST_METRICS_MAX_BUCKETS, REQUEST_METRICS_PERSIST_INTERVAL_MS, REQUIRED_MULTI_INSTANCE_BY_ENGINE, type RequestAttempt, type RequestMetrics, type RequestMetricsBucket, type RequestMetricsCollection, type RequestMetricsDoc, type RequestMetricsPersistence, type ResetCollectionOptions, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, SYNC_CADENCE_COLLECTION, SYNC_CADENCE_DOC_ID, SYNC_CADENCE_LIMITS, SYNC_CADENCE_PRESETS, type StartCatalogueReconcileOptions, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StartSyncCadenceOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type SyncCadence, type SyncCadenceChoice, type SyncCadenceCollection, type SyncCadenceDoc, type SyncCadencePreset, type SyncCadenceProfile, type SyncCadenceRunner, type SyncCadenceTarget, type SyncCadenceTick, type SyncCadenceTicker, type TallyDatabase, type TallyReplicationState, WEB_STORAGE_ENGINE, addRequestMetricsCollection, addSyncCadenceCollection, clampSyncCadence, connectorCollection, createConnectivityTracker, createRequestMetrics, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isRequestMetricsBucket, isStorageWorkerFailure, isSyncCadencePreset, jitteredIntervalMs, measureCollectionBytes, meteredFetch, persistRequestMetrics, readSyncCadence, reduceConnectivity, replicationGeneration, requestMetricsCollection, requestMetricsSchema, requestsPerHour, resetCollection, resetSyncCadence, setSyncCadence, shouldReconcileAfterGap, startCatalogueReconcile, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, startSyncCadence, stockLevelsCollection, stockLevelsSchema, syncCadence$, syncCadenceCollection, syncCadencePresetBudget, syncCadencePresetFor, syncCadenceSchema, withStorageWatchdog };
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@ var stockLevelsCollection = { schema: stockLevelsSchema, localDocuments: true };
35
35
 
36
36
  // src/engine.ts
37
37
  var WEB_STORAGE_ENGINE = "sqlite-sahpool";
38
- var REQUIRED_MULTI_INSTANCE_BY_ENGINE = { "sqlite-sahpool": false };
38
+ var REQUIRED_MULTI_INSTANCE_BY_ENGINE = { [WEB_STORAGE_ENGINE]: false };
39
39
 
40
40
  // src/storage-watchdog.ts
41
41
  import { BehaviorSubject } from "rxjs";
@@ -187,6 +187,33 @@ function getStorage() {
187
187
  );
188
188
  }
189
189
 
190
+ // src/collection-size.ts
191
+ var MEASURE_PAGE_SIZE = 500;
192
+ async function measureCollectionBytes(collection, options = {}) {
193
+ const pageSize = options.pageSize ?? MEASURE_PAGE_SIZE;
194
+ if (!Number.isInteger(pageSize) || pageSize < 1) throw new RangeError(`pageSize must be an integer of at least 1, got ${pageSize}`);
195
+ const primary = collection.schema.primaryPath;
196
+ const encoder = new TextEncoder();
197
+ const size = { docs: 0, bytes: 0 };
198
+ let last;
199
+ for (; ; ) {
200
+ options.signal?.throwIfAborted();
201
+ const query = {
202
+ selector: last === void 0 ? {} : { [primary]: { $gt: last } },
203
+ sort: [{ [primary]: "asc" }],
204
+ limit: pageSize
205
+ };
206
+ const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
207
+ for (const document of documents) {
208
+ const { _meta, _rev, _attachments, _deleted, ...data } = document;
209
+ size.docs += 1;
210
+ size.bytes += encoder.encode(JSON.stringify(data)).byteLength;
211
+ }
212
+ if (documents.length < pageSize) return size;
213
+ last = documents[documents.length - 1][primary];
214
+ }
215
+ }
216
+
190
217
  // src/replication.ts
191
218
  import { replicateRxCollection } from "rxdb/plugins/replication";
192
219
  import { errorToPlainJson, newRxError, toArray } from "rxdb";
@@ -258,7 +285,8 @@ function startReplication({
258
285
  autoStart = true,
259
286
  maxRetryTimeMs = MAX_RETRY_TIME_MS,
260
287
  connectivity,
261
- pullBatchSize
288
+ pullBatchSize,
289
+ generation = 0
262
290
  }) {
263
291
  let state;
264
292
  const notice$ = new BehaviorSubject2(void 0);
@@ -311,7 +339,7 @@ function startReplication({
311
339
  const { version } = collection.schema;
312
340
  const replication = replicateRxCollection({
313
341
  collection,
314
- replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}`,
342
+ replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}${generation > 0 ? `-g${generation}` : ""}`,
315
343
  pull: {
316
344
  handler: pullHandler,
317
345
  stream$: adapter.pull.stream$?.pipe(filter((event) => event === "RESYNC" || !tillHeld$.getValue())),
@@ -374,6 +402,29 @@ function startReplication({
374
402
  return Object.assign(replication, { notice$: notice$.asObservable(), resume });
375
403
  }
376
404
 
405
+ // src/reset-collection.ts
406
+ var REPLICATION_GENERATION_DOC = "tally-replication-generation";
407
+ async function replicationGeneration(collection) {
408
+ try {
409
+ const doc = await collection.getLocal(REPLICATION_GENERATION_DOC);
410
+ return doc ? doc.get("generation") : 0;
411
+ } catch (error) {
412
+ if (typeof collection.getLocal === "function" && error?.code !== "LD8") throw error;
413
+ throw new Error(`${collection.name} has no local documents; create it with connectorCollection`);
414
+ }
415
+ }
416
+ async function resetCollection(options) {
417
+ const { state, reconcileStateIds = ["catalogue-reconcile"], ...rest } = options;
418
+ const { collection } = rest;
419
+ if (rest.adapter.push) throw new Error(`resetCollection: ${collection.name} pushes local writes; a reset would lose them`);
420
+ const n = await replicationGeneration(collection);
421
+ await state.cancel();
422
+ await collection.upsertLocal(REPLICATION_GENERATION_DOC, { generation: n + 1 });
423
+ for (const id of reconcileStateIds) await (await collection.getLocal(id))?.remove();
424
+ await collection.find().remove();
425
+ return startReplication({ ...rest, generation: n + 1 });
426
+ }
427
+
377
428
  // src/connectivity.ts
378
429
  import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
379
430
  import { classifyFailure } from "@tallyui/core";
@@ -1297,6 +1348,7 @@ import { BehaviorSubject as BehaviorSubject8 } from "rxjs";
1297
1348
  function jitteredIntervalMs(intervalMs, random) {
1298
1349
  return Math.round(intervalMs * (0.8 + 0.4 * random()));
1299
1350
  }
1351
+ var isThenable = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
1300
1352
  function startSyncCadence({
1301
1353
  targets,
1302
1354
  cadence$,
@@ -1305,17 +1357,34 @@ function startSyncCadence({
1305
1357
  now = Date.now
1306
1358
  }) {
1307
1359
  const nextDueAtMs$ = new BehaviorSubject8(void 0);
1360
+ const lastTick$ = new BehaviorSubject8(null);
1361
+ let tickSeq = 0;
1362
+ let recordedSeq = 0;
1308
1363
  let current;
1309
1364
  let timer2;
1310
1365
  let stopped = false;
1311
1366
  const tick = () => {
1312
1367
  if (connectivity?.current().updateRequired) return;
1368
+ const seq = ++tickSeq;
1369
+ let failed = false;
1370
+ const pending = [];
1313
1371
  for (const target of targets) {
1314
1372
  try {
1315
- if (target.isPaused?.() !== true) target.reSync();
1373
+ if (target.isPaused?.() !== true) {
1374
+ const result = target.reSync();
1375
+ if (isThenable(result)) pending.push(result);
1376
+ }
1316
1377
  } catch {
1378
+ failed = true;
1317
1379
  }
1318
1380
  }
1381
+ const record = (ok) => {
1382
+ if (stopped || seq <= recordedSeq) return;
1383
+ recordedSeq = seq;
1384
+ lastTick$.next({ atMs: now(), status: ok ? "ok" : "error" });
1385
+ };
1386
+ if (pending.length === 0) record(!failed);
1387
+ else void Promise.allSettled(pending).then((results) => record(!failed && results.every((r) => r.status === "fulfilled")));
1319
1388
  };
1320
1389
  const arm = () => {
1321
1390
  if (timer2 !== void 0) clearTimeout(timer2);
@@ -1337,6 +1406,8 @@ function startSyncCadence({
1337
1406
  });
1338
1407
  return {
1339
1408
  nextDueAtMs$: nextDueAtMs$.asObservable(),
1409
+ lastTick$: lastTick$.asObservable(),
1410
+ lastTick: () => lastTick$.getValue(),
1340
1411
  tickNow: () => {
1341
1412
  if (stopped) return;
1342
1413
  tick();
@@ -1350,6 +1421,7 @@ function startSyncCadence({
1350
1421
  subscription.unsubscribe();
1351
1422
  nextDueAtMs$.next(void 0);
1352
1423
  nextDueAtMs$.complete();
1424
+ lastTick$.complete();
1353
1425
  }
1354
1426
  };
1355
1427
  }
@@ -1562,6 +1634,7 @@ export {
1562
1634
  FAILURE_CONFIRMATION_MS,
1563
1635
  FAILURE_CONFIRMATION_TOLERANCE_MS,
1564
1636
  INITIAL_CONNECTIVITY,
1637
+ REPLICATION_GENERATION_DOC,
1565
1638
  REQUEST_METRICS_COLLECTION,
1566
1639
  REQUEST_METRICS_HOUR_MS,
1567
1640
  REQUEST_METRICS_MAX_BUCKETS,
@@ -1590,13 +1663,16 @@ export {
1590
1663
  isStorageWorkerFailure,
1591
1664
  isSyncCadencePreset,
1592
1665
  jitteredIntervalMs,
1666
+ measureCollectionBytes,
1593
1667
  meteredFetch,
1594
1668
  persistRequestMetrics,
1595
1669
  readSyncCadence,
1596
1670
  reduceConnectivity,
1671
+ replicationGeneration,
1597
1672
  requestMetricsCollection,
1598
1673
  requestMetricsSchema,
1599
1674
  requestsPerHour,
1675
+ resetCollection,
1600
1676
  resetSyncCadence,
1601
1677
  setSyncCadence,
1602
1678
  shouldReconcileAfterGap,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/database",
3
- "version": "3.20.1",
3
+ "version": "4.0.1",
4
4
  "type": "module",
5
5
  "description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
6
6
  "main": "./dist/index.js",
@@ -30,11 +30,10 @@
30
30
  "rxjs": "7.8.2"
31
31
  },
32
32
  "peerDependencies": {
33
- "@tallyui/core": "^3.20.1"
33
+ "@tallyui/core": "^4.0.1"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "tsup",
37
- "typecheck": "tsc --noEmit",
38
- "test": "echo \"no tests yet\""
37
+ "typecheck": "tsc --noEmit"
39
38
  }
40
39
  }
@@ -0,0 +1,47 @@
1
+ import type { MangoQuery, RxCollection } from 'rxdb';
2
+
3
+ /** Memory holds at most one page of documents. */
4
+ const MEASURE_PAGE_SIZE = 500;
5
+
6
+ export interface CollectionSize { docs: number; bytes: number }
7
+ export interface MeasureCollectionOptions { pageSize?: number; signal?: AbortSignal }
8
+
9
+ /**
10
+ * Counts a collection's live documents and sums their data size in bytes.
11
+ *
12
+ * The size is the logical data size: each document's UTF-8 JSON without RxDB's metadata, not the
13
+ * bytes on disk (no indexes, pages or WAL). Deleted documents are not counted.
14
+ *
15
+ * It reads every live document, a page at a time, so run it on demand, never on mount or in a hot
16
+ * path. `signal` cancels it between pages.
17
+ *
18
+ * The pages are not one snapshot: a document written or removed while the walk runs may be missed
19
+ * or counted, so under concurrent writes the totals are approximate.
20
+ */
21
+ export async function measureCollectionBytes<T>(
22
+ collection: RxCollection<T>,
23
+ options: MeasureCollectionOptions = {},
24
+ ): Promise<CollectionSize> {
25
+ const pageSize = options.pageSize ?? MEASURE_PAGE_SIZE;
26
+ if (!Number.isInteger(pageSize) || pageSize < 1) throw new RangeError(`pageSize must be an integer of at least 1, got ${pageSize}`);
27
+ const primary = collection.schema.primaryPath as string;
28
+ const encoder = new TextEncoder();
29
+ const size: CollectionSize = { docs: 0, bytes: 0 };
30
+ let last: unknown;
31
+ for (;;) {
32
+ options.signal?.throwIfAborted();
33
+ const query = {
34
+ selector: last === undefined ? {} : { [primary]: { $gt: last } },
35
+ sort: [{ [primary]: 'asc' }],
36
+ limit: pageSize,
37
+ } as MangoQuery<T>;
38
+ const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
39
+ for (const document of documents) {
40
+ const { _meta, _rev, _attachments, _deleted, ...data } = document;
41
+ size.docs += 1;
42
+ size.bytes += encoder.encode(JSON.stringify(data)).byteLength;
43
+ }
44
+ if (documents.length < pageSize) return size;
45
+ last = (documents[documents.length - 1] as Record<string, unknown>)[primary];
46
+ }
47
+ }
package/src/engine.ts CHANGED
@@ -2,4 +2,4 @@
2
2
  export const WEB_STORAGE_ENGINE = 'sqlite-sahpool' as const;
3
3
 
4
4
  /** multiInstance each web engine requires: opfs-sahpool holds exclusive OPFS handles, so a second instance cannot exist. */
5
- export const REQUIRED_MULTI_INSTANCE_BY_ENGINE = { 'sqlite-sahpool': false } as const;
5
+ export const REQUIRED_MULTI_INSTANCE_BY_ENGINE = { [WEB_STORAGE_ENGINE]: false } as const;
package/src/index.ts CHANGED
@@ -7,9 +7,13 @@ export { getStorage } from './storage';
7
7
  export { WEB_STORAGE_ENGINE, REQUIRED_MULTI_INSTANCE_BY_ENGINE } from './engine';
8
8
  export { STORAGE_WRITE_STALL_MS, STORAGE_READ_WATCHDOG_MS, isStorageWorkerFailure, withStorageWatchdog } from './storage-watchdog';
9
9
  export type { StorageHealth, StorageWatchdogOptions } from './storage-watchdog';
10
+ export { measureCollectionBytes } from './collection-size';
11
+ export type { CollectionSize, MeasureCollectionOptions } from './collection-size';
10
12
 
11
13
  export { startReplication } from './replication';
12
14
  export type { StartReplicationOptions, TallyReplicationState } from './replication';
15
+ export { resetCollection, replicationGeneration, REPLICATION_GENERATION_DOC } from './reset-collection';
16
+ export type { ResetCollectionOptions } from './reset-collection';
13
17
 
14
18
  export {
15
19
  createConnectivityTracker, reduceConnectivity, INITIAL_CONNECTIVITY, FAILURE_CONFIRMATION_MS, FAILURE_CONFIRMATION_TOLERANCE_MS,
@@ -42,7 +46,7 @@ export {
42
46
  } from './sync-cadence-store';
43
47
  export type { SyncCadenceDoc, SyncCadenceCollection, SyncCadenceProfile } from './sync-cadence-store';
44
48
  export { startSyncCadence, jitteredIntervalMs } from './sync-cadence-runner';
45
- export type { SyncCadenceTarget, StartSyncCadenceOptions, SyncCadenceRunner } from './sync-cadence-runner';
49
+ export type { SyncCadenceTarget, StartSyncCadenceOptions, SyncCadenceRunner, SyncCadenceTicker, SyncCadenceTick } from './sync-cadence-runner';
46
50
  export {
47
51
  REQUEST_METRICS_HOUR_MS, REQUEST_METRICS_MAX_BUCKETS, createRequestMetrics, isRequestMetricsBucket, meteredFetch,
48
52
  } from './request-metrics';
@@ -73,6 +73,8 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
73
73
  * RxDB fixes it when the replication starts.
74
74
  */
75
75
  pullBatchSize?: number;
76
+ /** The reset generation (`resetCollection`); default 0. From 1 the identifier ends `-g${generation}`, a fresh checkpoint. Read it with `replicationGeneration(collection)` before every start of a collection that was ever reset. */
77
+ generation?: number;
76
78
  }
77
79
 
78
80
  /** RxDB's replication state plus the pull notice and a way to restart after a till error. */
@@ -140,6 +142,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
140
142
  maxRetryTimeMs = MAX_RETRY_TIME_MS,
141
143
  connectivity,
142
144
  pullBatchSize,
145
+ generation = 0,
143
146
  }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
144
147
  // Pull errors fall in three classes by who can fix them (errorKind):
145
148
  // - till (sign in again): one notice and an empty page (RxDB stores no
@@ -210,11 +213,12 @@ export function startReplication<RxDocType, CheckpointType = any>({
210
213
  // A new identifier is a fresh meta instance, so the pull starts from nothing
211
214
  // (and a combined adapter seeds as on a fresh install). The old meta instance
212
215
  // is left orphaned: a few rows, and removing it is out of scope. Version 0
213
- // keeps the original identifier, so existing installs never resync.
216
+ // keeps the original identifier, so existing installs never resync. A reset
217
+ // (resetCollection) appends `-g${generation}` from generation 1 the same way.
214
218
  const { version } = collection.schema;
215
219
  const replication = replicateRxCollection({
216
220
  collection,
217
- replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}`,
221
+ replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}${generation > 0 ? `-g${generation}` : ''}`,
218
222
  pull: {
219
223
  handler: pullHandler,
220
224
  stream$: adapter.pull.stream$?.pipe(filter(event => event === 'RESYNC' || !tillHeld$.getValue())),
@@ -0,0 +1,51 @@
1
+ import type { RxCollection } from 'rxdb';
2
+
3
+ import { startReplication, type StartReplicationOptions, type TallyReplicationState } from './replication';
4
+
5
+ /** The local document (on the collection itself) that holds its reset generation. */
6
+ export const REPLICATION_GENERATION_DOC = 'tally-replication-generation';
7
+
8
+ /** The collection's reset generation: 0 when it was never reset. Throws when the collection has no local documents. */
9
+ export async function replicationGeneration<RxDocType>(collection: RxCollection<RxDocType>): Promise<number> {
10
+ try {
11
+ const doc = await collection.getLocal<{ generation: number }>(REPLICATION_GENERATION_DOC);
12
+ return doc ? doc.get('generation') : 0;
13
+ } catch (error) {
14
+ // LD8: local documents are off; no getLocal at all: the plugin was never added (as catalogue-reconcile.ts tells them apart).
15
+ if (typeof collection.getLocal === 'function' && (error as { code?: unknown } | null)?.code !== 'LD8') throw error;
16
+ throw new Error(`${collection.name} has no local documents; create it with connectorCollection`);
17
+ }
18
+ }
19
+
20
+ export interface ResetCollectionOptions<RxDocType, CheckpointType = unknown> extends StartReplicationOptions<RxDocType, CheckpointType> {
21
+ /** The running replication `startReplication` returned for these options. */
22
+ state: TallyReplicationState<RxDocType, CheckpointType>;
23
+ /** Local documents to remove with the data: the catalogue reconcile state. Default `['catalogue-reconcile']`. */
24
+ reconcileStateIds?: string[];
25
+ }
26
+
27
+ /**
28
+ * Clears the collection and downloads it again from the start, under the next generation. It returns the new
29
+ * replication. Stop the collection's catalogue runner first and start it again afterwards. It refuses a collection
30
+ * whose adapter pushes, since local writes would be lost.
31
+ */
32
+ export async function resetCollection<RxDocType, CheckpointType = unknown>(
33
+ options: ResetCollectionOptions<RxDocType, CheckpointType>,
34
+ ): Promise<TallyReplicationState<RxDocType, CheckpointType>> {
35
+ const { state, reconcileStateIds = ['catalogue-reconcile'], ...rest } = options;
36
+ const { collection } = rest;
37
+ // 1. Push: refuse before anything changes, since a reset would lose unpushed local writes.
38
+ if (rest.adapter.push) throw new Error(`resetCollection: ${collection.name} pushes local writes; a reset would lose them`);
39
+ // 2. Generation: read it (this throws, with nothing changed, when local documents are off).
40
+ const n = await replicationGeneration(collection);
41
+ // 3. Stop the running replication.
42
+ await state.cancel();
43
+ // 4. Persist the next generation before removing anything: a start after a stop between steps pulls from the start.
44
+ await collection.upsertLocal(REPLICATION_GENERATION_DOC, { generation: n + 1 });
45
+ // 5. Reconcile state: remove it, or the first pass after the reset reads the empty collection as everything deleted.
46
+ for (const id of reconcileStateIds) await (await collection.getLocal(id))?.remove();
47
+ // 6. Data: remove every document.
48
+ await collection.find().remove();
49
+ // 7. Restart under the new generation, a fresh checkpoint.
50
+ return startReplication({ ...rest, generation: n + 1 });
51
+ }
@@ -4,7 +4,11 @@ import type { ConnectivityTracker } from './connectivity';
4
4
  import type { SyncCadence } from './sync-cadence';
5
5
 
6
6
  /** What a tick asks to check again. RxDB's replication state (and TallyReplicationState) fits as is. */
7
- export interface SyncCadenceTarget { reSync(): void; isPaused?(): boolean }
7
+ export interface SyncCadenceTarget {
8
+ /** A returned promise that rejects counts the tick as an error. */
9
+ reSync(): void | PromiseLike<unknown>;
10
+ isPaused?(): boolean;
11
+ }
8
12
 
9
13
  export interface StartSyncCadenceOptions {
10
14
  targets: readonly SyncCadenceTarget[];
@@ -13,10 +17,13 @@ export interface StartSyncCadenceOptions {
13
17
  connectivity?: ConnectivityTracker;
14
18
  /** Injectable for tests; default Math.random. */
15
19
  random?: () => number;
16
- /** Injectable for tests; default Date.now. Only used for nextDueAtMs$. */
20
+ /** Injectable for tests; default Date.now. Only used for nextDueAtMs$ and lastTick. */
17
21
  now?: () => number;
18
22
  }
19
23
 
24
+ /** One finished tick: when it finished (the `now()` clock) and whether every target's reSync went through. v2's lane `lastTick`. */
25
+ export interface SyncCadenceTick { atMs: number; status: 'ok' | 'error' }
26
+
20
27
  export interface SyncCadenceRunner {
21
28
  /** When the next tick is due (the `now()` clock), or undefined before the first cadence value and after stop. */
22
29
  readonly nextDueAtMs$: Observable<number | undefined>;
@@ -26,32 +33,61 @@ export interface SyncCadenceRunner {
26
33
  stop(): void;
27
34
  }
28
35
 
36
+ export interface SyncCadenceTicker extends SyncCadenceRunner {
37
+ /** The last finished tick on subscribe, then each new one; null before the first. Completes on stop. */
38
+ readonly lastTick$: Observable<SyncCadenceTick | null>;
39
+ /** The last finished tick, or null before the first. Still readable after stop. */
40
+ lastTick(): SyncCadenceTick | null;
41
+ }
42
+
29
43
  /** v2's ±20 % jitter (sync-engine change-signal/tick-cadence.ts). Exported for tests and for a "next check in" line. */
30
44
  export function jitteredIntervalMs(intervalMs: number, random: () => number): number {
31
45
  return Math.round(intervalMs * (0.8 + 0.4 * random()));
32
46
  }
33
47
 
48
+ const isThenable = (value: unknown): value is PromiseLike<unknown> =>
49
+ (typeof value === 'object' || typeof value === 'function') && value !== null && typeof (value as { then?: unknown }).then === 'function';
50
+
34
51
  /**
35
52
  * Opt-in polling beside startReplication: on each jittered tick, `reSync()` on every target that is not paused. A new
36
53
  * cadence value re-arms the timer from now, as v2's reconfigure does. A tick is skipped while connectivity's
37
54
  * update-required latch is set, never for offline or degraded: the replication's own backoff and holds decide those.
55
+ * The last finished tick is on `lastTick$`/`lastTick()`; a target may return a promise from `reSync()`, and a rejection
56
+ * counts as an error.
38
57
  */
39
58
  export function startSyncCadence({
40
59
  targets, cadence$, connectivity, random = Math.random, now = Date.now,
41
- }: StartSyncCadenceOptions): SyncCadenceRunner {
60
+ }: StartSyncCadenceOptions): SyncCadenceTicker {
42
61
  const nextDueAtMs$ = new BehaviorSubject<number | undefined>(undefined);
62
+ const lastTick$ = new BehaviorSubject<SyncCadenceTick | null>(null);
63
+ let tickSeq = 0;
64
+ let recordedSeq = 0;
43
65
  let current: SyncCadence | undefined;
44
66
  let timer: ReturnType<typeof setTimeout> | undefined;
45
67
  let stopped = false;
46
68
 
47
69
  const tick = () => {
48
70
  if (connectivity?.current().updateRequired) return;
71
+ const seq = ++tickSeq;
72
+ let failed = false;
73
+ const pending: PromiseLike<unknown>[] = [];
49
74
  for (const target of targets) {
50
75
  // One throwing target never stops the others or the timer.
51
76
  try {
52
- if (target.isPaused?.() !== true) target.reSync();
53
- } catch { /* swallowed */ }
77
+ if (target.isPaused?.() !== true) {
78
+ const result: unknown = target.reSync();
79
+ if (isThenable(result)) pending.push(result);
80
+ }
81
+ } catch { failed = true; }
54
82
  }
83
+ // A tick that settles after stop, or after a newer tick recorded, records nothing.
84
+ const record = (ok: boolean) => {
85
+ if (stopped || seq <= recordedSeq) return;
86
+ recordedSeq = seq;
87
+ lastTick$.next({ atMs: now(), status: ok ? 'ok' : 'error' });
88
+ };
89
+ if (pending.length === 0) record(!failed);
90
+ else void Promise.allSettled(pending).then((results) => record(!failed && results.every((r) => r.status === 'fulfilled')));
55
91
  };
56
92
  const arm = () => {
57
93
  if (timer !== undefined) clearTimeout(timer);
@@ -75,6 +111,8 @@ export function startSyncCadence({
75
111
 
76
112
  return {
77
113
  nextDueAtMs$: nextDueAtMs$.asObservable(),
114
+ lastTick$: lastTick$.asObservable(),
115
+ lastTick: () => lastTick$.getValue(),
78
116
  tickNow: () => {
79
117
  if (stopped) return;
80
118
  tick();
@@ -88,6 +126,7 @@ export function startSyncCadence({
88
126
  subscription.unsubscribe();
89
127
  nextDueAtMs$.next(undefined);
90
128
  nextDueAtMs$.complete();
129
+ lastTick$.complete();
91
130
  },
92
131
  };
93
132
  }