@tallyui/database 1.0.0 → 2.0.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 +304 -5
- package/dist/index.js +626 -20
- package/package.json +9 -3
- package/src/connector-collection.ts +20 -0
- package/src/create-db.ts +54 -10
- package/src/engine.ts +5 -0
- package/src/fingerprint-reconcile.ts +158 -0
- package/src/id-reconcile.ts +131 -0
- package/src/index.ts +18 -1
- package/src/live-tab.ts +280 -0
- package/src/pass-queue.ts +19 -0
- package/src/reconcile.ts +150 -0
- package/src/replication.ts +8 -1
- package/src/stock-levels.ts +32 -0
- package/src/storage-watchdog.ts +134 -0
- package/src/storage.ts +11 -5
- package/src/replication.test.ts +0 -97
- package/src/storage.test.ts +0 -19
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/database",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -15,15 +15,21 @@
|
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
17
|
"dist",
|
|
18
|
-
"src"
|
|
18
|
+
"src",
|
|
19
|
+
"!src/**/*.test.ts"
|
|
19
20
|
],
|
|
20
21
|
"license": "MIT",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/TallyUI/tallyui.git",
|
|
25
|
+
"directory": "packages/database"
|
|
26
|
+
},
|
|
21
27
|
"dependencies": {
|
|
22
28
|
"rxdb": "16.21.1",
|
|
23
29
|
"rxjs": "7.8.2"
|
|
24
30
|
},
|
|
25
31
|
"peerDependencies": {
|
|
26
|
-
"@tallyui/core": "
|
|
32
|
+
"@tallyui/core": "2.0.0"
|
|
27
33
|
},
|
|
28
34
|
"scripts": {
|
|
29
35
|
"build": "tsup",
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { addRxPlugin, type MigrationStrategies, type RxJsonSchema } from 'rxdb';
|
|
2
|
+
import { RxDBMigrationSchemaPlugin } from 'rxdb/plugins/migration-schema';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The collection config for a connector schema: the schema plus a `v => null`
|
|
6
|
+
* strategy for every version from 1 to N (`{}` at version 0), so a version
|
|
7
|
+
* bump drops the documents and replication resyncs them (see ConnectorSchemas).
|
|
8
|
+
*
|
|
9
|
+
* Use this for any connector collection created outside `createTallyDatabase`
|
|
10
|
+
* (tests, an app's own database). A connector schema above version 0 needs
|
|
11
|
+
* these strategies and the migration plugin, or RxDB throws COL12 or
|
|
12
|
+
* "plugin missing". Never for local-only collections (`stock_levels`,
|
|
13
|
+
* `pos_orders`): a drop would lose local data.
|
|
14
|
+
*/
|
|
15
|
+
export function connectorCollection<T>(schema: RxJsonSchema<T>): { schema: RxJsonSchema<T>; migrationStrategies: MigrationStrategies } {
|
|
16
|
+
// addRxPlugin ignores a plugin it already has.
|
|
17
|
+
addRxPlugin(RxDBMigrationSchemaPlugin);
|
|
18
|
+
const migrationStrategies = Object.fromEntries(Array.from({ length: schema.version }, (_, i) => [i + 1, () => null]));
|
|
19
|
+
return { schema, migrationStrategies };
|
|
20
|
+
}
|
package/src/create-db.ts
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
import { createRxDatabase, addRxPlugin, type RxDatabase, type RxCollection } from 'rxdb';
|
|
1
|
+
import { createRxDatabase, addRxPlugin, type MigrationStrategies, type RxDatabase, type RxCollection } from 'rxdb';
|
|
2
|
+
import type { Observable } from 'rxjs';
|
|
2
3
|
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
|
|
4
|
+
import { RxDBLocalDocumentsPlugin } from 'rxdb/plugins/local-documents';
|
|
3
5
|
import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';
|
|
6
|
+
import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';
|
|
4
7
|
|
|
5
8
|
import type { TallyConnector } from '@tallyui/core';
|
|
6
9
|
|
|
10
|
+
import { connectorCollection } from './connector-collection';
|
|
11
|
+
import { STOCK_LEVELS_COLLECTION, stockLevelsCollection } from './stock-levels';
|
|
12
|
+
import { WEB_STORAGE_ENGINE } from './engine';
|
|
13
|
+
import { withStorageWatchdog, type StorageHealth } from './storage-watchdog';
|
|
14
|
+
|
|
15
|
+
const DEV_MODE = process.env.NODE_ENV !== 'production';
|
|
16
|
+
addRxPlugin(RxDBLocalDocumentsPlugin);
|
|
17
|
+
|
|
7
18
|
// Enable dev mode in non-production
|
|
8
|
-
if (
|
|
19
|
+
if (DEV_MODE) {
|
|
9
20
|
addRxPlugin(RxDBDevModePlugin);
|
|
10
21
|
}
|
|
11
22
|
|
|
@@ -29,7 +40,8 @@ export interface CreateDatabaseOptions {
|
|
|
29
40
|
* Create an RxDB database from a connector's schemas.
|
|
30
41
|
*
|
|
31
42
|
* This is the main entry point — give it a connector and it builds
|
|
32
|
-
* the database with the right collections and schemas.
|
|
43
|
+
* the database with the right collections and schemas. A connector with
|
|
44
|
+
* `reconcile.stock` also gets the `stock_levels` overlay collection.
|
|
33
45
|
*
|
|
34
46
|
* ```ts
|
|
35
47
|
* import { woocommerceConnector } from '@tallyui/connector-woocommerce';
|
|
@@ -40,26 +52,58 @@ export interface CreateDatabaseOptions {
|
|
|
40
52
|
* ```
|
|
41
53
|
*/
|
|
42
54
|
export async function createTallyDatabase(options: CreateDatabaseOptions): Promise<TallyDatabase> {
|
|
55
|
+
if ((options as { multiInstance?: unknown }).multiInstance === true) throw new Error('multiInstance: true is unsupported: TallyUI databases are single-instance (ADR-061).');
|
|
43
56
|
const {
|
|
44
57
|
connector,
|
|
45
58
|
name = `tally_${connector.id}`,
|
|
46
59
|
storage = getRxStorageMemory(),
|
|
47
60
|
} = options;
|
|
48
61
|
|
|
62
|
+
// ADR-061's storage watchdog applies only to the pinned web engine; every other storage is untouched.
|
|
63
|
+
const watched = storage?.tallyEngine === WEB_STORAGE_ENGINE ? withStorageWatchdog(storage) : undefined;
|
|
64
|
+
const effectiveStorage = watched ?? storage;
|
|
65
|
+
|
|
66
|
+
const collectionConfigs: Record<string, { schema: any; localDocuments?: boolean; migrationStrategies?: MigrationStrategies }> = {};
|
|
67
|
+
for (const [collectionName, schema] of Object.entries(connector.schemas)) {
|
|
68
|
+
// A connector schema's version bump drops every document (see ConnectorSchemas);
|
|
69
|
+
// startReplication's new identifier then resyncs them. autoMigrate stays on.
|
|
70
|
+
collectionConfigs[collectionName] = connectorCollection(schema);
|
|
71
|
+
}
|
|
72
|
+
// The stock reconcile overlay (ADR-060): local only, never replicated. Its
|
|
73
|
+
// local documents hold the time of the last successful pass. It gets no
|
|
74
|
+
// migration strategies and must stay at version 0, since a drop would lose
|
|
75
|
+
// local data. `pos_orders` is local too; `@tallyui/pos` creates it, not this.
|
|
76
|
+
if (connector.reconcile?.stock) {
|
|
77
|
+
if (STOCK_LEVELS_COLLECTION in collectionConfigs) {
|
|
78
|
+
throw new Error(`Connector "${connector.id}" defines a "${STOCK_LEVELS_COLLECTION}" collection; that name is reserved for the stock reconcile overlay.`);
|
|
79
|
+
}
|
|
80
|
+
collectionConfigs[STOCK_LEVELS_COLLECTION] = stockLevelsCollection;
|
|
81
|
+
}
|
|
82
|
+
|
|
49
83
|
const db = await createRxDatabase({
|
|
50
84
|
name,
|
|
51
|
-
storage,
|
|
85
|
+
// Dev mode refuses storage without a schema validator (RxDB error DVM1),
|
|
86
|
+
// and validating is what makes dev mode catch bad connector documents.
|
|
87
|
+
storage: DEV_MODE ? wrappedValidateAjvStorage({ storage: effectiveStorage }) : effectiveStorage,
|
|
52
88
|
multiInstance: false,
|
|
53
|
-
|
|
89
|
+
// RxDB rejects this outside dev mode (DB9); in dev it lets hot reload re-create the same database.
|
|
90
|
+
ignoreDuplicate: DEV_MODE,
|
|
54
91
|
});
|
|
55
92
|
|
|
56
|
-
|
|
57
|
-
const collectionConfigs: Record<string, { schema: any }> = {};
|
|
58
|
-
for (const [collectionName, schema] of Object.entries(connector.schemas)) {
|
|
59
|
-
collectionConfigs[collectionName] = { schema };
|
|
60
|
-
}
|
|
93
|
+
if (watched) healthByDatabase.set(db, watched.health$);
|
|
61
94
|
|
|
62
95
|
await db.addCollections(collectionConfigs);
|
|
63
96
|
|
|
64
97
|
return db as TallyDatabase;
|
|
65
98
|
}
|
|
99
|
+
|
|
100
|
+
const healthByDatabase = new WeakMap<object, Observable<StorageHealth>>();
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The storage health of a database on the web engine (ADR-061), so an app can
|
|
104
|
+
* show "saving is slow…" (`stalled`) or "storage stopped, reload" (`dead`).
|
|
105
|
+
* `undefined` for any other storage, which has no watchdog.
|
|
106
|
+
*/
|
|
107
|
+
export function getStorageHealth(db: TallyDatabase): Observable<StorageHealth> | undefined {
|
|
108
|
+
return healthByDatabase.get(db);
|
|
109
|
+
}
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** ADR-061: the web runs premium SQLite on sqlite-wasm opfs-sahpool; one live tab. */
|
|
2
|
+
export const WEB_STORAGE_ENGINE = 'sqlite-sahpool' as const;
|
|
3
|
+
|
|
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;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { RxCollection } from 'rxdb';
|
|
2
|
+
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
3
|
+
|
|
4
|
+
import type { FingerprintReconcileAdapter, SyncContext } from '@tallyui/core';
|
|
5
|
+
import { readFresh } from '@tallyui/core/rxdb';
|
|
6
|
+
|
|
7
|
+
import { createPassQueue } from './pass-queue';
|
|
8
|
+
|
|
9
|
+
export interface StartFingerprintReconcileOptions<Doc> {
|
|
10
|
+
/** The replicated collection. Read only. */
|
|
11
|
+
collection: RxCollection<Doc>;
|
|
12
|
+
adapter: FingerprintReconcileAdapter<Doc>;
|
|
13
|
+
context: SyncContext;
|
|
14
|
+
/** The app's `() => replication.reSync()`. */
|
|
15
|
+
reSync: () => void;
|
|
16
|
+
/** Delay before the first pass; `null` (default) skips it, since this runner is meant as a nightly backstop. */
|
|
17
|
+
startDelayMs?: number | null;
|
|
18
|
+
/** Time between passes in ms (default 86400000, 24 hours). */
|
|
19
|
+
intervalMs?: number;
|
|
20
|
+
/** Pages read before a pass is truncated (default 100). */
|
|
21
|
+
maxPages?: number;
|
|
22
|
+
/** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
|
|
23
|
+
now?: () => number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface FingerprintReconcileResult {
|
|
27
|
+
pages: number;
|
|
28
|
+
compared: number;
|
|
29
|
+
queued: number;
|
|
30
|
+
truncated: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Local products the remote side did not report in a complete pass (they are skipped); 0 on a truncated or failed
|
|
33
|
+
* pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
|
|
34
|
+
* the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
|
|
35
|
+
* correctly reports everything as unreported.
|
|
36
|
+
* For `calculatedPrices`, the products the sales channel does not list, which are not sellable here. A channel
|
|
37
|
+
* misconfiguration shows up as a large number, not a silent empty till.
|
|
38
|
+
*/
|
|
39
|
+
unreported: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The runner's state; entirely in memory. The result is current only when
|
|
44
|
+
* `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
|
|
45
|
+
* as stale. See `isFingerprintResultCurrent`.
|
|
46
|
+
*/
|
|
47
|
+
export interface FingerprintReconcileState {
|
|
48
|
+
running: boolean;
|
|
49
|
+
lastResult?: FingerprintReconcileResult;
|
|
50
|
+
lastResultAt?: number;
|
|
51
|
+
lastError?: unknown;
|
|
52
|
+
lastErrorAt?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** True when `state.lastResult` is current, i.e. newer than the last failure, if any. */
|
|
56
|
+
export function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean {
|
|
57
|
+
return state.lastResultAt !== undefined && state.lastResultAt > (state.lastErrorAt ?? 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 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.
|
|
70
|
+
*/
|
|
71
|
+
export function startFingerprintReconcile<Doc>({
|
|
72
|
+
collection, adapter, context, reSync, startDelayMs = null, intervalMs = 86_400_000, maxPages = 100, now = Date.now,
|
|
73
|
+
}: StartFingerprintReconcileOptions<Doc>): {
|
|
74
|
+
reconcile(): Promise<FingerprintReconcileResult>;
|
|
75
|
+
stop(): void;
|
|
76
|
+
state$: Observable<FingerprintReconcileState>;
|
|
77
|
+
} {
|
|
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);
|
|
156
|
+
|
|
157
|
+
return { reconcile, stop, state$: state.asObservable() };
|
|
158
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { RxCollection } from 'rxdb';
|
|
2
|
+
import type { IdReconcileAdapter, SyncContext } from '@tallyui/core';
|
|
3
|
+
import { readFresh } from '@tallyui/core/rxdb';
|
|
4
|
+
|
|
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;
|
|
12
|
+
|
|
13
|
+
export interface StartIdReconcileOptions<Doc> {
|
|
14
|
+
/** The replicated products collection. Read only. */
|
|
15
|
+
collection: RxCollection<Doc>;
|
|
16
|
+
adapter: IdReconcileAdapter<Doc>;
|
|
17
|
+
context: SyncContext;
|
|
18
|
+
/** The app's `() => replication.reSync()`. */
|
|
19
|
+
reSync: () => void;
|
|
20
|
+
/** Delay before the first pass (default 5000); `null` skips it. */
|
|
21
|
+
startDelayMs?: number | null;
|
|
22
|
+
/** Time between passes in ms (default 86400000, 24 hours). */
|
|
23
|
+
intervalMs?: number;
|
|
24
|
+
/** Pages read before a pass is truncated (default 100). */
|
|
25
|
+
maxPages?: number;
|
|
26
|
+
/**
|
|
27
|
+
* The brake applies once would-be tombstones exceed this share of local
|
|
28
|
+
* products (default 0.2), unless `allowMassDelete` is set.
|
|
29
|
+
*/
|
|
30
|
+
maxDeleteShare?: number;
|
|
31
|
+
/** Explicit override for a genuine purge; disables the mass-delete brake. */
|
|
32
|
+
allowMassDelete?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface IdReconcileResult { pages: number; queued: number; truncated: boolean; braked: boolean }
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 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.
|
|
46
|
+
*/
|
|
47
|
+
export function startIdReconcile<Doc>({
|
|
48
|
+
collection, adapter, context, reSync, startDelayMs = 5_000, intervalMs = 86_400_000, maxPages = 100,
|
|
49
|
+
maxDeleteShare = 0.2, allowMassDelete = false,
|
|
50
|
+
}: 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
|
+
|
|
130
|
+
return { reconcileIds, stop };
|
|
131
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
|
-
export { createTallyDatabase } from './create-db';
|
|
1
|
+
export { createTallyDatabase, getStorageHealth } from './create-db';
|
|
2
2
|
export type { TallyDatabase, CreateDatabaseOptions } from './create-db';
|
|
3
|
+
export { connectorCollection } from './connector-collection';
|
|
3
4
|
|
|
4
5
|
export { getStorage } from './storage';
|
|
5
6
|
|
|
7
|
+
export { WEB_STORAGE_ENGINE, REQUIRED_MULTI_INSTANCE_BY_ENGINE } from './engine';
|
|
8
|
+
export { STORAGE_WRITE_STALL_MS, STORAGE_READ_WATCHDOG_MS, isStorageWorkerFailure, withStorageWatchdog } from './storage-watchdog';
|
|
9
|
+
export type { StorageHealth, StorageWatchdogOptions } from './storage-watchdog';
|
|
10
|
+
|
|
6
11
|
export { startReplication } from './replication';
|
|
7
12
|
export type { StartReplicationOptions } from './replication';
|
|
13
|
+
|
|
14
|
+
export { startLiveTab } from './live-tab';
|
|
15
|
+
export type { LiveTabState, LiveTabOptions, LiveTabHandle } from './live-tab';
|
|
16
|
+
|
|
17
|
+
export { startStockReconcile } from './reconcile';
|
|
18
|
+
export type { StartStockReconcileOptions, StockReconcileResult, StockReconcileState } from './reconcile';
|
|
19
|
+
export { startIdReconcile } from './id-reconcile';
|
|
20
|
+
export type { StartIdReconcileOptions, IdReconcileResult } from './id-reconcile';
|
|
21
|
+
export { startFingerprintReconcile, isFingerprintResultCurrent } from './fingerprint-reconcile';
|
|
22
|
+
export type { StartFingerprintReconcileOptions, FingerprintReconcileResult, FingerprintReconcileState } from './fingerprint-reconcile';
|
|
23
|
+
export { STOCK_LEVELS_COLLECTION, STOCK_LEVELS_LAST_PASS, stockLevelsCollection, stockLevelsSchema } from './stock-levels';
|
|
24
|
+
export type { StockLevelRow } from './stock-levels';
|