@tallyui/database 1.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.
- package/LICENSE +21 -0
- package/dist/index.d.ts +432 -8
- package/dist/index.js +1016 -24
- package/package.json +10 -4
- package/src/catalogue-reconcile.ts +388 -0
- package/src/chunks.ts +29 -0
- package/src/connector-collection.ts +26 -0
- package/src/create-db.ts +58 -15
- package/src/engine.ts +5 -0
- package/src/fingerprint-reconcile.ts +149 -0
- package/src/id-reconcile.ts +80 -0
- package/src/index.ts +23 -2
- package/src/live-tab.ts +280 -0
- package/src/pass-queue.ts +19 -0
- package/src/reconcile.ts +163 -0
- package/src/replication.ts +157 -6
- package/src/stock-levels.ts +32 -0
- package/src/storage-watchdog.ts +140 -0
- package/src/storage.ts +11 -5
- package/src/replication.test.ts +0 -97
- package/src/storage.test.ts +0 -19
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Paul Kilmurray and TallyUI contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,64 @@
|
|
|
1
|
-
import { RxDatabase, RxCollection,
|
|
2
|
-
import {
|
|
1
|
+
import { RxStorage, RxDatabase, RxCollection, RxJsonSchema, MigrationStrategies } from 'rxdb';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
import { TallyConnector, ReplicationAdapter, SyncContext, SyncNotice, StockReconcileAdapter, CatalogueReconcileAdapter, IdReconcileAdapter, FingerprintReconcileAdapter } from '@tallyui/core';
|
|
4
|
+
export { STOCK_LEVELS_LAST_PASS } from '@tallyui/core';
|
|
3
5
|
import { RxReplicationState } from 'rxdb/plugins/replication';
|
|
4
6
|
|
|
7
|
+
/** WCPOS's value (ADR-061): a write pending longer than this is flagged as stalled, never failed. */
|
|
8
|
+
declare const STORAGE_WRITE_STALL_MS = 10000;
|
|
9
|
+
/** WCPOS's value (ADR-061): two consecutive silent read windows of this length mean the worker is dead. */
|
|
10
|
+
declare const STORAGE_READ_WATCHDOG_MS = 30000;
|
|
11
|
+
interface StorageHealth {
|
|
12
|
+
/** 'ok'; 'stalled' while a write has been pending longer than writeStallMs; 'dead' after two silent read windows (reload to recover, ADR-061). */
|
|
13
|
+
status: 'ok' | 'stalled' | 'dead';
|
|
14
|
+
/** Writes pending longer than writeStallMs right now. */
|
|
15
|
+
stalledWrites: number;
|
|
16
|
+
/** When the oldest stalled write started (ms since epoch), if any. */
|
|
17
|
+
stalledSince?: number;
|
|
18
|
+
}
|
|
19
|
+
interface StorageWatchdogOptions {
|
|
20
|
+
writeStallMs?: number;
|
|
21
|
+
readWatchdogMs?: number;
|
|
22
|
+
/** Injectable clock, for tests. */
|
|
23
|
+
now?: () => number;
|
|
24
|
+
/** Injectable timer, for tests: runs `fn` once after `ms` and returns a cancel function. */
|
|
25
|
+
setTimer?: (fn: () => void, ms: number) => () => void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* True for `StorageWorkerStartError` (raised by `@tallyui/storage-sqlite/web`
|
|
29
|
+
* when the worker cannot open the opfs-sahpool pool), matched by `name` or by
|
|
30
|
+
* the substring `StorageWorkerStartError` anywhere in the message. RxDB's
|
|
31
|
+
* remote storage re-throws the worker's error serialised across the worker
|
|
32
|
+
* boundary as a plain `Error` whose message embeds the original name as JSON,
|
|
33
|
+
* so a substring match (`includes`, not `startsWith`) is needed to still
|
|
34
|
+
* recognise it.
|
|
35
|
+
*
|
|
36
|
+
* RxDB's RM1 (a stale worker built on another RxDB version, e.g. cached from
|
|
37
|
+
* before an upgrade) is one too: reloading loads the matching worker. The
|
|
38
|
+
* check is `isRxdbRemoteVersionMismatch` from `@tallyui/core`.
|
|
39
|
+
*
|
|
40
|
+
* A worker that crashes mid-call never replies (RxDB `storage-remote`,
|
|
41
|
+
* 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
|
|
42
|
+
*/
|
|
43
|
+
declare function isStorageWorkerFailure(error: unknown): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Wraps a storage so its instances report health on `health$` (ADR-061,
|
|
46
|
+
* following WCPOS). No storage call is ever settled on a clock: a timed-out
|
|
47
|
+
* write may still commit, so a slow write is only flagged as `stalled`, and
|
|
48
|
+
* its promise stays pending until the worker answers. Reads are watched: two
|
|
49
|
+
* consecutive `readWatchdogMs` windows in which reads were pending and no
|
|
50
|
+
* call settled mark the worker `dead` (sticky; the recovery is reload).
|
|
51
|
+
* `createStorageInstance` has no deadline, because the worker and wasm can be
|
|
52
|
+
* slow to download.
|
|
53
|
+
*
|
|
54
|
+
* Instance methods are replaced in place, the way RxDB's own validator wraps
|
|
55
|
+
* `bulkWrite`, so a later wrapper that assigns over ours calls ours, not itself.
|
|
56
|
+
* The `tallyEngine` marker is kept.
|
|
57
|
+
*/
|
|
58
|
+
declare function withStorageWatchdog(storage: RxStorage<any, any>, options?: StorageWatchdogOptions): RxStorage<any, any> & {
|
|
59
|
+
health$: Observable<StorageHealth>;
|
|
60
|
+
};
|
|
61
|
+
|
|
5
62
|
/**
|
|
6
63
|
* The shape of a Tally database — keyed by collection name.
|
|
7
64
|
*/
|
|
@@ -20,22 +77,49 @@ interface CreateDatabaseOptions {
|
|
|
20
77
|
* Create an RxDB database from a connector's schemas.
|
|
21
78
|
*
|
|
22
79
|
* This is the main entry point — give it a connector and it builds
|
|
23
|
-
* the database with the right collections and schemas.
|
|
80
|
+
* the database with the right collections and schemas. A connector with
|
|
81
|
+
* `reconcile.stock` also gets the `stock_levels` overlay collection.
|
|
24
82
|
*
|
|
25
83
|
* ```ts
|
|
26
|
-
* import {
|
|
84
|
+
* import { createWooCommerceConnector } from '@tallyui/connector-woocommerce';
|
|
27
85
|
* import { createTallyDatabase } from '@tallyui/database';
|
|
28
86
|
*
|
|
29
|
-
* const db = await createTallyDatabase({ connector:
|
|
87
|
+
* const db = await createTallyDatabase({ connector: createWooCommerceConnector() });
|
|
30
88
|
* const products = await db.products.find().exec();
|
|
31
89
|
* ```
|
|
32
90
|
*/
|
|
33
91
|
declare function createTallyDatabase(options: CreateDatabaseOptions): Promise<TallyDatabase>;
|
|
92
|
+
/**
|
|
93
|
+
* The storage health of a database on the web engine (ADR-061), so an app can
|
|
94
|
+
* show "saving is slow…" (`stalled`) or "storage stopped, reload" (`dead`).
|
|
95
|
+
* `undefined` for any other storage, which has no watchdog.
|
|
96
|
+
*/
|
|
97
|
+
declare function getStorageHealth(db: TallyDatabase): Observable<StorageHealth> | undefined;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The collection config for a connector schema: the schema plus a `v => null`
|
|
101
|
+
* strategy for every version from 1 to N (`{}` at version 0), so a version
|
|
102
|
+
* bump drops the documents and replication resyncs them (see ConnectorSchemas).
|
|
103
|
+
* Local documents are on: the catalogue reconcile keeps its gate and resume
|
|
104
|
+
* cursor there (#248), since they are never replicated.
|
|
105
|
+
*
|
|
106
|
+
* Use this for any connector collection created outside `createTallyDatabase`
|
|
107
|
+
* (tests, an app's own database). A connector schema above version 0 needs
|
|
108
|
+
* these strategies and the migration plugin, or RxDB throws COL12 or
|
|
109
|
+
* "plugin missing". Never for local-only collections (`stock_levels`,
|
|
110
|
+
* `pos_orders`): a drop would lose local data.
|
|
111
|
+
*/
|
|
112
|
+
declare function connectorCollection<T>(schema: RxJsonSchema<T>): {
|
|
113
|
+
schema: RxJsonSchema<T>;
|
|
114
|
+
migrationStrategies: MigrationStrategies;
|
|
115
|
+
localDocuments: true;
|
|
116
|
+
};
|
|
34
117
|
|
|
35
118
|
/**
|
|
36
119
|
* Returns the appropriate RxDB storage adapter for the current platform.
|
|
37
120
|
*
|
|
38
|
-
* - Web browser:
|
|
121
|
+
* - Web browser: throws with guidance to pass the SQLite-wasm storage
|
|
122
|
+
* explicitly (ADR-061) — there is no default web storage any more.
|
|
39
123
|
* - React Native: throws with guidance to provide SQLite storage explicitly
|
|
40
124
|
* - Node/SSR/test: In-memory
|
|
41
125
|
*
|
|
@@ -43,6 +127,13 @@ declare function createTallyDatabase(options: CreateDatabaseOptions): Promise<Ta
|
|
|
43
127
|
*/
|
|
44
128
|
declare function getStorage(): RxStorage<any, any>;
|
|
45
129
|
|
|
130
|
+
/** ADR-061: the web runs premium SQLite on sqlite-wasm opfs-sahpool; one live tab. */
|
|
131
|
+
declare const WEB_STORAGE_ENGINE: "sqlite-sahpool";
|
|
132
|
+
/** multiInstance each web engine requires: opfs-sahpool holds exclusive OPFS handles, so a second instance cannot exist. */
|
|
133
|
+
declare const REQUIRED_MULTI_INSTANCE_BY_ENGINE: {
|
|
134
|
+
readonly 'sqlite-sahpool': false;
|
|
135
|
+
};
|
|
136
|
+
|
|
46
137
|
interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
47
138
|
collection: RxCollection<RxDocType>;
|
|
48
139
|
adapter: ReplicationAdapter<RxDocType, CheckpointType>;
|
|
@@ -53,13 +144,346 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
|
53
144
|
retryTime?: number;
|
|
54
145
|
/** Start immediately (default: true) */
|
|
55
146
|
autoStart?: boolean;
|
|
147
|
+
/** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
|
|
148
|
+
maxRetryTimeMs?: number;
|
|
56
149
|
}
|
|
150
|
+
/** RxDB's replication state plus the pull notice and a way to restart after a till error. */
|
|
151
|
+
type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
|
|
152
|
+
/** A notice while a till or store error stops the pull; `undefined` otherwise. */
|
|
153
|
+
notice$: Observable<SyncNotice | undefined>;
|
|
154
|
+
/** Clears the notice, the gates and the backoff, and pulls again from the stored checkpoint. */
|
|
155
|
+
resume(): Promise<void>;
|
|
156
|
+
};
|
|
57
157
|
/**
|
|
58
158
|
* Start RxDB replication for a single collection using a ReplicationAdapter.
|
|
59
159
|
*
|
|
60
160
|
* Returns the RxReplicationState which exposes observables for monitoring
|
|
61
161
|
* and methods like cancel(), awaitInSync(), reSync().
|
|
62
162
|
*/
|
|
63
|
-
declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, }: StartReplicationOptions<RxDocType, CheckpointType>):
|
|
163
|
+
declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, maxRetryTimeMs, }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType>;
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* ADR-061: exactly one live tab per store, and a second tab never opens
|
|
167
|
+
* storage. `acquiring` while a hand-over is in flight, `live` while this tab
|
|
168
|
+
* holds the lock, `parked` after handing over, `blocked` when the live tab
|
|
169
|
+
* never answered and the user must close it.
|
|
170
|
+
*/
|
|
171
|
+
type LiveTabState = 'acquiring' | 'live' | 'parked' | 'blocked';
|
|
172
|
+
type LiveTabChannel = Pick<BroadcastChannel, 'postMessage' | 'close'> & {
|
|
173
|
+
onmessage: ((event: {
|
|
174
|
+
data: unknown;
|
|
175
|
+
}) => void) | null;
|
|
176
|
+
};
|
|
177
|
+
interface LiveTabOptions {
|
|
178
|
+
/** Store scope; the lock and channel are named `tally-live-tab:<scope>`. */
|
|
179
|
+
scope: string;
|
|
180
|
+
/** Called on the live tab before it hands over: close the database, stop workers. Awaited. */
|
|
181
|
+
onPark: () => void | Promise<void>;
|
|
182
|
+
/** True while a sale, payment or storage write is in flight; the hand-over waits for false. */
|
|
183
|
+
isBusy?: () => boolean;
|
|
184
|
+
/** Longest the live tab defers a hand-over while busy (default 10_000 ms). */
|
|
185
|
+
maxDeferMs?: number;
|
|
186
|
+
/** How long a new tab waits for the live tab to acknowledge (default 3_000 ms). */
|
|
187
|
+
ackTimeoutMs?: number;
|
|
188
|
+
/** Injection for tests and non-browser hosts; default globalThis.navigator?.locks and globalThis.BroadcastChannel. */
|
|
189
|
+
locks?: Pick<LockManager, 'request'>;
|
|
190
|
+
createChannel?: (name: string) => LiveTabChannel;
|
|
191
|
+
/** Injection for tests; default globalThis. Source of `pagehide`/`pageshow`. */
|
|
192
|
+
events?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
|
|
193
|
+
/** Injection for tests; default Date.now. Wall clock for the busy-defer cap below. */
|
|
194
|
+
now?: () => number;
|
|
195
|
+
}
|
|
196
|
+
interface LiveTabHandle {
|
|
197
|
+
state$: Observable<LiveTabState>;
|
|
198
|
+
/** Ask the live tab to hand over, and take the lock. Used on start and by the parked screen's "Use here" button. */
|
|
199
|
+
takeOver(): Promise<LiveTabState>;
|
|
200
|
+
/** Release the lock and close the channel (sign-out, unmount). */
|
|
201
|
+
stop(): void;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Coordinates one live tab per store (ADR-061) over a Web Lock and a
|
|
205
|
+
* BroadcastChannel, both named `tally-live-tab:<scope>`.
|
|
206
|
+
*
|
|
207
|
+
* On platforms without Web Locks (React Native, Node, tests: `locks` is
|
|
208
|
+
* undefined) a tab is simply live at once, since native and Electron have
|
|
209
|
+
* one window per store.
|
|
210
|
+
*/
|
|
211
|
+
declare function startLiveTab(options: LiveTabOptions): LiveTabHandle;
|
|
212
|
+
|
|
213
|
+
/** Collection holding the stock reconcile overlay (ADR-060). Local only: never replicated. */
|
|
214
|
+
declare const STOCK_LEVELS_COLLECTION = "stock_levels";
|
|
215
|
+
|
|
216
|
+
/** One overlay row: the connector's stock value for one key (Vendure variant id, Medusa inventory item id). */
|
|
217
|
+
interface StockLevelRow {
|
|
218
|
+
id: string;
|
|
219
|
+
/** The value `fetchPages` gave for this key, stored as is. */
|
|
220
|
+
value: unknown;
|
|
221
|
+
/** ISO 8601 time of the pass that wrote the row. */
|
|
222
|
+
updatedAt: string;
|
|
223
|
+
}
|
|
224
|
+
declare const stockLevelsSchema: RxJsonSchema<StockLevelRow>;
|
|
225
|
+
/** Use this whenever you create `stock_levels` yourself: the runner stores its last pass in local documents. */
|
|
226
|
+
declare const stockLevelsCollection: {
|
|
227
|
+
readonly schema: RxJsonSchema<StockLevelRow>;
|
|
228
|
+
readonly localDocuments: true;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
interface StartStockReconcileOptions {
|
|
232
|
+
/** The `stock_levels` collection. The runner writes nothing else. */
|
|
233
|
+
collection: RxCollection<StockLevelRow>;
|
|
234
|
+
adapter: StockReconcileAdapter;
|
|
235
|
+
context: SyncContext;
|
|
236
|
+
/** Time between passes in ms (default: 300000, 5 minutes) */
|
|
237
|
+
intervalMs?: number;
|
|
238
|
+
/** Most pages one pass reads; beyond it the pass is truncated (default: 100) */
|
|
239
|
+
maxPages?: number;
|
|
240
|
+
}
|
|
241
|
+
interface StockReconcileResult {
|
|
242
|
+
pages: number;
|
|
243
|
+
/** Rows inserted or changed */
|
|
244
|
+
written: number;
|
|
245
|
+
/** Rows whose key the backend no longer returns */
|
|
246
|
+
removed: number;
|
|
247
|
+
truncated: boolean;
|
|
248
|
+
/** ISO time of a successful pass; also stored in the `last-pass` local document. */
|
|
249
|
+
completedAt?: string;
|
|
250
|
+
}
|
|
251
|
+
/** The runner's state. `lastCompletedAt` survives restarts; the rest is in memory. */
|
|
252
|
+
interface StockReconcileState {
|
|
253
|
+
lastCompletedAt?: string;
|
|
254
|
+
running: boolean;
|
|
255
|
+
truncated: boolean;
|
|
256
|
+
lastError?: unknown;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Periodically re-read stock into the `stock_levels` overlay collection (ADR-060).
|
|
260
|
+
*
|
|
261
|
+
* Replicated product documents are never written: a local write there makes
|
|
262
|
+
* RxDB's downstream skip the next pulled version of that document.
|
|
263
|
+
*
|
|
264
|
+
* The first pass waits for the interval; the app calls reconcileStock() after
|
|
265
|
+
* first paint and on foreground or resume. A call during a pass queues one
|
|
266
|
+
* follow-up pass (later calls share it), so a change made after the pass
|
|
267
|
+
* read is picked up straight after, not at the next interval. stop() clears
|
|
268
|
+
* the timer and aborts a running pass.
|
|
269
|
+
* A stop during writes leaves earlier chunks written and `last-pass` unchanged.
|
|
270
|
+
* ADR-060: these server-truth passes are idempotent, so the next pass finishes what a stopped pass left.
|
|
271
|
+
*/
|
|
272
|
+
declare function startStockReconcile({ collection, adapter, context, intervalMs, maxPages, }: StartStockReconcileOptions): {
|
|
273
|
+
reconcileStock(): Promise<StockReconcileResult>;
|
|
274
|
+
stop(): void;
|
|
275
|
+
state$: Observable<StockReconcileState>;
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
/** After a pull gap this long the app should call `reconcile()` (see `shouldReconcileAfterGap`). */
|
|
279
|
+
declare const CATALOGUE_OFFLINE_GAP_MS: number;
|
|
280
|
+
/** What a pass did, for the till's sync log (#248 A3). There is no cashier notice. */
|
|
281
|
+
type CatalogueReconcileEvent = {
|
|
282
|
+
type: 'pass-started';
|
|
283
|
+
resumed: boolean;
|
|
284
|
+
} | {
|
|
285
|
+
type: 'refetched';
|
|
286
|
+
count: number;
|
|
287
|
+
keys: string[];
|
|
288
|
+
} | {
|
|
289
|
+
type: 'tombstoned';
|
|
290
|
+
count: number;
|
|
291
|
+
keys: string[];
|
|
292
|
+
} | {
|
|
293
|
+
type: 'kept';
|
|
294
|
+
count: number;
|
|
295
|
+
keys: string[];
|
|
296
|
+
reason: 'unconfirmed' | 'resumed-pass';
|
|
297
|
+
}
|
|
298
|
+
/** `message` tells the store owner, in plain words and without naming a backend, what was kept and why. */
|
|
299
|
+
| {
|
|
300
|
+
type: 'kept';
|
|
301
|
+
count: number;
|
|
302
|
+
keys: string[];
|
|
303
|
+
reason: 'brake';
|
|
304
|
+
message: string;
|
|
305
|
+
} | ({
|
|
306
|
+
type: 'pass-completed';
|
|
307
|
+
} & CatalogueReconcileSummary) | {
|
|
308
|
+
type: 'stopped';
|
|
309
|
+
reason: 'till' | 'store' | 'transient' | 'stopped';
|
|
310
|
+
code?: string;
|
|
311
|
+
} | {
|
|
312
|
+
type: 'skipped';
|
|
313
|
+
reason: 'gate' | 'store';
|
|
314
|
+
};
|
|
315
|
+
interface CatalogueReconcileSummary {
|
|
316
|
+
pages: number;
|
|
317
|
+
/** Listed documents the till holds. */
|
|
318
|
+
compared: number;
|
|
319
|
+
/** Differing or missing documents handed to the pull. */
|
|
320
|
+
refetched: number;
|
|
321
|
+
tombstoned: number;
|
|
322
|
+
/** Deletion candidates kept: unconfirmed, or held by the brake. */
|
|
323
|
+
kept: number;
|
|
324
|
+
/** Local documents the listing did not name, counted in an uninterrupted pass (0 in a resumed one). */
|
|
325
|
+
unlisted: number;
|
|
326
|
+
durationMs: number;
|
|
327
|
+
}
|
|
328
|
+
/** In memory; the gate itself is persisted. `lastResult` is current when `lastResultAt > (lastErrorAt ?? 0)`. */
|
|
329
|
+
interface CatalogueReconcileState {
|
|
330
|
+
running: boolean;
|
|
331
|
+
lastResult?: CatalogueReconcileSummary;
|
|
332
|
+
lastResultAt?: number;
|
|
333
|
+
lastError?: unknown;
|
|
334
|
+
lastErrorAt?: number;
|
|
335
|
+
}
|
|
336
|
+
interface StartCatalogueReconcileOptions<Doc, Cursor = unknown> {
|
|
337
|
+
/** The replicated collection, created with `connectorCollection` (local documents on). Only read. */
|
|
338
|
+
collection: RxCollection<Doc>;
|
|
339
|
+
adapter: CatalogueReconcileAdapter<Doc, Cursor>;
|
|
340
|
+
context: SyncContext;
|
|
341
|
+
/** The app's `() => replication.reSync()`; called once per page that enqueued anything, and once for the tombstones. */
|
|
342
|
+
reSync: () => void;
|
|
343
|
+
/**
|
|
344
|
+
* Requests allowed in any 60 s window (default 30): each page, each `confirmGone` chunk, and the refetch requests
|
|
345
|
+
* each page that enqueued anything causes (the pull's `fetchByIds`: `ceil(n / adapter.refetchBatchSize)`, or 1 when unset).
|
|
346
|
+
*/
|
|
347
|
+
requestsPerMinute?: number;
|
|
348
|
+
/** Most candidates per `confirmGone` call (default 100); each call takes one budget slot. */
|
|
349
|
+
confirmChunk?: number;
|
|
350
|
+
/** Time from the last completed pass to the next (default 86400000, 24 hours). */
|
|
351
|
+
intervalMs?: number;
|
|
352
|
+
/** The first gate check after start (default 120000); then one every `min(1 hour, intervalMs / 2)`, and at least a minute. */
|
|
353
|
+
startDelayMs?: number;
|
|
354
|
+
/** The brake holds deletion candidates above this share of local documents (and above 10), unless `allowMassDelete`. */
|
|
355
|
+
maxDeleteShare?: number;
|
|
356
|
+
allowMassDelete?: boolean;
|
|
357
|
+
log?: (event: CatalogueReconcileEvent) => void;
|
|
358
|
+
now?: () => number;
|
|
359
|
+
/** The local document holding the gate and cursor (default 'catalogue-reconcile'); one per runner on a collection. */
|
|
360
|
+
stateId?: string;
|
|
361
|
+
/** Tests: schedules `fn` after `ms` and returns its cancel (default setTimeout). */
|
|
362
|
+
setTimer?: (fn: () => void, ms: number) => () => void;
|
|
363
|
+
}
|
|
364
|
+
/** True when the last successful pull is older than `offlineGapMs`: the app should then call `reconcile()`. */
|
|
365
|
+
declare function shouldReconcileAfterGap(lastPullAt: number | undefined, now?: number, offlineGapMs?: number): boolean;
|
|
366
|
+
/**
|
|
367
|
+
* The daily catalogue check (#248, ADR-060). Walks the remote listing page by
|
|
368
|
+
* page within a request budget, refetches what differs through the pull, and
|
|
369
|
+
* deletes only after a pass that ran from first page to last in one go, only
|
|
370
|
+
* what `confirmGone` confirms, and only under the mass-delete brake. Never
|
|
371
|
+
* writes the collection; its gate and cursor live in a local document.
|
|
372
|
+
*/
|
|
373
|
+
declare function startCatalogueReconcile<Doc, Cursor = unknown>(options: StartCatalogueReconcileOptions<Doc, Cursor>): {
|
|
374
|
+
reconcile(): void;
|
|
375
|
+
state$: Observable<CatalogueReconcileState>;
|
|
376
|
+
stop(): void;
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
interface StartIdReconcileOptions<Doc> {
|
|
380
|
+
/** The replicated products collection. Read only. */
|
|
381
|
+
collection: RxCollection<Doc>;
|
|
382
|
+
adapter: IdReconcileAdapter<Doc>;
|
|
383
|
+
context: SyncContext;
|
|
384
|
+
/** The app's `() => replication.reSync()`. */
|
|
385
|
+
reSync: () => void;
|
|
386
|
+
/** Delay before the first gate check (default 5000); `null` skips it and checks hourly. */
|
|
387
|
+
startDelayMs?: number | null;
|
|
388
|
+
/** Time from the last completed pass to the next (default 86400000, 24 hours). */
|
|
389
|
+
intervalMs?: number;
|
|
390
|
+
/** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
|
|
391
|
+
maxPages?: number;
|
|
392
|
+
/**
|
|
393
|
+
* The brake applies once tombstones exceed this share of local
|
|
394
|
+
* products (default 0.2), unless `allowMassDelete` is set.
|
|
395
|
+
*/
|
|
396
|
+
maxDeleteShare?: number;
|
|
397
|
+
/** Explicit override for a genuine purge; disables the mass-delete brake. */
|
|
398
|
+
allowMassDelete?: boolean;
|
|
399
|
+
/** The local document holding this runner's gate (default 'id-reconcile'). */
|
|
400
|
+
stateId?: string;
|
|
401
|
+
}
|
|
402
|
+
/** `truncated` is always false now that no page cap applies. */
|
|
403
|
+
interface IdReconcileResult {
|
|
404
|
+
pages: number;
|
|
405
|
+
queued: number;
|
|
406
|
+
truncated: boolean;
|
|
407
|
+
braked: boolean;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Compares live product/variant ids against the local `products` collection
|
|
411
|
+
* and queues disagreeing documents for the collection's pull (ADR-060), as a
|
|
412
|
+
* wrapper over the catalogue runner (#248): a product whose variant ids differ
|
|
413
|
+
* is refetched page by page; a product missing remotely is queued for deletion
|
|
414
|
+
* only after an uninterrupted pass and under the mass-delete brake. Passes
|
|
415
|
+
* follow the persisted daily gate within a request budget. A call during a
|
|
416
|
+
* pass queues one follow-up pass (later calls share it).
|
|
417
|
+
*/
|
|
418
|
+
declare function startIdReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartIdReconcileOptions<Doc>): {
|
|
419
|
+
reconcileIds(): Promise<IdReconcileResult>;
|
|
420
|
+
stop(): void;
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
interface StartFingerprintReconcileOptions<Doc> {
|
|
424
|
+
/** The replicated collection. Read only. */
|
|
425
|
+
collection: RxCollection<Doc>;
|
|
426
|
+
adapter: FingerprintReconcileAdapter<Doc>;
|
|
427
|
+
context: SyncContext;
|
|
428
|
+
/** The app's `() => replication.reSync()`. */
|
|
429
|
+
reSync: () => void;
|
|
430
|
+
/** Delay before the first gate check; `null` (default) skips it and checks hourly. */
|
|
431
|
+
startDelayMs?: number | null;
|
|
432
|
+
/** Time from the last completed pass to the next (default 86400000, 24 hours). */
|
|
433
|
+
intervalMs?: number;
|
|
434
|
+
/** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
|
|
435
|
+
maxPages?: number;
|
|
436
|
+
/** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
|
|
437
|
+
now?: () => number;
|
|
438
|
+
/**
|
|
439
|
+
* The local document holding this runner's gate (default 'fingerprint-reconcile').
|
|
440
|
+
* Two fingerprint runners on one collection (prices and calculated prices) each need their own.
|
|
441
|
+
*/
|
|
442
|
+
stateId?: string;
|
|
443
|
+
}
|
|
444
|
+
interface FingerprintReconcileResult {
|
|
445
|
+
pages: number;
|
|
446
|
+
compared: number;
|
|
447
|
+
queued: number;
|
|
448
|
+
/** Always false now that no page cap applies. */
|
|
449
|
+
truncated: boolean;
|
|
450
|
+
/**
|
|
451
|
+
* Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
|
|
452
|
+
* pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
|
|
453
|
+
* the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
|
|
454
|
+
* correctly reports everything as unreported.
|
|
455
|
+
* For `calculatedPrices`, the products the sales channel does not list, which are not sellable here. A channel
|
|
456
|
+
* misconfiguration shows up as a large number, not a silent empty till.
|
|
457
|
+
*/
|
|
458
|
+
unreported: number;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* The runner's state; entirely in memory. The result is current only when
|
|
462
|
+
* `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
|
|
463
|
+
* as stale. See `isFingerprintResultCurrent`.
|
|
464
|
+
*/
|
|
465
|
+
interface FingerprintReconcileState {
|
|
466
|
+
running: boolean;
|
|
467
|
+
lastResult?: FingerprintReconcileResult;
|
|
468
|
+
lastResultAt?: number;
|
|
469
|
+
lastError?: unknown;
|
|
470
|
+
lastErrorAt?: number;
|
|
471
|
+
}
|
|
472
|
+
/** True when `state.lastResult` is current, i.e. newer than the last failure, if any. */
|
|
473
|
+
declare function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean;
|
|
474
|
+
/**
|
|
475
|
+
* Compares a remote fingerprint per product against the local `collection`
|
|
476
|
+
* and queues disagreeing products for the collection's pull (ADR-060), as a
|
|
477
|
+
* wrapper over the catalogue runner (#248). Never deletes: every entry is
|
|
478
|
+
* `refreshOnly`, and a product the remote side doesn't report is only counted
|
|
479
|
+
* as `unreported`. Passes follow the persisted daily gate within a request
|
|
480
|
+
* budget; the app may still call `reconcile()` on demand. A call during a pass
|
|
481
|
+
* queues one follow-up pass (later calls share it).
|
|
482
|
+
*/
|
|
483
|
+
declare function startFingerprintReconcile<Doc>({ adapter, reSync, startDelayMs, maxPages: _ignored, stateId, ...options }: StartFingerprintReconcileOptions<Doc>): {
|
|
484
|
+
reconcile(): Promise<FingerprintReconcileResult>;
|
|
485
|
+
stop(): void;
|
|
486
|
+
state$: Observable<FingerprintReconcileState>;
|
|
487
|
+
};
|
|
64
488
|
|
|
65
|
-
export { type CreateDatabaseOptions, type StartReplicationOptions, type TallyDatabase, createTallyDatabase, getStorage, startReplication };
|
|
489
|
+
export { CATALOGUE_OFFLINE_GAP_MS, type CatalogueReconcileEvent, type CatalogueReconcileState, type CatalogueReconcileSummary, type CreateDatabaseOptions, type FingerprintReconcileResult, type FingerprintReconcileState, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, REQUIRED_MULTI_INSTANCE_BY_ENGINE, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, type StartCatalogueReconcileOptions, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type TallyDatabase, type TallyReplicationState, WEB_STORAGE_ENGINE, connectorCollection, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isStorageWorkerFailure, shouldReconcileAfterGap, startCatalogueReconcile, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, stockLevelsCollection, stockLevelsSchema, withStorageWatchdog };
|