@tallyui/database 2.0.0 → 3.0.0-next.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.
@@ -1,10 +1,9 @@
1
1
  import type { RxCollection } from 'rxdb';
2
2
  import { BehaviorSubject, type Observable } from 'rxjs';
3
3
 
4
- import type { FingerprintReconcileAdapter, SyncContext } from '@tallyui/core';
5
- import { readFresh } from '@tallyui/core/rxdb';
4
+ import type { CatalogueReconcileEntry, FingerprintReconcileAdapter, SyncContext } from '@tallyui/core';
6
5
 
7
- import { createPassQueue } from './pass-queue';
6
+ import { startCatalogueRunner, type CatalogueReconcileSummary } from './catalogue-reconcile';
8
7
 
9
8
  export interface StartFingerprintReconcileOptions<Doc> {
10
9
  /** The replicated collection. Read only. */
@@ -13,23 +12,29 @@ export interface StartFingerprintReconcileOptions<Doc> {
13
12
  context: SyncContext;
14
13
  /** The app's `() => replication.reSync()`. */
15
14
  reSync: () => void;
16
- /** Delay before the first pass; `null` (default) skips it, since this runner is meant as a nightly backstop. */
15
+ /** Delay before the first gate check; `null` (default) skips it and checks hourly. */
17
16
  startDelayMs?: number | null;
18
- /** Time between passes in ms (default 86400000, 24 hours). */
17
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
19
18
  intervalMs?: number;
20
- /** Pages read before a pass is truncated (default 100). */
19
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
21
20
  maxPages?: number;
22
21
  /** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
23
22
  now?: () => number;
23
+ /**
24
+ * The local document holding this runner's gate (default 'fingerprint-reconcile').
25
+ * Two fingerprint runners on one collection (prices and calculated prices) each need their own.
26
+ */
27
+ stateId?: string;
24
28
  }
25
29
 
26
30
  export interface FingerprintReconcileResult {
27
31
  pages: number;
28
32
  compared: number;
29
33
  queued: number;
34
+ /** Always false now that no page cap applies. */
30
35
  truncated: boolean;
31
36
  /**
32
- * Local products the remote side did not report in a complete pass (they are skipped); 0 on a truncated or failed
37
+ * Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
33
38
  * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
34
39
  * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
35
40
  * correctly reports everything as unreported.
@@ -57,102 +62,88 @@ export function isFingerprintResultCurrent(state: FingerprintReconcileState): bo
57
62
  return state.lastResultAt !== undefined && state.lastResultAt > (state.lastErrorAt ?? 0);
58
63
  }
59
64
 
65
+ /**
66
+ * The id wrapper's deletion proof: a pass-through that confirms every candidate. The wrapper hands
67
+ * each to the reconcile feed as a plain `{ id, local }` entry, not a tombstone, and the feed's by-id
68
+ * re-read (`fetchByIds`) tombstones only what does not come back: that refetch is the proof.
69
+ */
70
+ export function confirmAll<Doc>(collection: RxCollection<Doc>) {
71
+ const primary = collection.schema.primaryPath as string;
72
+ return async (locals: Doc[]) => locals.map((doc) => (doc as Record<string, unknown>)[primary] as string);
73
+ }
74
+
75
+ /**
76
+ * An old adapter's pages as catalogue pages. The cursor is the count of pages read. Old adapters
77
+ * cannot start mid-way, so a resumed pass re-reads the pages before its cursor; each comes back
78
+ * empty, so the runner takes a budget slot for its request but compares nothing, and counts it as a page.
79
+ */
80
+ export async function* skipPages<Page>(
81
+ pages: AsyncIterable<Page>, entries: (page: Page) => CatalogueReconcileEntry[], from = 0,
82
+ ): AsyncIterable<{ entries: CatalogueReconcileEntry[]; cursor: number }> {
83
+ let read = 0;
84
+ for await (const page of pages) {
85
+ read++;
86
+ yield { entries: read <= from ? [] : entries(page), cursor: Math.max(read, from) };
87
+ }
88
+ }
89
+
60
90
  /**
61
91
  * Compares a remote fingerprint per product against the local `collection`
62
- * and queues disagreeing products for the collection's pull (ADR-060). Only
63
- * reads `collection`. A throw, abort or truncation queues nothing and skips
64
- * `reSync`; only a complete pass acts. Products the remote side doesn't
65
- * report are left alone -- deletions are the id reconcile's job. No pass
66
- * runs at start by default (`startDelayMs: null`); the app may still call
67
- * `reconcile()` on demand. A call during a pass queues one follow-up pass
68
- * (later calls share it), so a change made after the pass read is picked up
69
- * straight after, not at the next interval.
92
+ * and queues disagreeing products for the collection's pull (ADR-060), as a
93
+ * wrapper over the catalogue runner (#248). Never deletes: every entry is
94
+ * `refreshOnly`, and a product the remote side doesn't report is only counted
95
+ * as `unreported`. Passes follow the persisted daily gate within a request
96
+ * budget; the app may still call `reconcile()` on demand. A call during a pass
97
+ * queues one follow-up pass (later calls share it).
70
98
  */
71
99
  export function startFingerprintReconcile<Doc>({
72
- collection, adapter, context, reSync, startDelayMs = null, intervalMs = 86_400_000, maxPages = 100, now = Date.now,
100
+ adapter, reSync, startDelayMs = null, maxPages: _ignored, stateId = 'fingerprint-reconcile', ...options
73
101
  }: StartFingerprintReconcileOptions<Doc>): {
74
102
  reconcile(): Promise<FingerprintReconcileResult>;
75
103
  stop(): void;
76
104
  state$: Observable<FingerprintReconcileState>;
77
105
  } {
78
- const controller = new AbortController();
79
- const { signal } = controller;
80
- // React Native's AbortController polyfill has no throwIfAborted() and may have no reason.
81
- const checkAborted = () => { if (signal.aborted) throw signal.reason ?? new Error('Fingerprint reconcile stopped'); };
82
- const state = new BehaviorSubject<FingerprintReconcileState>({ running: false });
83
- const update = (patch: Partial<FingerprintReconcileState>) => state.next({ ...state.value, ...patch });
84
-
85
- const pass = async (): Promise<FingerprintReconcileResult> => {
86
- checkAborted();
87
- // Phase 1: read every page first. A throw, abort or truncation here queues
88
- // nothing and skips reSync, so only a complete pass ever acts (ADR-060).
89
- const remote = new Map<string, string>();
90
- let pages = 0;
91
- for await (const page of adapter.fetchPages({ ...context, signal })) {
92
- checkAborted();
93
- if (pages === maxPages) {
94
- console.warn(`Fingerprint reconcile stopped at the ${maxPages}-page limit; nothing was queued.`);
95
- return { pages, compared: 0, queued: 0, truncated: true, unreported: 0 };
96
- }
97
- pages++;
98
- for (const [id, fingerprint] of page) remote.set(id, fingerprint);
99
- }
100
-
101
- checkAborted();
102
- // Phase 2: compare local documents the remote side reported against their
103
- // remote fingerprint. A product the remote side didn't report is skipped.
104
- const entries: Array<{ id: string; local: Doc; refreshOnly: true }> = [];
105
- let compared = 0;
106
- let unreported = 0;
107
- // readFresh, not a cached `find()`: a pull write during that query's storage read would
108
- // leave it stale for every later pass (RxDB 16.21.1 bug 4, `readFresh`'s doc comment).
109
- for (const local of await readFresh(collection, {})) {
110
- const id = (local as Record<string, unknown>)[collection.schema.primaryPath] as string;
111
- const remoteFingerprint = remote.get(id);
112
- if (remoteFingerprint === undefined) { if (pages > 0) unreported++; continue; }
113
- compared++;
114
- // refreshOnly: a missing re-fetch is skipped, never tombstoned -- deletions are the id reconcile's job (ADR-060).
115
- if (adapter.fingerprint(local) !== remoteFingerprint) entries.push({ id, local, refreshOnly: true });
116
- }
117
-
118
- checkAborted();
119
- // Only touch reSync when there is something for the pull to correct.
120
- if (entries.length) { adapter.enqueue(entries); reSync(); }
121
- return { pages, compared, queued: entries.length, truncated: false, unreported };
122
- };
123
-
124
- const tracked = async (): Promise<FingerprintReconcileResult> => {
125
- update({ running: true });
126
- try {
127
- const result = await pass();
128
- update({ running: false, lastResult: result, lastResultAt: now() });
129
- return result;
130
- } catch (error) {
131
- // lastResult (and lastResultAt) are left as they were: the app can tell it's stale via isFingerprintResultCurrent.
132
- update({ running: false, lastError: error, lastErrorAt: now() });
133
- throw error;
134
- }
135
- };
136
-
137
- const reconcile = createPassQueue(tracked);
138
- const onTimer = () => reconcile().catch((error) => console.warn('Fingerprint reconcile failed:', error));
139
- let startTimer: ReturnType<typeof setTimeout> | undefined;
140
- let intervalTimer: ReturnType<typeof setInterval>;
141
- const scheduleInterval = () => { intervalTimer = setInterval(onTimer, intervalMs); };
142
- // startDelayMs: null (the default) skips the start pass and goes straight to the nightly cadence.
143
- if (startDelayMs === null) scheduleInterval();
144
- else startTimer = setTimeout(() => { onTimer(); scheduleInterval(); }, startDelayMs);
145
-
146
- // stop() and an abort of context.signal both end the runner for good.
147
- const stop = () => {
148
- clearTimeout(startTimer);
149
- clearInterval(intervalTimer);
150
- context.signal?.removeEventListener('abort', stop);
151
- controller.abort();
152
- state.complete();
153
- };
154
- if (context.signal?.aborted) stop();
155
- else context.signal?.addEventListener('abort', stop);
106
+ let queued = 0;
107
+ let pending = false;
108
+ const { request, stop, state$: catalogue$ } = startCatalogueRunner<Doc, number>({
109
+ ...options, startDelayMs, stateId, keepCandidates: true,
110
+ // Only touch reSync when something reached the pull.
111
+ reSync: () => { if (pending) { pending = false; reSync(); } },
112
+ log: (event) => { if (event.type === 'pass-started') queued = 0; },
113
+ adapter: {
114
+ fetchPages: (context, from) => skipPages(adapter.fetchPages(context),
115
+ (page) => [...page].map(([key, fingerprint]) => ({ key, fingerprint })), from),
116
+ fingerprint: (doc) => adapter.fingerprint(doc),
117
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
118
+ refetchBatchSize: adapter.refetchBatchSize,
119
+ // It never deletes: keepCandidates only counts the products the listing did not name (`unreported`), before the
120
+ // brake and confirmGone, so this is never called; a call is a runner bug, and it fails the pass loudly.
121
+ confirmGone: async () => { throw new Error('The fingerprint reconcile never deletes; confirmGone must not be called.'); },
122
+ // refreshOnly: a missing re-fetch is skipped, never tombstoned (ADR-060). A product the till lacks is left to the pull.
123
+ enqueue: (entries) => {
124
+ const known = entries.flatMap(({ key, local }) => (local ? [{ id: key, local, refreshOnly: true as const }] : []));
125
+ if (!known.length) return;
126
+ queued += known.length;
127
+ pending = true;
128
+ adapter.enqueue(known);
129
+ },
130
+ },
131
+ });
132
+ const toResult = ({ pages, compared, unlisted }: CatalogueReconcileSummary): FingerprintReconcileResult =>
133
+ ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0 });
156
134
 
135
+ // Mapped as each pass ends, while `queued` is still that pass's count.
136
+ const state = new BehaviorSubject<FingerprintReconcileState>({ running: false });
137
+ let summary: CatalogueReconcileSummary | undefined;
138
+ let result: FingerprintReconcileResult | undefined;
139
+ catalogue$.subscribe({
140
+ next: ({ lastResult, ...rest }) => {
141
+ if (lastResult !== summary) { summary = lastResult; result = lastResult && toResult(lastResult); }
142
+ state.next(result ? { ...rest, lastResult: result } : rest);
143
+ },
144
+ complete: () => state.complete(),
145
+ });
146
+ // `.then` is attached at call time, so it reads this pass's counts before a follow-up starts.
147
+ const reconcile = () => request().then(toResult);
157
148
  return { reconcile, stop, state$: state.asObservable() };
158
149
  }
@@ -1,14 +1,8 @@
1
1
  import type { RxCollection } from 'rxdb';
2
2
  import type { IdReconcileAdapter, SyncContext } from '@tallyui/core';
3
- import { readFresh } from '@tallyui/core/rxdb';
4
3
 
5
- import { createPassQueue } from './pass-queue';
6
-
7
- /**
8
- * Below this count of would-be tombstones, the brake never applies, whatever
9
- * `maxDeleteShare` says: in a small shop, deleting 2 of 5 products is normal.
10
- */
11
- const MASS_DELETE_MINIMUM = 10;
4
+ import { startCatalogueRunner } from './catalogue-reconcile';
5
+ import { confirmAll, skipPages } from './fingerprint-reconcile';
12
6
 
13
7
  export interface StartIdReconcileOptions<Doc> {
14
8
  /** The replicated products collection. Read only. */
@@ -17,115 +11,70 @@ export interface StartIdReconcileOptions<Doc> {
17
11
  context: SyncContext;
18
12
  /** The app's `() => replication.reSync()`. */
19
13
  reSync: () => void;
20
- /** Delay before the first pass (default 5000); `null` skips it. */
14
+ /** Delay before the first gate check (default 5000); `null` skips it and checks hourly. */
21
15
  startDelayMs?: number | null;
22
- /** Time between passes in ms (default 86400000, 24 hours). */
16
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
23
17
  intervalMs?: number;
24
- /** Pages read before a pass is truncated (default 100). */
18
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
25
19
  maxPages?: number;
26
20
  /**
27
- * The brake applies once would-be tombstones exceed this share of local
21
+ * The brake applies once tombstones exceed this share of local
28
22
  * products (default 0.2), unless `allowMassDelete` is set.
29
23
  */
30
24
  maxDeleteShare?: number;
31
25
  /** Explicit override for a genuine purge; disables the mass-delete brake. */
32
26
  allowMassDelete?: boolean;
27
+ /** The local document holding this runner's gate (default 'id-reconcile'). */
28
+ stateId?: string;
33
29
  }
34
30
 
31
+ /** `truncated` is always false now that no page cap applies. */
35
32
  export interface IdReconcileResult { pages: number; queued: number; truncated: boolean; braked: boolean }
36
33
 
37
34
  /**
38
35
  * Compares live product/variant ids against the local `products` collection
39
- * and queues disagreeing documents for the collection's pull (ADR-060). Only
40
- * reads `collection`. A throw, abort, truncation or the mass-delete brake
41
- * (below) queues nothing and skips `reSync`; only a complete, un-braked pass
42
- * acts. One pass runs `startDelayMs` after start, then every `intervalMs`. A
43
- * call during a pass queues one follow-up pass (later calls share it), so a
44
- * change made after the pass read is picked up straight after, not at the
45
- * next interval.
36
+ * and queues disagreeing documents for the collection's pull (ADR-060), as a
37
+ * wrapper over the catalogue runner (#248): a product whose variant ids differ
38
+ * is refetched page by page; a product missing remotely is queued for deletion
39
+ * only after an uninterrupted pass and under the mass-delete brake. Passes
40
+ * follow the persisted daily gate within a request budget. A call during a
41
+ * pass queues one follow-up pass (later calls share it).
46
42
  */
47
43
  export function startIdReconcile<Doc>({
48
- collection, adapter, context, reSync, startDelayMs = 5_000, intervalMs = 86_400_000, maxPages = 100,
49
- maxDeleteShare = 0.2, allowMassDelete = false,
44
+ adapter, reSync, startDelayMs = 5_000, maxPages: _ignored, stateId = 'id-reconcile', ...options
50
45
  }: StartIdReconcileOptions<Doc>): { reconcileIds(): Promise<IdReconcileResult>; stop(): void } {
51
- const controller = new AbortController();
52
- const { signal } = controller;
53
- // React Native's AbortController polyfill has no throwIfAborted() and may have no reason.
54
- const checkAborted = () => { if (signal.aborted) throw signal.reason ?? new Error('Id reconcile stopped'); };
55
-
56
- const pass = async (): Promise<IdReconcileResult> => {
57
- checkAborted();
58
- // Phase 1: read every page first. A throw, abort or truncation here queues
59
- // nothing and skips reSync, so only a complete pass ever acts (ADR-060).
60
- const remote = new Map<string, string[]>();
61
- let pages = 0;
62
- for await (const page of adapter.fetchPages({ ...context, signal })) {
63
- checkAborted();
64
- if (pages === maxPages) {
65
- console.warn(`Id reconcile stopped at the ${maxPages}-page limit; nothing was queued.`);
66
- return { pages, queued: 0, truncated: true, braked: false };
67
- }
68
- pages++;
69
- for (const row of page) remote.set(row.id, row.variantIds);
70
- }
71
-
72
- checkAborted();
73
- // Phase 2: queue local documents the backend no longer agrees with, either
74
- // missing entirely (a tombstone) or listing a variant id that vanished
75
- // remotely. Tombstones are counted separately for the mass-delete brake.
76
- const entries: Array<{ id: string; local: Doc }> = [];
77
- let localCount = 0;
78
- let tombstones = 0;
79
- // readFresh, not a cached `find()`: a pull write during that query's storage read would
80
- // leave it stale for every later pass (RxDB 16.21.1 bug 4, `readFresh`'s doc comment).
81
- for (const local of await readFresh(collection, {})) {
82
- localCount++;
83
- const id = (local as Record<string, unknown>)[collection.schema.primaryPath] as string;
84
- const remoteVariantIds = remote.get(id);
85
- const vanished = remoteVariantIds && adapter.variantIds(local).some((v) => !remoteVariantIds.includes(v));
86
- if (!remoteVariantIds) tombstones++;
87
- if (!remoteVariantIds || vanished) entries.push({ id, local });
88
- }
89
-
90
- checkAborted();
91
- // The brake: a wrong channel token or a permissions change must never
92
- // empty a shop's catalogue. A catalogue that would vanish completely is
93
- // always suspicious, whatever its size. Otherwise, apply only when
94
- // tombstones are both a large share of the local catalogue and more than
95
- // the minimum that a small shop's normal churn can explain.
96
- if (!allowMassDelete && localCount > 0
97
- && (tombstones === localCount || (tombstones > MASS_DELETE_MINIMUM && tombstones > maxDeleteShare * localCount))) {
98
- const share = localCount ? tombstones / localCount : 1;
99
- console.warn(
100
- `Id reconcile braked: ${tombstones} of ${localCount} local products `
101
- + `(${(share * 100).toFixed(1)}%); nothing was queued. Pass allowMassDelete: true to override.`,
102
- );
103
- return { pages, queued: 0, truncated: false, braked: true };
104
- }
105
-
106
- // Only touch reSync when there is something for the pull to correct.
107
- if (entries.length) { adapter.enqueue(entries); reSync(); }
108
- return { pages, queued: entries.length, truncated: false, braked: false };
109
- };
110
-
111
- const reconcileIds = createPassQueue(pass);
112
- const onTimer = () => reconcileIds().catch((error) => console.warn('Id reconcile failed:', error));
113
- let startTimer: ReturnType<typeof setTimeout> | undefined;
114
- let intervalTimer: ReturnType<typeof setInterval>;
115
- const scheduleInterval = () => { intervalTimer = setInterval(onTimer, intervalMs); };
116
- // startDelayMs: null skips the start pass and goes straight to the nightly cadence.
117
- if (startDelayMs === null) scheduleInterval();
118
- else startTimer = setTimeout(() => { onTimer(); scheduleInterval(); }, startDelayMs);
119
-
120
- // stop() and an abort of context.signal both end the runner for good.
121
- const stop = () => {
122
- clearTimeout(startTimer);
123
- clearInterval(intervalTimer);
124
- context.signal?.removeEventListener('abort', stop);
125
- controller.abort();
126
- };
127
- if (context.signal?.aborted) stop();
128
- else context.signal?.addEventListener('abort', stop);
129
-
46
+ const fingerprint = (ids: string[]) => [...ids].sort().join('\n');
47
+ let queued = 0;
48
+ let braked = false;
49
+ let pending = false;
50
+ const { request, stop } = startCatalogueRunner<Doc, number>({
51
+ ...options, startDelayMs, stateId,
52
+ // Only touch reSync when something reached the pull.
53
+ reSync: () => { if (pending) { pending = false; reSync(); } },
54
+ log: (event) => {
55
+ if (event.type === 'pass-started') { queued = 0; braked = false; }
56
+ if (event.type === 'kept' && event.reason === 'brake') braked = true;
57
+ },
58
+ adapter: {
59
+ fetchPages: (context, from) => skipPages(adapter.fetchPages(context),
60
+ (rows) => rows.map((row) => ({ key: row.id, fingerprint: fingerprint(row.variantIds) })), from),
61
+ fingerprint: (doc) => fingerprint(adapter.variantIds(doc)),
62
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
63
+ refetchBatchSize: adapter.refetchBatchSize,
64
+ // The proof is the feed's by-id re-read: every candidate is confirmed here and reaches the feed below as a
65
+ // plain entry, never `tombstone: true`, so the feed tombstones it only when fetchByIds does not return it.
66
+ confirmGone: confirmAll(options.collection),
67
+ // The old entry shape. A product the till lacks is left to the pull, as before.
68
+ enqueue: (entries) => {
69
+ const known = entries.flatMap(({ key, local }) => (local ? [{ id: key, local }] : []));
70
+ if (!known.length) return;
71
+ queued += known.length;
72
+ pending = true;
73
+ adapter.enqueue(known);
74
+ },
75
+ },
76
+ });
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 }));
130
79
  return { reconcileIds, stop };
131
80
  }
package/src/index.ts CHANGED
@@ -9,13 +9,17 @@ export { STORAGE_WRITE_STALL_MS, STORAGE_READ_WATCHDOG_MS, isStorageWorkerFailur
9
9
  export type { StorageHealth, StorageWatchdogOptions } from './storage-watchdog';
10
10
 
11
11
  export { startReplication } from './replication';
12
- export type { StartReplicationOptions } from './replication';
12
+ export type { StartReplicationOptions, TallyReplicationState } from './replication';
13
13
 
14
14
  export { startLiveTab } from './live-tab';
15
15
  export type { LiveTabState, LiveTabOptions, LiveTabHandle } from './live-tab';
16
16
 
17
17
  export { startStockReconcile } from './reconcile';
18
18
  export type { StartStockReconcileOptions, StockReconcileResult, StockReconcileState } from './reconcile';
19
+ export { startCatalogueReconcile, shouldReconcileAfterGap, CATALOGUE_OFFLINE_GAP_MS } from './catalogue-reconcile';
20
+ export type {
21
+ StartCatalogueReconcileOptions, CatalogueReconcileEvent, CatalogueReconcileState, CatalogueReconcileSummary,
22
+ } from './catalogue-reconcile';
19
23
  export { startIdReconcile } from './id-reconcile';
20
24
  export type { StartIdReconcileOptions, IdReconcileResult } from './id-reconcile';
21
25
  export { startFingerprintReconcile, isFingerprintResultCurrent } from './fingerprint-reconcile';
package/src/reconcile.ts CHANGED
@@ -3,6 +3,7 @@ import { BehaviorSubject, type Observable } from 'rxjs';
3
3
 
4
4
  import { STOCK_LEVELS_LAST_PASS, type StockReconcileAdapter, type SyncContext } from '@tallyui/core';
5
5
 
6
+ import { BACKGROUND_CHUNK_SIZE, pauseBetweenChunks, readFreshInChunks } from './chunks';
6
7
  import { createPassQueue } from './pass-queue';
7
8
  import type { StockLevelRow } from './stock-levels';
8
9
 
@@ -47,6 +48,8 @@ export interface StockReconcileState {
47
48
  * follow-up pass (later calls share it), so a change made after the pass
48
49
  * read is picked up straight after, not at the next interval. stop() clears
49
50
  * the timer and aborts a running pass.
51
+ * A stop during writes leaves earlier chunks written and `last-pass` unchanged.
52
+ * ADR-060: these server-truth passes are idempotent, so the next pass finishes what a stopped pass left.
50
53
  */
51
54
  export function startStockReconcile({
52
55
  collection,
@@ -95,7 +98,11 @@ export function startStockReconcile({
95
98
  }
96
99
 
97
100
  // Phase 2: write only rows that changed; remove keys the backend no longer returns.
98
- const rows = (await collection.find().exec()).map((doc) => doc.toJSON() as StockLevelRow);
101
+ const rows: StockLevelRow[] = [];
102
+ for await (const chunk of readFreshInChunks(collection)) {
103
+ checkAborted();
104
+ rows.push(...chunk);
105
+ }
99
106
  const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
100
107
  const updatedAt = new Date().toISOString();
101
108
  const upserts = [...stock]
@@ -103,14 +110,20 @@ export function startStockReconcile({
103
110
  .map(([id, value]) => ({ id, value, updatedAt }));
104
111
  const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
105
112
 
106
- checkAborted();
107
- if (upserts.length) {
108
- const { error } = await collection.bulkUpsert(upserts);
113
+ let wroteChunk = false;
114
+ for (let i = 0; i < upserts.length; i += BACKGROUND_CHUNK_SIZE) {
115
+ if (wroteChunk) await pauseBetweenChunks();
116
+ checkAborted();
117
+ const { error } = await collection.bulkUpsert(upserts.slice(i, i + BACKGROUND_CHUNK_SIZE));
109
118
  if (error.length) throw error[0];
119
+ wroteChunk = true;
110
120
  }
111
- if (removals.length) {
112
- const { error } = await collection.bulkRemove(removals);
121
+ for (let i = 0; i < removals.length; i += BACKGROUND_CHUNK_SIZE) {
122
+ if (wroteChunk) await pauseBetweenChunks();
123
+ checkAborted();
124
+ const { error } = await collection.bulkRemove(removals.slice(i, i + BACKGROUND_CHUNK_SIZE));
113
125
  if (error.length) throw error[0];
126
+ wroteChunk = true;
114
127
  }
115
128
  // Rows written by this pass carry the same time.
116
129
  const completedAt = updatedAt;