@tallyui/database 2.0.0 → 3.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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 { ReplicationAdapter, SyncContext } from '@tallyui/core';
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,7 +97,68 @@ export function startReplication<RxDocType, CheckpointType = any>({
28
97
  live = true,
29
98
  retryTime = 5000,
30
99
  autoStart = true,
31
- }: StartReplicationOptions<RxDocType, CheckpointType>): RxReplicationState<RxDocType, CheckpointType> {
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
+ };
32
162
  // A schema bump drops the documents (createTallyDatabase), so it must also
33
163
  // reset the checkpoint: RxDB migrates the old checkpoint with the collection.
34
164
  // A new identifier is a fresh meta instance, so the pull starts from nothing
@@ -36,13 +166,13 @@ export function startReplication<RxDocType, CheckpointType = any>({
36
166
  // is left orphaned: a few rows, and removing it is out of scope. Version 0
37
167
  // keeps the original identifier, so existing installs never resync.
38
168
  const { version } = collection.schema;
39
- return replicateRxCollection({
169
+ const replication = replicateRxCollection({
40
170
  collection,
41
171
  replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}`,
42
172
  pull: {
43
- handler: (checkpoint, batchSize) =>
44
- adapter.pull.handler(checkpoint as CheckpointType | undefined, batchSize, context),
173
+ handler: pullHandler,
45
174
  stream$: adapter.pull.stream$,
175
+ batchSize: adapter.pull.batchSize,
46
176
  },
47
177
  push: adapter.push
48
178
  ? {
@@ -54,4 +184,18 @@ export function startReplication<RxDocType, CheckpointType = any>({
54
184
  retryTime,
55
185
  autoStart,
56
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 });
57
201
  }
@@ -1,5 +1,6 @@
1
1
  import { BehaviorSubject, type Observable } from 'rxjs';
2
2
  import type { RxStorage } from 'rxdb';
3
+ import { isRxdbRemoteVersionMismatch } from '@tallyui/core';
3
4
 
4
5
  /** WCPOS's value (ADR-061): a write pending longer than this is flagged as stalled, never failed. */
5
6
  export const STORAGE_WRITE_STALL_MS = 10_000;
@@ -34,12 +35,17 @@ export interface StorageWatchdogOptions {
34
35
  * so a substring match (`includes`, not `startsWith`) is needed to still
35
36
  * recognise it.
36
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
+ *
37
42
  * A worker that crashes mid-call never replies (RxDB `storage-remote`,
38
43
  * 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
39
44
  */
40
45
  export function isStorageWorkerFailure(error: unknown): boolean {
41
46
  return error instanceof Error
42
- && (error.name === 'StorageWorkerStartError' || error.message.includes('StorageWorkerStartError'));
47
+ && (error.name === 'StorageWorkerStartError' || error.message.includes('StorageWorkerStartError')
48
+ || isRxdbRemoteVersionMismatch(error));
43
49
  }
44
50
 
45
51
  const READ_METHODS = ['query', 'count', 'findDocumentsById', 'getChangedDocumentsSince'] as const;