@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/src/reconcile.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type { RxCollection } from 'rxdb';
|
|
2
|
+
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
3
|
+
|
|
4
|
+
import { STOCK_LEVELS_LAST_PASS, type StockReconcileAdapter, type SyncContext } from '@tallyui/core';
|
|
5
|
+
|
|
6
|
+
import { BACKGROUND_CHUNK_SIZE, pauseBetweenChunks, readFreshInChunks } from './chunks';
|
|
7
|
+
import { createPassQueue } from './pass-queue';
|
|
8
|
+
import type { StockLevelRow } from './stock-levels';
|
|
9
|
+
|
|
10
|
+
export interface StartStockReconcileOptions {
|
|
11
|
+
/** The `stock_levels` collection. The runner writes nothing else. */
|
|
12
|
+
collection: RxCollection<StockLevelRow>;
|
|
13
|
+
adapter: StockReconcileAdapter;
|
|
14
|
+
context: SyncContext;
|
|
15
|
+
/** Time between passes in ms (default: 300000, 5 minutes) */
|
|
16
|
+
intervalMs?: number;
|
|
17
|
+
/** Most pages one pass reads; beyond it the pass is truncated (default: 100) */
|
|
18
|
+
maxPages?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface StockReconcileResult {
|
|
22
|
+
pages: number;
|
|
23
|
+
/** Rows inserted or changed */
|
|
24
|
+
written: number;
|
|
25
|
+
/** Rows whose key the backend no longer returns */
|
|
26
|
+
removed: number;
|
|
27
|
+
truncated: boolean;
|
|
28
|
+
/** ISO time of a successful pass; also stored in the `last-pass` local document. */
|
|
29
|
+
completedAt?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The runner's state. `lastCompletedAt` survives restarts; the rest is in memory. */
|
|
33
|
+
export interface StockReconcileState {
|
|
34
|
+
lastCompletedAt?: string;
|
|
35
|
+
running: boolean;
|
|
36
|
+
truncated: boolean;
|
|
37
|
+
lastError?: unknown;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Periodically re-read stock into the `stock_levels` overlay collection (ADR-060).
|
|
42
|
+
*
|
|
43
|
+
* Replicated product documents are never written: a local write there makes
|
|
44
|
+
* RxDB's downstream skip the next pulled version of that document.
|
|
45
|
+
*
|
|
46
|
+
* The first pass waits for the interval; the app calls reconcileStock() after
|
|
47
|
+
* first paint and on foreground or resume. A call during a pass queues one
|
|
48
|
+
* follow-up pass (later calls share it), so a change made after the pass
|
|
49
|
+
* read is picked up straight after, not at the next interval. stop() clears
|
|
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.
|
|
53
|
+
*/
|
|
54
|
+
export function startStockReconcile({
|
|
55
|
+
collection,
|
|
56
|
+
adapter,
|
|
57
|
+
context,
|
|
58
|
+
intervalMs = 300_000,
|
|
59
|
+
maxPages = 100,
|
|
60
|
+
}: StartStockReconcileOptions): {
|
|
61
|
+
reconcileStock(): Promise<StockReconcileResult>;
|
|
62
|
+
stop(): void;
|
|
63
|
+
state$: Observable<StockReconcileState>;
|
|
64
|
+
} {
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const { signal } = controller;
|
|
67
|
+
// React Native's AbortController polyfill has no throwIfAborted() and may have no reason.
|
|
68
|
+
const checkAborted = () => {
|
|
69
|
+
if (signal.aborted) throw signal.reason ?? new Error('Stock reconcile stopped');
|
|
70
|
+
};
|
|
71
|
+
const state = new BehaviorSubject<StockReconcileState>({ running: false, truncated: false });
|
|
72
|
+
const update = (patch: Partial<StockReconcileState>) => state.next({ ...state.value, ...patch });
|
|
73
|
+
// Every pass awaits this, so a collection without local documents (RxDB LD8) fails before fetching.
|
|
74
|
+
const lastPass = collection.getLocal<{ completedAt: string }>(STOCK_LEVELS_LAST_PASS).catch((error) => {
|
|
75
|
+
if (error?.code !== 'LD8') return null;
|
|
76
|
+
throw new Error(`Create "${collection.name}" with stockLevelsCollection (localDocuments: true); stock reconcile stores its last pass there.`, { cause: error });
|
|
77
|
+
});
|
|
78
|
+
// Seed "as of" from the last successful pass before this start, unless a pass already set it.
|
|
79
|
+
lastPass.then((doc) => {
|
|
80
|
+
if (doc && !state.value.lastCompletedAt) update({ lastCompletedAt: doc.get('completedAt') });
|
|
81
|
+
}, () => {});
|
|
82
|
+
|
|
83
|
+
const pass = async (): Promise<StockReconcileResult> => {
|
|
84
|
+
checkAborted();
|
|
85
|
+
await lastPass;
|
|
86
|
+
// Phase 1: read every page. A fetch that throws, is truncated or is
|
|
87
|
+
// aborted writes nothing, so a partial snapshot never removes rows.
|
|
88
|
+
const stock = new Map<string, unknown>();
|
|
89
|
+
let pages = 0;
|
|
90
|
+
for await (const page of adapter.fetchPages({ ...context, signal })) {
|
|
91
|
+
checkAborted();
|
|
92
|
+
if (pages === maxPages) {
|
|
93
|
+
console.warn(`Stock reconcile stopped at the ${maxPages}-page limit; nothing was written.`);
|
|
94
|
+
return { pages, written: 0, removed: 0, truncated: true };
|
|
95
|
+
}
|
|
96
|
+
pages++;
|
|
97
|
+
for (const [key, value] of page) stock.set(key, value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Phase 2: write only rows that changed; remove keys the backend no longer returns.
|
|
101
|
+
const rows: StockLevelRow[] = [];
|
|
102
|
+
for await (const chunk of readFreshInChunks(collection)) {
|
|
103
|
+
checkAborted();
|
|
104
|
+
rows.push(...chunk);
|
|
105
|
+
}
|
|
106
|
+
const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
|
|
107
|
+
const updatedAt = new Date().toISOString();
|
|
108
|
+
const upserts = [...stock]
|
|
109
|
+
.filter(([id, value]) => stored.get(id) !== JSON.stringify(value))
|
|
110
|
+
.map(([id, value]) => ({ id, value, updatedAt }));
|
|
111
|
+
const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
|
|
112
|
+
|
|
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));
|
|
118
|
+
if (error.length) throw error[0];
|
|
119
|
+
wroteChunk = true;
|
|
120
|
+
}
|
|
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));
|
|
125
|
+
if (error.length) throw error[0];
|
|
126
|
+
wroteChunk = true;
|
|
127
|
+
}
|
|
128
|
+
// Rows written by this pass carry the same time.
|
|
129
|
+
const completedAt = updatedAt;
|
|
130
|
+
checkAborted();
|
|
131
|
+
await collection.upsertLocal(STOCK_LEVELS_LAST_PASS, { completedAt });
|
|
132
|
+
return { pages, written: upserts.length, removed: removals.length, truncated: false, completedAt };
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const tracked = async (): Promise<StockReconcileResult> => {
|
|
136
|
+
update({ running: true });
|
|
137
|
+
try {
|
|
138
|
+
const result = await pass();
|
|
139
|
+
if (result.truncated) update({ running: false, truncated: true });
|
|
140
|
+
else state.next({ running: false, truncated: false, lastCompletedAt: result.completedAt });
|
|
141
|
+
return result;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
update({ running: false, lastError: error });
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const reconcileStock = createPassQueue(tracked);
|
|
148
|
+
const timer = setInterval(() => {
|
|
149
|
+
reconcileStock().catch((error) => console.warn('Stock reconcile failed:', error));
|
|
150
|
+
}, intervalMs);
|
|
151
|
+
|
|
152
|
+
// stop() and an abort of context.signal both end the runner for good.
|
|
153
|
+
const stop = () => {
|
|
154
|
+
clearInterval(timer);
|
|
155
|
+
context.signal?.removeEventListener('abort', stop);
|
|
156
|
+
controller.abort();
|
|
157
|
+
state.complete();
|
|
158
|
+
};
|
|
159
|
+
if (context.signal?.aborted) stop();
|
|
160
|
+
else context.signal?.addEventListener('abort', stop);
|
|
161
|
+
|
|
162
|
+
return { reconcileStock, stop, state$: state.asObservable() };
|
|
163
|
+
}
|
package/src/replication.ts
CHANGED
|
@@ -1,7 +1,50 @@
|
|
|
1
1
|
import { replicateRxCollection, type RxReplicationState } from 'rxdb/plugins/replication';
|
|
2
2
|
import type { RxCollection } from 'rxdb';
|
|
3
|
+
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
3
4
|
|
|
4
|
-
import type
|
|
5
|
+
import { errorKind, type ReplicationAdapter, type SyncContext, type SyncNotice } from '@tallyui/core';
|
|
6
|
+
|
|
7
|
+
/** The longest backoff between pull retries, and a store error's wait: 5 minutes. */
|
|
8
|
+
export const MAX_RETRY_TIME_MS = 5 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The longest wait an error's `retryAfterMs` can ask for: 1 hour. `setTimeout`
|
|
12
|
+
* fires at once past about 24.8 days and a NaN wait crashes RxDB's loop, so only
|
|
13
|
+
* a finite `retryAfterMs >= 0` counts, and never beyond this.
|
|
14
|
+
*/
|
|
15
|
+
export const MAX_RETRY_AFTER_MS = 60 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
// A timer can fire a few milliseconds early against Date.now(): a store retry
|
|
18
|
+
// this close to its time is on time, not an early call to hold back.
|
|
19
|
+
const TIMER_SLACK_MS = 10;
|
|
20
|
+
|
|
21
|
+
declare const __DEV__: boolean | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* React Native's __DEV__, else NODE_ENV (a bundler replaces the literal `process.env.NODE_ENV`); false where neither
|
|
24
|
+
* exists. Read at each start so that a test can switch it.
|
|
25
|
+
*/
|
|
26
|
+
const isDev = () => {
|
|
27
|
+
if (typeof __DEV__ !== 'undefined') return Boolean(__DEV__);
|
|
28
|
+
try { return process.env.NODE_ENV !== 'production'; } catch { return false; }
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// The collection each adapter object replicates into while live (#307). One connector instance
|
|
32
|
+
// replicating into two databases at once is the static-export misuse: a shared reconcile feed.
|
|
33
|
+
const liveInto = new WeakMap<object, RxCollection<any>>();
|
|
34
|
+
const warned = new WeakSet<object>();
|
|
35
|
+
|
|
36
|
+
/** Development only: warns once per adapter started on a second collection while the first is live. Never throws. */
|
|
37
|
+
function watchShared(adapter: object, collection: RxCollection<any>): () => void {
|
|
38
|
+
if (!isDev()) return () => {};
|
|
39
|
+
const live = liveInto.get(adapter);
|
|
40
|
+
if (!live) liveInto.set(adapter, collection);
|
|
41
|
+
else if (live !== collection && !warned.has(adapter)) {
|
|
42
|
+
warned.add(adapter);
|
|
43
|
+
console.warn('TallyUI: one connector instance is replicating into two databases. Build a connector per store session '
|
|
44
|
+
+ '(createXConnector()); a shared instance can leak queued reconcile work across stores.');
|
|
45
|
+
}
|
|
46
|
+
return () => { if (liveInto.get(adapter) === collection) liveInto.delete(adapter); };
|
|
47
|
+
}
|
|
5
48
|
|
|
6
49
|
export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
7
50
|
collection: RxCollection<RxDocType>;
|
|
@@ -13,6 +56,32 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
|
|
|
13
56
|
retryTime?: number;
|
|
14
57
|
/** Start immediately (default: true) */
|
|
15
58
|
autoStart?: boolean;
|
|
59
|
+
/** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
|
|
60
|
+
maxRetryTimeMs?: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** RxDB's replication state plus the pull notice and a way to restart after a till error. */
|
|
64
|
+
export type TallyReplicationState<RxDocType, CheckpointType = any> = RxReplicationState<RxDocType, CheckpointType> & {
|
|
65
|
+
/** A notice while a till or store error stops the pull; `undefined` otherwise. */
|
|
66
|
+
notice$: Observable<SyncNotice | undefined>;
|
|
67
|
+
/** Clears the notice, the gates and the backoff, and pulls again from the stored checkpoint. */
|
|
68
|
+
resume(): Promise<void>;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** A valid `retryAfterMs` on the error (a finite number >= 0), else 0. */
|
|
72
|
+
export function retryAfter(error: unknown): number {
|
|
73
|
+
const value = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
|
|
74
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The notice for a till or store error, with the error's string `software`, `minVersion` and `fix`. */
|
|
78
|
+
function noticeFor(error: unknown, fixedBy: 'till' | 'store'): SyncNotice {
|
|
79
|
+
const fields = error as Record<string, unknown>;
|
|
80
|
+
const notice: SyncNotice = { code: fields.code as string, since: Date.now(), fixedBy };
|
|
81
|
+
for (const key of ['software', 'minVersion', 'fix'] as const) {
|
|
82
|
+
if (typeof fields[key] === 'string') notice[key] = fields[key] as string;
|
|
83
|
+
}
|
|
84
|
+
return notice;
|
|
16
85
|
}
|
|
17
86
|
|
|
18
87
|
/**
|
|
@@ -28,14 +97,82 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
28
97
|
live = true,
|
|
29
98
|
retryTime = 5000,
|
|
30
99
|
autoStart = true,
|
|
31
|
-
|
|
32
|
-
|
|
100
|
+
maxRetryTimeMs = MAX_RETRY_TIME_MS,
|
|
101
|
+
}: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
|
|
102
|
+
// Pull errors fall in three classes by who can fix them (errorKind):
|
|
103
|
+
// - till (sign in again): one notice, pause, and an empty page (RxDB stores no
|
|
104
|
+
// checkpoint for it), so it costs one request. Until resume() the handler
|
|
105
|
+
// returns empty pages without calling the adapter, because RxDB restarts a
|
|
106
|
+
// paused loop (start() on page visibility, reSync(), stream$).
|
|
107
|
+
// - store (the owner fixes it elsewhere): one notice, then rethrown with the
|
|
108
|
+
// store delay. An earlier call rethrows the stored error without calling the
|
|
109
|
+
// adapter, with retryTime set to the time left, so RxDB retries exactly then.
|
|
110
|
+
// The first success clears the notice.
|
|
111
|
+
// - transient: rethrown with a doubling delay, or retryAfterMs if longer.
|
|
112
|
+
let state: RxReplicationState<RxDocType, CheckpointType> | undefined;
|
|
113
|
+
const notice$ = new BehaviorSubject<SyncNotice | undefined>(undefined);
|
|
114
|
+
let failures = 0;
|
|
115
|
+
let tillStopped = false;
|
|
116
|
+
let storeError: unknown;
|
|
117
|
+
let storeRetryAt = 0;
|
|
118
|
+
const setRetryTime = (ms: number) => {
|
|
119
|
+
if (state) state.retryTime = ms;
|
|
120
|
+
};
|
|
121
|
+
const pullHandler = async (checkpoint: CheckpointType | undefined, batchSize: number) => {
|
|
122
|
+
if (tillStopped) {
|
|
123
|
+
void state?.pause();
|
|
124
|
+
return { documents: [], checkpoint };
|
|
125
|
+
}
|
|
126
|
+
const wait = storeRetryAt - Date.now();
|
|
127
|
+
if (wait > TIMER_SLACK_MS) {
|
|
128
|
+
setRetryTime(wait);
|
|
129
|
+
throw storeError;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const result = await adapter.pull.handler(checkpoint, batchSize, context);
|
|
133
|
+
failures = 0;
|
|
134
|
+
storeError = undefined;
|
|
135
|
+
storeRetryAt = 0;
|
|
136
|
+
if (notice$.getValue()?.fixedBy === 'store') notice$.next(undefined);
|
|
137
|
+
setRetryTime(retryTime);
|
|
138
|
+
return result;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
const kind = errorKind(error);
|
|
141
|
+
if (kind === 'transient') {
|
|
142
|
+
const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
|
|
143
|
+
setRetryTime(Math.min(Math.max(backoff, retryAfter(error)), MAX_RETRY_AFTER_MS));
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
const code = (error as { code: string }).code;
|
|
147
|
+
const current = notice$.getValue();
|
|
148
|
+
// One notice per cause: a repeat keeps the first `since`; another cause replaces it.
|
|
149
|
+
if (current?.code !== code || current.fixedBy !== kind) notice$.next(noticeFor(error, kind));
|
|
150
|
+
if (kind === 'till') {
|
|
151
|
+
tillStopped = true;
|
|
152
|
+
void state?.pause();
|
|
153
|
+
return { documents: [], checkpoint };
|
|
154
|
+
}
|
|
155
|
+
const delay = Math.min(Math.max(maxRetryTimeMs, retryAfter(error)), MAX_RETRY_AFTER_MS);
|
|
156
|
+
storeError = error;
|
|
157
|
+
storeRetryAt = Date.now() + delay;
|
|
158
|
+
setRetryTime(delay);
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
// A schema bump drops the documents (createTallyDatabase), so it must also
|
|
163
|
+
// reset the checkpoint: RxDB migrates the old checkpoint with the collection.
|
|
164
|
+
// A new identifier is a fresh meta instance, so the pull starts from nothing
|
|
165
|
+
// (and a combined adapter seeds as on a fresh install). The old meta instance
|
|
166
|
+
// is left orphaned: a few rows, and removing it is out of scope. Version 0
|
|
167
|
+
// keeps the original identifier, so existing installs never resync.
|
|
168
|
+
const { version } = collection.schema;
|
|
169
|
+
const replication = replicateRxCollection({
|
|
33
170
|
collection,
|
|
34
|
-
replicationIdentifier: `${context.connectorId}-${collection.name}`,
|
|
171
|
+
replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}`,
|
|
35
172
|
pull: {
|
|
36
|
-
handler:
|
|
37
|
-
adapter.pull.handler(checkpoint as CheckpointType | undefined, batchSize, context),
|
|
173
|
+
handler: pullHandler,
|
|
38
174
|
stream$: adapter.pull.stream$,
|
|
175
|
+
batchSize: adapter.pull.batchSize,
|
|
39
176
|
},
|
|
40
177
|
push: adapter.push
|
|
41
178
|
? {
|
|
@@ -47,4 +184,18 @@ export function startReplication<RxDocType, CheckpointType = any>({
|
|
|
47
184
|
retryTime,
|
|
48
185
|
autoStart,
|
|
49
186
|
});
|
|
187
|
+
state = replication;
|
|
188
|
+
// Cancelled or, for a one-shot replication, completed: RxDB cancels it either way.
|
|
189
|
+
const release = watchShared(adapter, collection);
|
|
190
|
+
replication.canceled$.subscribe((canceled) => { if (canceled) release(); });
|
|
191
|
+
const resume = async () => {
|
|
192
|
+
notice$.next(undefined);
|
|
193
|
+
tillStopped = false;
|
|
194
|
+
storeError = undefined;
|
|
195
|
+
storeRetryAt = 0;
|
|
196
|
+
failures = 0;
|
|
197
|
+
replication.retryTime = retryTime;
|
|
198
|
+
await replication.start();
|
|
199
|
+
};
|
|
200
|
+
return Object.assign(replication, { notice$: notice$.asObservable(), resume });
|
|
50
201
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RxJsonSchema } from 'rxdb';
|
|
2
|
+
|
|
3
|
+
/** Collection holding the stock reconcile overlay (ADR-060). Local only: never replicated. */
|
|
4
|
+
export const STOCK_LEVELS_COLLECTION = 'stock_levels';
|
|
5
|
+
|
|
6
|
+
/** Local document in `stock_levels` holding `{ completedAt }` of the last successful pass. */
|
|
7
|
+
export { STOCK_LEVELS_LAST_PASS } from '@tallyui/core';
|
|
8
|
+
|
|
9
|
+
/** One overlay row: the connector's stock value for one key (Vendure variant id, Medusa inventory item id). */
|
|
10
|
+
export interface StockLevelRow {
|
|
11
|
+
id: string;
|
|
12
|
+
/** The value `fetchPages` gave for this key, stored as is. */
|
|
13
|
+
value: unknown;
|
|
14
|
+
/** ISO 8601 time of the pass that wrote the row. */
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const stockLevelsSchema: RxJsonSchema<StockLevelRow> = {
|
|
19
|
+
version: 0,
|
|
20
|
+
primaryKey: 'id',
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
id: { type: 'string', maxLength: 255 },
|
|
24
|
+
// Untyped: any JSON value the connector yields.
|
|
25
|
+
value: {},
|
|
26
|
+
updatedAt: { type: 'string' },
|
|
27
|
+
},
|
|
28
|
+
required: ['id', 'value', 'updatedAt'],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Use this whenever you create `stock_levels` yourself: the runner stores its last pass in local documents. */
|
|
32
|
+
export const stockLevelsCollection = { schema: stockLevelsSchema, localDocuments: true } as const;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { BehaviorSubject, type Observable } from 'rxjs';
|
|
2
|
+
import type { RxStorage } from 'rxdb';
|
|
3
|
+
import { isRxdbRemoteVersionMismatch } from '@tallyui/core';
|
|
4
|
+
|
|
5
|
+
/** WCPOS's value (ADR-061): a write pending longer than this is flagged as stalled, never failed. */
|
|
6
|
+
export const STORAGE_WRITE_STALL_MS = 10_000;
|
|
7
|
+
|
|
8
|
+
/** WCPOS's value (ADR-061): two consecutive silent read windows of this length mean the worker is dead. */
|
|
9
|
+
export const STORAGE_READ_WATCHDOG_MS = 30_000;
|
|
10
|
+
|
|
11
|
+
export 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
|
+
|
|
20
|
+
export interface StorageWatchdogOptions {
|
|
21
|
+
writeStallMs?: number;
|
|
22
|
+
readWatchdogMs?: number;
|
|
23
|
+
/** Injectable clock, for tests. */
|
|
24
|
+
now?: () => number;
|
|
25
|
+
/** Injectable timer, for tests: runs `fn` once after `ms` and returns a cancel function. */
|
|
26
|
+
setTimer?: (fn: () => void, ms: number) => () => void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* True for `StorageWorkerStartError` (raised by `@tallyui/storage-sqlite/web`
|
|
31
|
+
* when the worker cannot open the opfs-sahpool pool), matched by `name` or by
|
|
32
|
+
* the substring `StorageWorkerStartError` anywhere in the message. RxDB's
|
|
33
|
+
* remote storage re-throws the worker's error serialised across the worker
|
|
34
|
+
* boundary as a plain `Error` whose message embeds the original name as JSON,
|
|
35
|
+
* so a substring match (`includes`, not `startsWith`) is needed to still
|
|
36
|
+
* recognise it.
|
|
37
|
+
*
|
|
38
|
+
* RxDB's RM1 (a stale worker built on another RxDB version, e.g. cached from
|
|
39
|
+
* before an upgrade) is one too: reloading loads the matching worker. The
|
|
40
|
+
* check is `isRxdbRemoteVersionMismatch` from `@tallyui/core`.
|
|
41
|
+
*
|
|
42
|
+
* A worker that crashes mid-call never replies (RxDB `storage-remote`,
|
|
43
|
+
* 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
|
|
44
|
+
*/
|
|
45
|
+
export function isStorageWorkerFailure(error: unknown): boolean {
|
|
46
|
+
return error instanceof Error
|
|
47
|
+
&& (error.name === 'StorageWorkerStartError' || error.message.includes('StorageWorkerStartError')
|
|
48
|
+
|| isRxdbRemoteVersionMismatch(error));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const READ_METHODS = ['query', 'count', 'findDocumentsById', 'getChangedDocumentsSince'] as const;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Wraps a storage so its instances report health on `health$` (ADR-061,
|
|
55
|
+
* following WCPOS). No storage call is ever settled on a clock: a timed-out
|
|
56
|
+
* write may still commit, so a slow write is only flagged as `stalled`, and
|
|
57
|
+
* its promise stays pending until the worker answers. Reads are watched: two
|
|
58
|
+
* consecutive `readWatchdogMs` windows in which reads were pending and no
|
|
59
|
+
* call settled mark the worker `dead` (sticky; the recovery is reload).
|
|
60
|
+
* `createStorageInstance` has no deadline, because the worker and wasm can be
|
|
61
|
+
* slow to download.
|
|
62
|
+
*
|
|
63
|
+
* Instance methods are replaced in place, the way RxDB's own validator wraps
|
|
64
|
+
* `bulkWrite`, so a later wrapper that assigns over ours calls ours, not itself.
|
|
65
|
+
* The `tallyEngine` marker is kept.
|
|
66
|
+
*/
|
|
67
|
+
export function withStorageWatchdog(
|
|
68
|
+
storage: RxStorage<any, any>,
|
|
69
|
+
options: StorageWatchdogOptions = {},
|
|
70
|
+
): RxStorage<any, any> & { health$: Observable<StorageHealth> } {
|
|
71
|
+
const {
|
|
72
|
+
writeStallMs = STORAGE_WRITE_STALL_MS,
|
|
73
|
+
readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
|
|
74
|
+
now = Date.now,
|
|
75
|
+
setTimer = (fn, ms) => { const timer = setTimeout(fn, ms); return () => clearTimeout(timer); },
|
|
76
|
+
} = options;
|
|
77
|
+
const health$ = new BehaviorSubject<StorageHealth>({ status: 'ok', stalledWrites: 0 });
|
|
78
|
+
const stalledStarts: number[] = [];
|
|
79
|
+
let dead = false;
|
|
80
|
+
let pendingReads = 0;
|
|
81
|
+
let silentWindows = 0;
|
|
82
|
+
let settledThisWindow = false;
|
|
83
|
+
let cancelReadTimer: (() => void) | undefined;
|
|
84
|
+
|
|
85
|
+
const emit = () => health$.next({
|
|
86
|
+
status: dead ? 'dead' : stalledStarts.length > 0 ? 'stalled' : 'ok',
|
|
87
|
+
stalledWrites: stalledStarts.length,
|
|
88
|
+
...(stalledStarts.length > 0 ? { stalledSince: Math.min(...stalledStarts) } : {}),
|
|
89
|
+
});
|
|
90
|
+
const settled = () => { settledThisWindow = true; silentWindows = 0; };
|
|
91
|
+
|
|
92
|
+
// Ticks only while a read is pending, and stops once dead (sticky). A window
|
|
93
|
+
// is silent when nothing settled during it.
|
|
94
|
+
const armReadTimer = () => {
|
|
95
|
+
settledThisWindow = false;
|
|
96
|
+
cancelReadTimer = setTimer(() => {
|
|
97
|
+
cancelReadTimer = undefined;
|
|
98
|
+
silentWindows = settledThisWindow ? 0 : silentWindows + 1;
|
|
99
|
+
if (silentWindows >= 2) { dead = true; emit(); } else armReadTimer();
|
|
100
|
+
}, readWatchdogMs);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const watchWrite = <T>(promise: Promise<T>): Promise<T> => {
|
|
104
|
+
const start = now();
|
|
105
|
+
let stalled = false;
|
|
106
|
+
const cancel = setTimer(() => { stalled = true; stalledStarts.push(start); emit(); }, writeStallMs);
|
|
107
|
+
const done = () => {
|
|
108
|
+
cancel();
|
|
109
|
+
settled();
|
|
110
|
+
if (stalled) { stalledStarts.splice(stalledStarts.indexOf(start), 1); emit(); }
|
|
111
|
+
};
|
|
112
|
+
promise.then(done, done);
|
|
113
|
+
return promise;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const watchRead = <T>(promise: Promise<T>): Promise<T> => {
|
|
117
|
+
if (pendingReads++ === 0 && !dead) armReadTimer();
|
|
118
|
+
const done = () => {
|
|
119
|
+
settled();
|
|
120
|
+
if (--pendingReads === 0) { cancelReadTimer?.(); cancelReadTimer = undefined; }
|
|
121
|
+
};
|
|
122
|
+
promise.then(done, done);
|
|
123
|
+
return promise;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
return Object.assign(Object.create(storage), {
|
|
127
|
+
health$: health$.asObservable(),
|
|
128
|
+
async createStorageInstance(params: any) {
|
|
129
|
+
const instance: any = await storage.createStorageInstance(params);
|
|
130
|
+
const originalBulkWrite = instance.bulkWrite.bind(instance);
|
|
131
|
+
instance.bulkWrite = (...args: any[]) => watchWrite(originalBulkWrite(...args));
|
|
132
|
+
for (const method of READ_METHODS) {
|
|
133
|
+
if (typeof instance[method] !== 'function') continue;
|
|
134
|
+
const original = instance[method].bind(instance);
|
|
135
|
+
instance[method] = (...args: any[]) => watchRead(original(...args));
|
|
136
|
+
}
|
|
137
|
+
return instance;
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
package/src/storage.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';
|
|
|
4
4
|
/**
|
|
5
5
|
* Returns the appropriate RxDB storage adapter for the current platform.
|
|
6
6
|
*
|
|
7
|
-
* - Web browser:
|
|
7
|
+
* - Web browser: throws with guidance to pass the SQLite-wasm storage
|
|
8
|
+
* explicitly (ADR-061) — there is no default web storage any more.
|
|
8
9
|
* - React Native: throws with guidance to provide SQLite storage explicitly
|
|
9
10
|
* - Node/SSR/test: In-memory
|
|
10
11
|
*
|
|
@@ -26,8 +27,13 @@ export function getStorage(): RxStorage<any, any> {
|
|
|
26
27
|
);
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
// Web browser
|
|
30
|
-
//
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
// Web browser (ADR-061, breaking): the web storage is no longer Dexie.
|
|
31
|
+
// getStorage() can't build it itself — it needs a worker entry the app's
|
|
32
|
+
// own bundler emits — so pass it explicitly.
|
|
33
|
+
throw new Error(
|
|
34
|
+
'Web storage is RxDB Premium SQLite-wasm, not Dexie (ADR-061). Pass it explicitly, bundling the worker entry:\n' +
|
|
35
|
+
' import { getRxStorageSQLiteWasm } from "@tallyui/storage-sqlite/web";\n' +
|
|
36
|
+
' const workerInput = new URL("@tallyui/storage-sqlite/web-worker", import.meta.url);\n' +
|
|
37
|
+
' createTallyDatabase({ connector, storage: getRxStorageSQLiteWasm({ workerInput }) })'
|
|
38
|
+
);
|
|
33
39
|
}
|
package/src/replication.test.ts
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
-
import { createRxDatabase, addRxPlugin } from 'rxdb';
|
|
3
|
-
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
|
|
4
|
-
import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';
|
|
5
|
-
import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';
|
|
6
|
-
|
|
7
|
-
import { startReplication } from './replication';
|
|
8
|
-
import type { ReplicationAdapter, SyncContext } from '@tallyui/core';
|
|
9
|
-
|
|
10
|
-
addRxPlugin(RxDBDevModePlugin);
|
|
11
|
-
|
|
12
|
-
const storage = wrappedValidateAjvStorage({ storage: getRxStorageMemory() });
|
|
13
|
-
|
|
14
|
-
const testSchema = {
|
|
15
|
-
version: 0,
|
|
16
|
-
primaryKey: 'id',
|
|
17
|
-
type: 'object' as const,
|
|
18
|
-
properties: {
|
|
19
|
-
id: { type: 'string', maxLength: 100 },
|
|
20
|
-
name: { type: 'string' },
|
|
21
|
-
},
|
|
22
|
-
required: ['id', 'name'],
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
const context: SyncContext = {
|
|
26
|
-
connectorId: 'test',
|
|
27
|
-
baseUrl: 'https://example.com',
|
|
28
|
-
headers: {},
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
describe('startReplication', () => {
|
|
32
|
-
let db: any;
|
|
33
|
-
|
|
34
|
-
beforeEach(async () => {
|
|
35
|
-
db = await createRxDatabase({
|
|
36
|
-
name: `test_${Date.now()}`,
|
|
37
|
-
storage,
|
|
38
|
-
multiInstance: false,
|
|
39
|
-
ignoreDuplicate: true,
|
|
40
|
-
});
|
|
41
|
-
await db.addCollections({ products: { schema: testSchema } });
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
afterEach(async () => {
|
|
45
|
-
await db?.close();
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
it('starts replication and pulls documents', async () => {
|
|
49
|
-
const adapter: ReplicationAdapter<any, any> = {
|
|
50
|
-
pull: {
|
|
51
|
-
handler: vi.fn().mockResolvedValueOnce({
|
|
52
|
-
documents: [
|
|
53
|
-
{ id: '1', name: 'Widget', _deleted: false },
|
|
54
|
-
],
|
|
55
|
-
checkpoint: { id: '1' },
|
|
56
|
-
}).mockResolvedValue({
|
|
57
|
-
documents: [],
|
|
58
|
-
checkpoint: { id: '1' },
|
|
59
|
-
}),
|
|
60
|
-
},
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
const state = startReplication({
|
|
64
|
-
collection: db.products,
|
|
65
|
-
adapter,
|
|
66
|
-
context,
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
await state.awaitInSync();
|
|
70
|
-
|
|
71
|
-
const docs = await db.products.find().exec();
|
|
72
|
-
expect(docs).toHaveLength(1);
|
|
73
|
-
expect(docs[0].name).toBe('Widget');
|
|
74
|
-
|
|
75
|
-
await state.cancel();
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
it('returns RxReplicationState with observables', async () => {
|
|
79
|
-
const adapter: ReplicationAdapter<any, any> = {
|
|
80
|
-
pull: {
|
|
81
|
-
handler: vi.fn().mockResolvedValue({ documents: [], checkpoint: {} }),
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
const state = startReplication({
|
|
86
|
-
collection: db.products,
|
|
87
|
-
adapter,
|
|
88
|
-
context,
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
expect(state.error$).toBeDefined();
|
|
92
|
-
expect(state.active$).toBeDefined();
|
|
93
|
-
expect(state.received$).toBeDefined();
|
|
94
|
-
|
|
95
|
-
await state.cancel();
|
|
96
|
-
});
|
|
97
|
-
});
|
package/src/storage.test.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// @vitest-environment node
|
|
2
|
-
import { describe, it, expect } from 'vitest';
|
|
3
|
-
|
|
4
|
-
import { getStorage } from './storage';
|
|
5
|
-
|
|
6
|
-
describe('getStorage', () => {
|
|
7
|
-
it('returns a storage object with a name property', () => {
|
|
8
|
-
const storage = getStorage();
|
|
9
|
-
expect(storage).toBeDefined();
|
|
10
|
-
expect(storage.name).toBeDefined();
|
|
11
|
-
expect(typeof storage.createStorageInstance).toBe('function');
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
it('returns memory storage in node/test environment', () => {
|
|
15
|
-
const storage = getStorage();
|
|
16
|
-
// In Node.js (test env), we expect memory storage
|
|
17
|
-
expect(storage.name).toBe('memory');
|
|
18
|
-
});
|
|
19
|
-
});
|