@tallyui/database 3.0.0-next.0 → 3.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -321,8 +321,10 @@ interface CatalogueReconcileSummary {
321
321
  tombstoned: number;
322
322
  /** Deletion candidates kept: unconfirmed, or held by the brake. */
323
323
  kept: number;
324
- /** Local documents the listing did not name, counted in an uninterrupted pass (0 in a resumed one). */
324
+ /** Local documents the listing did not name; only a result with `complete` has a real count. */
325
325
  unlisted: number;
326
+ /** True when the pass ran from its first page to its last in one go, so `unlisted` is a real count; false for a resumed pass, whose `unlisted` is 0 and must not be shown as current (medusapos/app#160). */
327
+ complete: boolean;
326
328
  durationMs: number;
327
329
  }
328
330
  /** In memory; the gate itself is persisted. `lastResult` is current when `lastResultAt > (lastErrorAt ?? 0)`. */
@@ -330,6 +332,8 @@ interface CatalogueReconcileState {
330
332
  running: boolean;
331
333
  lastResult?: CatalogueReconcileSummary;
332
334
  lastResultAt?: number;
335
+ /** When the last complete pass finished (persisted). A result without `complete` is not current. */
336
+ lastCompleteAt?: number;
333
337
  lastError?: unknown;
334
338
  lastErrorAt?: number;
335
339
  }
@@ -405,6 +409,7 @@ interface IdReconcileResult {
405
409
  queued: number;
406
410
  truncated: boolean;
407
411
  braked: boolean;
412
+ complete: boolean;
408
413
  }
409
414
  /**
410
415
  * Compares live product/variant ids against the local `products` collection
@@ -447,8 +452,10 @@ interface FingerprintReconcileResult {
447
452
  queued: number;
448
453
  /** Always false now that no page cap applies. */
449
454
  truncated: boolean;
455
+ /** True when `unreported` is a real count: a complete pass that read at least one page. */
456
+ complete: boolean;
450
457
  /**
451
- * Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
458
+ * Local products the remote side did not report (`complete` marks a real count); 0 on a resumed
452
459
  * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
453
460
  * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
454
461
  * correctly reports everything as unreported.
@@ -458,7 +465,7 @@ interface FingerprintReconcileResult {
458
465
  unreported: number;
459
466
  }
460
467
  /**
461
- * The runner's state; entirely in memory. The result is current only when
468
+ * The runner's state; `lastCompleteAt` is persisted. The result is current only when
462
469
  * `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
463
470
  * as stale. See `isFingerprintResultCurrent`.
464
471
  */
@@ -466,6 +473,7 @@ interface FingerprintReconcileState {
466
473
  running: boolean;
467
474
  lastResult?: FingerprintReconcileResult;
468
475
  lastResultAt?: number;
476
+ lastCompleteAt?: number;
469
477
  lastError?: unknown;
470
478
  lastErrorAt?: number;
471
479
  }
package/dist/index.js CHANGED
@@ -697,7 +697,7 @@ function startCatalogueRunner({
697
697
  if (memory) return memory;
698
698
  try {
699
699
  const doc = await collection.getLocal(stateId);
700
- return doc ? { lastCompletedAt: doc.get("lastCompletedAt"), pass: doc.get("pass") } : {};
700
+ return doc ? { lastCompletedAt: doc.get("lastCompletedAt"), lastCompleteAt: doc.get("lastCompleteAt"), pass: doc.get("pass") } : {};
701
701
  } catch (error) {
702
702
  if (typeof collection.getLocal === "function" && error?.code !== "LD8") throw error;
703
703
  console.warn(`Catalogue reconcile: ${collection.name} has no local documents (create it with connectorCollection); the gate is kept in memory.`);
@@ -708,6 +708,10 @@ function startCatalogueRunner({
708
708
  if (memory) memory = value;
709
709
  else await collection.upsertLocal(stateId, JSON.parse(JSON.stringify(value)));
710
710
  };
711
+ load().then(({ lastCompleteAt }) => {
712
+ if (lastCompleteAt !== void 0) update({ lastCompleteAt });
713
+ }).catch(() => {
714
+ });
711
715
  const sleep2 = (ms) => new Promise((resolve) => {
712
716
  const onAbort = () => {
713
717
  cancel();
@@ -746,11 +750,23 @@ function startCatalogueRunner({
746
750
  checkAborted();
747
751
  const startedAt = now();
748
752
  const saved = await load();
749
- const resumed = Boolean(saved.pass && startedAt - saved.pass.startedAt < intervalMs);
753
+ const resumed = Boolean(saved.pass && saved.pass.cursor !== void 0 && startedAt - saved.pass.startedAt < intervalMs);
750
754
  let current = resumed ? { ...saved.pass, uninterrupted: false } : { startedAt, uninterrupted: true };
751
- await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
755
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
752
756
  log({ type: "pass-started", resumed });
753
757
  const seen = /* @__PURE__ */ new Set();
758
+ let index;
759
+ const buildIndex = async (matchKey) => {
760
+ const built = /* @__PURE__ */ new Map();
761
+ for await (const chunk of readFreshInChunks(collection)) {
762
+ checkAborted();
763
+ for (const doc of chunk) {
764
+ const match = matchKey(doc);
765
+ if (match !== void 0 && !built.has(match)) built.set(match, keyOf(doc));
766
+ }
767
+ }
768
+ return built;
769
+ };
754
770
  let pages = 0;
755
771
  let compared = 0;
756
772
  let refetched = 0;
@@ -763,14 +779,16 @@ function startCatalogueRunner({
763
779
  if (next.done) break;
764
780
  pages++;
765
781
  const { entries, cursor } = next.value;
766
- const locals = await readByKeys(entries.map((e) => e.key));
782
+ const byMatch = adapter.matchKey ? index ??= await buildIndex(adapter.matchKey.bind(adapter)) : void 0;
783
+ const primaries = entries.map((e) => byMatch ? byMatch.get(e.key) : e.key);
784
+ const locals = await readByKeys(primaries.filter((key) => key !== void 0));
767
785
  const queue = [];
768
- for (const { key, fingerprint, remote } of entries) {
786
+ entries.forEach(({ key, fingerprint, remote }, i) => {
769
787
  seen.add(key);
770
- const local = locals.get(key);
788
+ const local = primaries[i] === void 0 ? void 0 : locals.get(primaries[i]);
771
789
  if (local) compared++;
772
- if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key, local, remote });
773
- }
790
+ if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key: local ? keyOf(local) : key, local, remote });
791
+ });
774
792
  checkAborted();
775
793
  if (queue.length) {
776
794
  const size = adapter.refetchBatchSize;
@@ -782,7 +800,7 @@ function startCatalogueRunner({
782
800
  log({ type: "refetched", ...listed(queue.map((e) => e.key)) });
783
801
  }
784
802
  current = { ...current, cursor };
785
- await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
803
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
786
804
  }
787
805
  } finally {
788
806
  iterator.return?.()?.catch(() => {
@@ -802,7 +820,10 @@ function startCatalogueRunner({
802
820
  for await (const chunk of readFreshInChunks(collection)) {
803
821
  checkAborted();
804
822
  localCount += chunk.length;
805
- for (const doc of chunk) if (!seen.has(keyOf(doc))) candidates.push(doc);
823
+ for (const doc of chunk) {
824
+ const key = adapter.matchKey ? adapter.matchKey(doc) : keyOf(doc);
825
+ if (key === void 0 || !seen.has(key)) candidates.push(doc);
826
+ }
806
827
  }
807
828
  unlisted = candidates.length;
808
829
  let gone = [];
@@ -833,8 +854,8 @@ function startCatalogueRunner({
833
854
  }
834
855
  checkAborted();
835
856
  const lastCompletedAt = now();
836
- await save({ lastCompletedAt });
837
- const summary = { pages, compared, refetched, tombstoned, kept, unlisted, durationMs: lastCompletedAt - startedAt };
857
+ await save({ lastCompletedAt, lastCompleteAt: current.uninterrupted ? lastCompletedAt : saved.lastCompleteAt });
858
+ const summary = { pages, compared, refetched, tombstoned, kept, unlisted, complete: current.uninterrupted, durationMs: lastCompletedAt - startedAt };
838
859
  log({ type: "pass-completed", ...summary });
839
860
  return summary;
840
861
  };
@@ -863,7 +884,7 @@ function startCatalogueRunner({
863
884
  try {
864
885
  const result = await pass();
865
886
  failures = 0;
866
- update({ running: false, lastResult: result, lastResultAt: now() });
887
+ update({ running: false, lastResult: result, lastResultAt: now(), ...result.complete && { lastCompleteAt: now() } });
867
888
  return result;
868
889
  } catch (error) {
869
890
  update({ running: false, lastError: error, lastErrorAt: now() });
@@ -971,7 +992,7 @@ function startFingerprintReconcile({
971
992
  }
972
993
  }
973
994
  });
974
- const toResult = ({ pages, compared, unlisted }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0 });
995
+ const toResult = ({ pages, compared, unlisted, complete }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0, complete: complete && pages > 0 });
975
996
  const state = new BehaviorSubject6({ running: false });
976
997
  let summary;
977
998
  let result;
@@ -1042,7 +1063,7 @@ function startIdReconcile({
1042
1063
  }
1043
1064
  }
1044
1065
  });
1045
- const reconcileIds = () => request().then(({ pages }) => ({ pages, queued, truncated: false, braked }));
1066
+ const reconcileIds = () => request().then(({ pages, complete }) => ({ pages, queued, truncated: false, braked, complete }));
1046
1067
  return { reconcileIds, stop };
1047
1068
  }
1048
1069
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/database",
3
- "version": "3.0.0-next.0",
3
+ "version": "3.0.0-next.1",
4
4
  "type": "module",
5
5
  "description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
6
6
  "main": "./dist/index.js",
@@ -29,7 +29,7 @@
29
29
  "rxjs": "7.8.2"
30
30
  },
31
31
  "peerDependencies": {
32
- "@tallyui/core": "^3.0.0-next.0"
32
+ "@tallyui/core": "^3.0.0-next.1"
33
33
  },
34
34
  "scripts": {
35
35
  "build": "tsup",
@@ -47,8 +47,10 @@ export interface CatalogueReconcileSummary {
47
47
  tombstoned: number;
48
48
  /** Deletion candidates kept: unconfirmed, or held by the brake. */
49
49
  kept: number;
50
- /** Local documents the listing did not name, counted in an uninterrupted pass (0 in a resumed one). */
50
+ /** Local documents the listing did not name; only a result with `complete` has a real count. */
51
51
  unlisted: number;
52
+ /** True when the pass ran from its first page to its last in one go, so `unlisted` is a real count; false for a resumed pass, whose `unlisted` is 0 and must not be shown as current (medusapos/app#160). */
53
+ complete: boolean;
52
54
  durationMs: number;
53
55
  }
54
56
 
@@ -57,6 +59,8 @@ export interface CatalogueReconcileState {
57
59
  running: boolean;
58
60
  lastResult?: CatalogueReconcileSummary;
59
61
  lastResultAt?: number;
62
+ /** When the last complete pass finished (persisted). A result without `complete` is not current. */
63
+ lastCompleteAt?: number;
60
64
  lastError?: unknown;
61
65
  lastErrorAt?: number;
62
66
  }
@@ -96,7 +100,7 @@ export function shouldReconcileAfterGap(lastPullAt: number | undefined, now = Da
96
100
  }
97
101
 
98
102
  interface PassState { startedAt: number; cursor?: unknown; uninterrupted: boolean }
99
- interface Persisted { lastCompletedAt?: number; pass?: PassState }
103
+ interface Persisted { lastCompletedAt?: number; lastCompleteAt?: number; pass?: PassState }
100
104
 
101
105
  // The state ids in use per collection: two runners sharing one would share a cursor.
102
106
  const claimed = new WeakMap<object, Set<string>>();
@@ -158,7 +162,7 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
158
162
  if (memory) return memory;
159
163
  try {
160
164
  const doc = await collection.getLocal<Persisted>(stateId);
161
- return doc ? { lastCompletedAt: doc.get('lastCompletedAt'), pass: doc.get('pass') } : {};
165
+ return doc ? { lastCompletedAt: doc.get('lastCompletedAt'), lastCompleteAt: doc.get('lastCompleteAt'), pass: doc.get('pass') } : {};
162
166
  } catch (error) {
163
167
  // LD8: local documents are off; no getLocal at all: the plugin was never added.
164
168
  if (typeof collection.getLocal === 'function' && (error as { code?: unknown } | null)?.code !== 'LD8') throw error;
@@ -171,6 +175,7 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
171
175
  if (memory) memory = value;
172
176
  else await collection.upsertLocal(stateId, JSON.parse(JSON.stringify(value)));
173
177
  };
178
+ load().then(({ lastCompleteAt }) => { if (lastCompleteAt !== undefined) update({ lastCompleteAt }); }).catch(() => {});
174
179
 
175
180
  const sleep = (ms: number) => new Promise<void>((resolve) => {
176
181
  const onAbort = () => { cancel(); resolve(); };
@@ -207,14 +212,29 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
207
212
  checkAborted();
208
213
  const startedAt = now();
209
214
  const saved = await load();
210
- // A pass stopped within the interval resumes from its cursor. A resumed pass never
211
- // deletes: the keys it saw before it stopped are not kept.
212
- const resumed = Boolean(saved.pass && startedAt - saved.pass.startedAt < intervalMs);
215
+ // A stored pass that finished no page has no cursor. Restarting it re-reads from the first page,
216
+ // so it runs uninterrupted. A resumed pass never deletes: earlier keys are not kept.
217
+ const resumed = Boolean(saved.pass && saved.pass.cursor !== undefined && startedAt - saved.pass.startedAt < intervalMs);
213
218
  let current: PassState = resumed ? { ...saved.pass!, uninterrupted: false } : { startedAt, uninterrupted: true };
214
- await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
219
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
215
220
  log({ type: 'pass-started', resumed });
216
221
 
222
+ // The listing's keys; with adapter.matchKey these are match keys, not primary keys (#313).
217
223
  const seen = new Set<string>();
224
+ // With matchKey: match key to primary key, built at the first page of each pass (a resumed one too). Strings only.
225
+ let index: Map<string, string> | undefined;
226
+ const buildIndex = async (matchKey: (doc: Doc) => string | undefined) => {
227
+ const built = new Map<string, string>();
228
+ for await (const chunk of readFreshInChunks(collection)) {
229
+ checkAborted();
230
+ for (const doc of chunk) {
231
+ const match = matchKey(doc);
232
+ // On a duplicate match key the first document wins.
233
+ if (match !== undefined && !built.has(match)) built.set(match, keyOf(doc));
234
+ }
235
+ }
236
+ return built;
237
+ };
218
238
  let pages = 0;
219
239
  let compared = 0;
220
240
  let refetched = 0;
@@ -227,14 +247,17 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
227
247
  if (next.done) break;
228
248
  pages++;
229
249
  const { entries, cursor } = next.value;
230
- const locals = await readByKeys(entries.map((e) => e.key));
250
+ const byMatch = adapter.matchKey ? (index ??= await buildIndex(adapter.matchKey.bind(adapter))) : undefined;
251
+ const primaries = entries.map((e) => (byMatch ? byMatch.get(e.key) : e.key));
252
+ const locals = await readByKeys(primaries.filter((key): key is string => key !== undefined));
231
253
  const queue: Array<{ key: string; local?: Doc; remote?: unknown }> = [];
232
- for (const { key, fingerprint, remote } of entries) {
254
+ entries.forEach(({ key, fingerprint, remote }, i) => {
233
255
  seen.add(key);
234
- const local = locals.get(key);
256
+ const local = primaries[i] === undefined ? undefined : locals.get(primaries[i]!);
235
257
  if (local) compared++;
236
- if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key, local, remote });
237
- }
258
+ // A remote-only entry keeps the listing's key.
259
+ if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key: local ? keyOf(local) : key, local, remote });
260
+ });
238
261
  checkAborted();
239
262
  if (queue.length) {
240
263
  // The refetch this page causes runs in the pull, outside the runner: its slots, one per fetchByIds request
@@ -248,7 +271,7 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
248
271
  log({ type: 'refetched', ...listed(queue.map((e) => e.key)) });
249
272
  }
250
273
  current = { ...current, cursor };
251
- await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
274
+ await save({ lastCompletedAt: saved.lastCompletedAt, lastCompleteAt: saved.lastCompleteAt, pass: current });
252
275
  }
253
276
  } finally {
254
277
  iterator.return?.()?.catch(() => {});
@@ -269,7 +292,10 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
269
292
  for await (const chunk of readFreshInChunks(collection)) {
270
293
  checkAborted();
271
294
  localCount += chunk.length;
272
- for (const doc of chunk) if (!seen.has(keyOf(doc))) candidates.push(doc);
295
+ for (const doc of chunk) {
296
+ const key = adapter.matchKey ? adapter.matchKey(doc) : keyOf(doc);
297
+ if (key === undefined || !seen.has(key)) candidates.push(doc);
298
+ }
273
299
  }
274
300
  unlisted = candidates.length;
275
301
  // The brake applies to the candidates, before confirmGone: a broken listing never sends
@@ -309,8 +335,8 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
309
335
 
310
336
  checkAborted();
311
337
  const lastCompletedAt = now();
312
- await save({ lastCompletedAt });
313
- const summary = { pages, compared, refetched, tombstoned, kept, unlisted, durationMs: lastCompletedAt - startedAt };
338
+ await save({ lastCompletedAt, lastCompleteAt: current.uninterrupted ? lastCompletedAt : saved.lastCompleteAt });
339
+ const summary = { pages, compared, refetched, tombstoned, kept, unlisted, complete: current.uninterrupted, durationMs: lastCompletedAt - startedAt };
314
340
  log({ type: 'pass-completed', ...summary });
315
341
  return summary;
316
342
  };
@@ -337,7 +363,7 @@ export function startCatalogueRunner<Doc, Cursor = unknown>({
337
363
  try {
338
364
  const result = await pass();
339
365
  failures = 0;
340
- update({ running: false, lastResult: result, lastResultAt: now() });
366
+ update({ running: false, lastResult: result, lastResultAt: now(), ...(result.complete && { lastCompleteAt: now() }) });
341
367
  return result;
342
368
  } catch (error) {
343
369
  update({ running: false, lastError: error, lastErrorAt: now() });
@@ -33,8 +33,10 @@ export interface FingerprintReconcileResult {
33
33
  queued: number;
34
34
  /** Always false now that no page cap applies. */
35
35
  truncated: boolean;
36
+ /** True when `unreported` is a real count: a complete pass that read at least one page. */
37
+ complete: boolean;
36
38
  /**
37
- * Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
39
+ * Local products the remote side did not report (`complete` marks a real count); 0 on a resumed
38
40
  * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
39
41
  * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
40
42
  * correctly reports everything as unreported.
@@ -45,7 +47,7 @@ export interface FingerprintReconcileResult {
45
47
  }
46
48
 
47
49
  /**
48
- * The runner's state; entirely in memory. The result is current only when
50
+ * The runner's state; `lastCompleteAt` is persisted. The result is current only when
49
51
  * `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
50
52
  * as stale. See `isFingerprintResultCurrent`.
51
53
  */
@@ -53,6 +55,7 @@ export interface FingerprintReconcileState {
53
55
  running: boolean;
54
56
  lastResult?: FingerprintReconcileResult;
55
57
  lastResultAt?: number;
58
+ lastCompleteAt?: number;
56
59
  lastError?: unknown;
57
60
  lastErrorAt?: number;
58
61
  }
@@ -129,8 +132,8 @@ export function startFingerprintReconcile<Doc>({
129
132
  },
130
133
  },
131
134
  });
132
- const toResult = ({ pages, compared, unlisted }: CatalogueReconcileSummary): FingerprintReconcileResult =>
133
- ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0 });
135
+ const toResult = ({ pages, compared, unlisted, complete }: CatalogueReconcileSummary): FingerprintReconcileResult =>
136
+ ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0, complete: complete && pages > 0 });
134
137
 
135
138
  // Mapped as each pass ends, while `queued` is still that pass's count.
136
139
  const state = new BehaviorSubject<FingerprintReconcileState>({ running: false });
@@ -29,7 +29,7 @@ export interface StartIdReconcileOptions<Doc> {
29
29
  }
30
30
 
31
31
  /** `truncated` is always false now that no page cap applies. */
32
- export interface IdReconcileResult { pages: number; queued: number; truncated: boolean; braked: boolean }
32
+ export interface IdReconcileResult { pages: number; queued: number; truncated: boolean; braked: boolean; complete: boolean }
33
33
 
34
34
  /**
35
35
  * Compares live product/variant ids against the local `products` collection
@@ -75,6 +75,6 @@ export function startIdReconcile<Doc>({
75
75
  },
76
76
  });
77
77
  // `.then` is attached at call time, so it reads this pass's counts before a follow-up starts.
78
- const reconcileIds = () => request().then(({ pages }) => ({ pages, queued, truncated: false, braked }));
78
+ const reconcileIds = () => request().then(({ pages, complete }) => ({ pages, queued, truncated: false, braked, complete }));
79
79
  return { reconcileIds, stop };
80
80
  }