@tallyui/database 3.14.0 → 3.16.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/dist/index.d.ts CHANGED
@@ -151,10 +151,13 @@ interface ConnectivitySnapshot {
151
151
  type ConnectivityEvent = {
152
152
  type: 'success';
153
153
  at: number;
154
- } | {
154
+ }
155
+ /** `answered`: the store sent a response (a 401, a 404, a 5xx), so the network is up whatever `failure` says. */
156
+ | {
155
157
  type: 'failure';
156
158
  at: number;
157
159
  failure: FailureClass;
160
+ answered?: boolean;
158
161
  }
159
162
  /** The OS says the link is down: offline at once, as v2. */
160
163
  | {
@@ -165,8 +168,9 @@ type ConnectivityEvent = {
165
168
  declare const INITIAL_CONNECTIVITY: ConnectivitySnapshot;
166
169
  /**
167
170
  * v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
168
- * failures have run for the confirmation window. The latch holds across successes, first sight wins, and only a
169
- * reset (v2: a fresh engine) clears it. Returns the same object when nothing changes.
171
+ * failures have run for the confirmation window. Any answer from the store ends offline. The latch holds across
172
+ * successes, first sight wins, and only a reset (v2: a fresh engine, which re-probes) clears it. Returns the same
173
+ * object when nothing changes.
170
174
  */
171
175
  declare function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot;
172
176
  interface ConnectivityTracker {
@@ -174,10 +178,10 @@ interface ConnectivityTracker {
174
178
  readonly snapshot$: Observable<ConnectivitySnapshot>;
175
179
  current(): ConnectivitySnapshot;
176
180
  recordSuccess(): void;
177
- /** Classifies with the tracker's connector, reduces, and returns the class. */
181
+ /** Classifies with the tracker's connector, reduces, and returns the class. A numeric `status` on the error is an answer. */
178
182
  recordFailure(error: unknown): FailureClass;
179
183
  linkDown(): void;
180
- /** Clears the update-required latch, for a re-probe after the store or the till was updated. */
184
+ /** Clears the update-required latch once the store or the till was updated; a replication it feeds re-probes. */
181
185
  resetUpdateRequired(): void;
182
186
  }
183
187
  /** One tracker per connector session; a new one starts clear, as a fresh v2 engine does. */
@@ -199,8 +203,9 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
199
203
  /** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
200
204
  maxRetryTimeMs?: number;
201
205
  /**
202
- * Fed with every pull and push outcome. While its update-required latch is set, the pull pauses and the push throws,
203
- * neither calling the adapter (v2 sends nothing once latched). `resume()` keeps the latch: reset it first.
206
+ * Fed with every pull and push outcome. While its update-required latch is set, the pull returns empty pages and a
207
+ * push waits, neither calling the adapter (v2 sends nothing once latched). `resetUpdateRequired()` re-probes: the
208
+ * pull asks the store again and a held push goes. `resume()` keeps the latch, and the reset keeps a sign-in hold.
204
209
  */
205
210
  connectivity?: ConnectivityTracker;
206
211
  }
package/dist/index.js CHANGED
@@ -52,8 +52,8 @@ function withStorageWatchdog(storage, options = {}) {
52
52
  readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
53
53
  now = Date.now,
54
54
  setTimer = (fn, ms) => {
55
- const timer = setTimeout(fn, ms);
56
- return () => clearTimeout(timer);
55
+ const timer2 = setTimeout(fn, ms);
56
+ return () => clearTimeout(timer2);
57
57
  }
58
58
  } = options;
59
59
  const health$ = new BehaviorSubject({ status: "ok", stalledWrites: 0 });
@@ -189,7 +189,16 @@ function getStorage() {
189
189
 
190
190
  // src/replication.ts
191
191
  import { replicateRxCollection } from "rxdb/plugins/replication";
192
- import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
192
+ import { errorToPlainJson, newRxError, toArray } from "rxdb";
193
+ import {
194
+ BehaviorSubject as BehaviorSubject2,
195
+ EMPTY,
196
+ filter,
197
+ firstValueFrom,
198
+ fromEvent,
199
+ merge,
200
+ timer
201
+ } from "rxjs";
193
202
  import { errorKind } from "@tallyui/core";
194
203
  var MAX_RETRY_TIME_MS = 5 * 60 * 1e3;
195
204
  var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
@@ -221,6 +230,17 @@ function retryAfter(error) {
221
230
  const value = error?.retryAfterMs;
222
231
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
223
232
  }
233
+ async function hold(events, ready, wake$ = EMPTY) {
234
+ const done = () => events.canceled.getValue() || ready();
235
+ if (done()) return;
236
+ await firstValueFrom(merge(events.paused, events.canceled, wake$).pipe(filter(done)), { defaultValue: void 0 });
237
+ }
238
+ function retryWait(events, ms) {
239
+ if (events.canceled.getValue()) return Promise.resolve();
240
+ const offline = typeof window === "object" && typeof window.addEventListener === "function" && !navigator.onLine;
241
+ const wake$ = merge(timer(ms), events.canceled.pipe(filter(Boolean)), offline ? fromEvent(window, "online") : EMPTY);
242
+ return firstValueFrom(wake$, { defaultValue: void 0 });
243
+ }
224
244
  function noticeFor(error, fixedBy) {
225
245
  const fields = error;
226
246
  const notice = { code: fields.code, since: Date.now(), fixedBy };
@@ -242,17 +262,15 @@ function startReplication({
242
262
  let state;
243
263
  const notice$ = new BehaviorSubject2(void 0);
244
264
  let failures = 0;
245
- let tillStopped = false;
265
+ const tillHeld$ = new BehaviorSubject2(false);
246
266
  let storeError;
247
267
  let storeRetryAt = 0;
248
268
  const setRetryTime = (ms) => {
249
269
  if (state) state.retryTime = ms;
250
270
  };
251
271
  const pullHandler = async (checkpoint, batchSize) => {
252
- if (tillStopped || connectivity?.current().updateRequired) {
253
- void state?.pause();
254
- return { documents: [], checkpoint };
255
- }
272
+ if (tillHeld$.getValue()) return { documents: [], checkpoint };
273
+ if (connectivity?.current().updateRequired) return { documents: [], checkpoint };
256
274
  const wait = storeRetryAt - Date.now();
257
275
  if (wait > TIMER_SLACK_MS) {
258
276
  setRetryTime(wait);
@@ -279,8 +297,7 @@ function startReplication({
279
297
  const current = notice$.getValue();
280
298
  if (current?.code !== code || current.fixedBy !== kind) notice$.next(noticeFor(error, kind));
281
299
  if (kind === "till") {
282
- tillStopped = true;
283
- void state?.pause();
300
+ tillHeld$.next(true);
284
301
  return { documents: [], checkpoint };
285
302
  }
286
303
  const delay = Math.min(Math.max(maxRetryTimeMs, retryAfter(error)), MAX_RETRY_AFTER_MS);
@@ -296,20 +313,34 @@ function startReplication({
296
313
  replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}`,
297
314
  pull: {
298
315
  handler: pullHandler,
299
- stream$: adapter.pull.stream$,
316
+ stream$: adapter.pull.stream$?.pipe(filter((event) => event === "RESYNC" || !tillHeld$.getValue())),
300
317
  batchSize: adapter.pull.batchSize
301
318
  },
302
319
  push: adapter.push ? {
320
+ // A push is held, never thrown or dropped, while latched, held for sign-in or paused: before the send, and
321
+ // after it until the pause ends. RxDB 17.5 drops a paused push's answer (plugins/replication/index.js 269, upstream.js
322
+ // 287), so its rows go twice. And the pages queued behind it (upstream.js 90-100) then find no rows and
323
+ // store the up checkpoint anyway (upstream.js 211), so those rows never go. A failed push is retried
324
+ // here, never thrown: RxDB's own retry wait (index.js 266) ends unsent if paused by then, with the same
325
+ // loss. Only a cancel ends a hold, with nothing sent.
303
326
  handler: async (rows) => {
304
- if (!connectivity) return adapter.push.handler(rows, context);
305
- if (connectivity.current().updateRequired) throw new Error("update required: push held");
306
- try {
307
- const conflicts = await adapter.push.handler(rows, context);
308
- connectivity.recordSuccess();
309
- return conflicts;
310
- } catch (error) {
311
- connectivity.recordFailure(error);
312
- throw error;
327
+ const events = state.internalReplicationState.events;
328
+ const isHeld = () => tillHeld$.getValue() || Boolean(connectivity?.current().updateRequired);
329
+ const wake$ = connectivity ? merge(connectivity.snapshot$, tillHeld$) : tillHeld$;
330
+ for (; ; ) {
331
+ await hold(events, () => !isHeld() && !events.paused.getValue(), wake$);
332
+ if (events.canceled.getValue()) return [];
333
+ const sent = await adapter.push.handler(rows, context).then((conflicts) => ({ conflicts }), (error) => {
334
+ connectivity?.recordFailure(error);
335
+ const errors = toArray(error).map(errorToPlainJson);
336
+ events.error.next(newRxError("RC_PUSH", { pushRows: rows, errors, direction: "push" }));
337
+ });
338
+ if (sent) {
339
+ connectivity?.recordSuccess();
340
+ await hold(events, () => !events.paused.getValue());
341
+ return sent.conflicts;
342
+ }
343
+ await retryWait(events, state.retryTime ?? retryTime);
313
344
  }
314
345
  },
315
346
  batchSize: adapter.push.batchSize
@@ -320,12 +351,19 @@ function startReplication({
320
351
  });
321
352
  state = replication;
322
353
  const release = watchShared(adapter, collection);
354
+ let latched = Boolean(connectivity?.current().updateRequired);
355
+ const probe = connectivity?.snapshot$.subscribe(({ updateRequired }) => {
356
+ if (latched && !updateRequired && !tillHeld$.getValue() && !replication.isPaused()) replication.reSync();
357
+ latched = updateRequired !== null;
358
+ });
323
359
  replication.canceled$.subscribe((canceled) => {
324
- if (canceled) release();
360
+ if (!canceled) return;
361
+ release();
362
+ probe?.unsubscribe();
325
363
  });
326
364
  const resume = async () => {
327
365
  notice$.next(void 0);
328
- tillStopped = false;
366
+ tillHeld$.next(false);
329
367
  storeError = void 0;
330
368
  storeRetryAt = 0;
331
369
  failures = 0;
@@ -352,14 +390,15 @@ function reduceConnectivity(snapshot, event) {
352
390
  return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
353
391
  case "failure": {
354
392
  const { failure, at } = event;
355
- if (failure === null) return snapshot;
393
+ if (failure === null) return event.answered ? answered(snapshot) : snapshot;
356
394
  if (typeof failure === "object") {
357
395
  const next = answered(snapshot);
358
396
  return next.updateRequired ? next : { ...next, updateRequired: failure.updateRequired };
359
397
  }
360
398
  const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
361
399
  const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
362
- const state = confirmed ? failure : snapshot.state;
400
+ const verdict = confirmed ? failure : snapshot.state;
401
+ const state = event.answered && verdict === "offline" ? "degraded" : verdict;
363
402
  return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
364
403
  }
365
404
  }
@@ -377,7 +416,8 @@ function createConnectivityTracker(options = {}) {
377
416
  recordSuccess: () => dispatch({ type: "success", at: now() }),
378
417
  recordFailure: (error) => {
379
418
  const failure = classifyFailure(connector, error);
380
- dispatch({ type: "failure", at: now(), failure });
419
+ const answered2 = typeof error?.status === "number";
420
+ dispatch({ type: "failure", at: now(), failure, answered: answered2 });
381
421
  return failure;
382
422
  },
383
423
  linkDown: () => dispatch({ type: "link-down" }),
@@ -435,12 +475,12 @@ function startLiveTab(options) {
435
475
  });
436
476
  });
437
477
  const waitForAck = (id) => new Promise((resolve) => {
438
- const timer = setTimeout(() => {
478
+ const timer2 = setTimeout(() => {
439
479
  ackWaiters.delete(id);
440
480
  resolve(false);
441
481
  }, ackTimeoutMs);
442
482
  ackWaiters.set(id, () => {
443
- clearTimeout(timer);
483
+ clearTimeout(timer2);
444
484
  ackWaiters.delete(id);
445
485
  resolve(true);
446
486
  });
@@ -680,11 +720,11 @@ function startStockReconcile({
680
720
  }
681
721
  };
682
722
  const reconcileStock = createPassQueue(tracked);
683
- const timer = setInterval(() => {
723
+ const timer2 = setInterval(() => {
684
724
  reconcileStock().catch((error) => console.warn("Stock reconcile failed:", error));
685
725
  }, intervalMs);
686
726
  const stop = () => {
687
- clearInterval(timer);
727
+ clearInterval(timer2);
688
728
  context.signal?.removeEventListener("abort", stop);
689
729
  controller.abort();
690
730
  state.complete();
@@ -732,8 +772,8 @@ function startCatalogueRunner({
732
772
  now = Date.now,
733
773
  stateId = "catalogue-reconcile",
734
774
  setTimer = (fn, ms) => {
735
- const timer = setTimeout(fn, ms);
736
- return () => clearTimeout(timer);
775
+ const timer2 = setTimeout(fn, ms);
776
+ return () => clearTimeout(timer2);
737
777
  },
738
778
  keepCandidates = false
739
779
  }) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/database",
3
- "version": "3.14.0",
3
+ "version": "3.16.0",
4
4
  "type": "module",
5
5
  "description": "RxDB database factory for Tally UI — accepts pluggable connector schemas",
6
6
  "main": "./dist/index.js",
@@ -30,7 +30,7 @@
30
30
  "rxjs": "7.8.2"
31
31
  },
32
32
  "peerDependencies": {
33
- "@tallyui/core": "^3.14.0"
33
+ "@tallyui/core": "^3.16.0"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "tsup",
@@ -24,7 +24,8 @@ export interface ConnectivitySnapshot {
24
24
 
25
25
  export type ConnectivityEvent =
26
26
  | { type: 'success'; at: number }
27
- | { type: 'failure'; at: number; failure: FailureClass }
27
+ /** `answered`: the store sent a response (a 401, a 404, a 5xx), so the network is up whatever `failure` says. */
28
+ | { type: 'failure'; at: number; failure: FailureClass; answered?: boolean }
28
29
  /** The OS says the link is down: offline at once, as v2. */
29
30
  | { type: 'link-down' }
30
31
  | { type: 'reset-update-required' };
@@ -36,8 +37,9 @@ const answered = (snapshot: ConnectivitySnapshot): ConnectivitySnapshot =>
36
37
 
37
38
  /**
38
39
  * v2's rule (`use-online-status.web.tsx`): the first success is online; a failure changes the verdict only once
39
- * failures have run for the confirmation window. The latch holds across successes, first sight wins, and only a
40
- * reset (v2: a fresh engine) clears it. Returns the same object when nothing changes.
40
+ * failures have run for the confirmation window. Any answer from the store ends offline. The latch holds across
41
+ * successes, first sight wins, and only a reset (v2: a fresh engine, which re-probes) clears it. Returns the same
42
+ * object when nothing changes.
41
43
  */
42
44
  export function reduceConnectivity(snapshot: ConnectivitySnapshot, event: ConnectivityEvent): ConnectivitySnapshot {
43
45
  switch (event.type) {
@@ -49,7 +51,8 @@ export function reduceConnectivity(snapshot: ConnectivitySnapshot, event: Connec
49
51
  return snapshot.updateRequired === null ? snapshot : { ...snapshot, updateRequired: null };
50
52
  case 'failure': {
51
53
  const { failure, at } = event;
52
- if (failure === null) return snapshot;
54
+ // An answer that says nothing about connectivity (a 401, a 404) still proves the store is reachable.
55
+ if (failure === null) return event.answered ? answered(snapshot) : snapshot;
53
56
  if (typeof failure === 'object') {
54
57
  // The store answered with its refusal, so it is reachable.
55
58
  const next = answered(snapshot);
@@ -58,7 +61,9 @@ export function reduceConnectivity(snapshot: ConnectivitySnapshot, event: Connec
58
61
  // A clock that went back would hold the verdict off for ever: re-anchor instead.
59
62
  const failingSince = snapshot.failingSince === null || snapshot.failingSince > at ? at : snapshot.failingSince;
60
63
  const confirmed = at - failingSince >= FAILURE_CONFIRMATION_MS - FAILURE_CONFIRMATION_TOLERANCE_MS;
61
- const state = confirmed ? failure : snapshot.state;
64
+ const verdict = confirmed ? failure : snapshot.state;
65
+ // An answer is never offline: a 5xx while offline is degraded at once.
66
+ const state = event.answered && verdict === 'offline' ? 'degraded' : verdict;
62
67
  return state === snapshot.state && failingSince === snapshot.failingSince ? snapshot : { ...snapshot, state, failingSince };
63
68
  }
64
69
  }
@@ -69,10 +74,10 @@ export interface ConnectivityTracker {
69
74
  readonly snapshot$: Observable<ConnectivitySnapshot>;
70
75
  current(): ConnectivitySnapshot;
71
76
  recordSuccess(): void;
72
- /** Classifies with the tracker's connector, reduces, and returns the class. */
77
+ /** Classifies with the tracker's connector, reduces, and returns the class. A numeric `status` on the error is an answer. */
73
78
  recordFailure(error: unknown): FailureClass;
74
79
  linkDown(): void;
75
- /** Clears the update-required latch, for a re-probe after the store or the till was updated. */
80
+ /** Clears the update-required latch once the store or the till was updated; a replication it feeds re-probes. */
76
81
  resetUpdateRequired(): void;
77
82
  }
78
83
 
@@ -92,7 +97,8 @@ export function createConnectivityTracker(
92
97
  recordSuccess: () => dispatch({ type: 'success', at: now() }),
93
98
  recordFailure: (error) => {
94
99
  const failure = classifyFailure(connector, error);
95
- dispatch({ type: 'failure', at: now(), failure });
100
+ const answered = typeof (error as { status?: unknown } | null | undefined)?.status === 'number';
101
+ dispatch({ type: 'failure', at: now(), failure, answered });
96
102
  return failure;
97
103
  },
98
104
  linkDown: () => dispatch({ type: 'link-down' }),
@@ -1,6 +1,8 @@
1
1
  import { replicateRxCollection, type RxReplicationState } from 'rxdb/plugins/replication';
2
- import type { RxCollection } from 'rxdb';
3
- import { BehaviorSubject, type Observable } from 'rxjs';
2
+ import { errorToPlainJson, newRxError, toArray, type RxCollection, type RxError } from 'rxdb';
3
+ import {
4
+ BehaviorSubject, EMPTY, filter, firstValueFrom, fromEvent, merge, timer, type Observable, type Subject, type Subscription,
5
+ } from 'rxjs';
4
6
 
5
7
  import { errorKind, type ReplicationAdapter, type SyncContext, type SyncNotice } from '@tallyui/core';
6
8
 
@@ -61,8 +63,9 @@ export interface StartReplicationOptions<RxDocType, CheckpointType = any> {
61
63
  /** The backoff's ceiling and a store error's wait, in ms (default: MAX_RETRY_TIME_MS); tests shorten it. */
62
64
  maxRetryTimeMs?: number;
63
65
  /**
64
- * Fed with every pull and push outcome. While its update-required latch is set, the pull pauses and the push throws,
65
- * neither calling the adapter (v2 sends nothing once latched). `resume()` keeps the latch: reset it first.
66
+ * Fed with every pull and push outcome. While its update-required latch is set, the pull returns empty pages and a
67
+ * push waits, neither calling the adapter (v2 sends nothing once latched). `resetUpdateRequired()` re-probes: the
68
+ * pull asks the store again and a held push goes. `resume()` keeps the latch, and the reset keeps a sign-in hold.
66
69
  */
67
70
  connectivity?: ConnectivityTracker;
68
71
  }
@@ -81,6 +84,31 @@ export function retryAfter(error: unknown): number {
81
84
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
82
85
  }
83
86
 
87
+ /** The subjects of RxDB's protocol state the push reads, and its error feed (17.5 types/replication-protocol.d.ts 200-219). */
88
+ type ProtocolEvents = { paused: BehaviorSubject<boolean>; canceled: BehaviorSubject<boolean>; error: Subject<RxError> };
89
+
90
+ /**
91
+ * Resolves once `ready()` holds or the replication is cancelled, waking on a pause change, the cancel and `wake$`.
92
+ * The protocol's own `canceled` is set before a cancel awaits anything (17.5 replication-protocol/index.js 216), and
93
+ * completes after, hence the check first and the default value.
94
+ */
95
+ async function hold(events: ProtocolEvents, ready: () => boolean, wake$: Observable<unknown> = EMPTY) {
96
+ const done = () => events.canceled.getValue() || ready();
97
+ if (done()) return;
98
+ await firstValueFrom(merge(events.paused, events.canceled, wake$).pipe(filter(done)), { defaultValue: undefined });
99
+ }
100
+
101
+ /**
102
+ * RxDB's own push retry wait (17.5 plugins/replication/replication-helper.js 51-65): `ms`, cut short by the browser's
103
+ * `online` event while it is offline, and here also by a cancel.
104
+ */
105
+ function retryWait(events: ProtocolEvents, ms: number) {
106
+ if (events.canceled.getValue()) return Promise.resolve();
107
+ const offline = typeof window === 'object' && typeof window.addEventListener === 'function' && !navigator.onLine;
108
+ const wake$ = merge(timer(ms), events.canceled.pipe(filter(Boolean)), offline ? fromEvent(window, 'online') : EMPTY);
109
+ return firstValueFrom(wake$, { defaultValue: undefined });
110
+ }
111
+
84
112
  /** The notice for a till or store error, with the error's string `software`, `minVersion` and `fix`. */
85
113
  function noticeFor(error: unknown, fixedBy: 'till' | 'store'): SyncNotice {
86
114
  const fields = error as Record<string, unknown>;
@@ -108,10 +136,13 @@ export function startReplication<RxDocType, CheckpointType = any>({
108
136
  connectivity,
109
137
  }: StartReplicationOptions<RxDocType, CheckpointType>): TallyReplicationState<RxDocType, CheckpointType> {
110
138
  // Pull errors fall in three classes by who can fix them (errorKind):
111
- // - till (sign in again): one notice, pause, and an empty page (RxDB stores no
112
- // checkpoint for it), so it costs one request. Until resume() the handler
113
- // returns empty pages without calling the adapter, because RxDB restarts a
114
- // paused loop (start() on page visibility, reSync(), stream$).
139
+ // - till (sign in again): one notice and an empty page (RxDB stores no
140
+ // checkpoint for it), so it costs one request. Then a hold until resume():
141
+ // the pull returns empty pages without calling the adapter, a push waits in
142
+ // its handler, and stream$ documents are dropped. Never RxDB's pause(): a
143
+ // pause before a push page reaches the handler drops it unsent, and the
144
+ // pages queued behind it store the up checkpoint past its rows (17.5
145
+ // plugins/replication/index.js 240, 269; upstream.js 211, 287; #645).
115
146
  // - store (the owner fixes it elsewhere): one notice, then rethrown with the
116
147
  // store delay. An earlier call rethrows the stored error without calling the
117
148
  // adapter, with retryTime set to the time left, so RxDB retries exactly then.
@@ -120,17 +151,17 @@ export function startReplication<RxDocType, CheckpointType = any>({
120
151
  let state: RxReplicationState<RxDocType, CheckpointType> | undefined;
121
152
  const notice$ = new BehaviorSubject<SyncNotice | undefined>(undefined);
122
153
  let failures = 0;
123
- let tillStopped = false;
154
+ const tillHeld$ = new BehaviorSubject(false);
124
155
  let storeError: unknown;
125
156
  let storeRetryAt = 0;
126
157
  const setRetryTime = (ms: number) => {
127
158
  if (state) state.retryTime = ms;
128
159
  };
129
160
  const pullHandler = async (checkpoint: CheckpointType | undefined, batchSize: number) => {
130
- if (tillStopped || connectivity?.current().updateRequired) {
131
- void state?.pause();
132
- return { documents: [], checkpoint };
133
- }
161
+ if (tillHeld$.getValue()) return { documents: [], checkpoint };
162
+ // Latched: an empty page, no request, and no pause. A pause while a push is in flight makes RxDB drop that push's
163
+ // answer and send its rows again after the restart (17.5 replication-protocol/upstream.js), a doubled write.
164
+ if (connectivity?.current().updateRequired) return { documents: [], checkpoint };
134
165
  const wait = storeRetryAt - Date.now();
135
166
  if (wait > TIMER_SLACK_MS) {
136
167
  setRetryTime(wait);
@@ -158,8 +189,7 @@ export function startReplication<RxDocType, CheckpointType = any>({
158
189
  // One notice per cause: a repeat keeps the first `since`; another cause replaces it.
159
190
  if (current?.code !== code || current.fixedBy !== kind) notice$.next(noticeFor(error, kind));
160
191
  if (kind === 'till') {
161
- tillStopped = true;
162
- void state?.pause();
192
+ tillHeld$.next(true);
163
193
  return { documents: [], checkpoint };
164
194
  }
165
195
  const delay = Math.min(Math.max(maxRetryTimeMs, retryAfter(error)), MAX_RETRY_AFTER_MS);
@@ -181,21 +211,36 @@ export function startReplication<RxDocType, CheckpointType = any>({
181
211
  replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ''}`,
182
212
  pull: {
183
213
  handler: pullHandler,
184
- stream$: adapter.pull.stream$,
214
+ stream$: adapter.pull.stream$?.pipe(filter(event => event === 'RESYNC' || !tillHeld$.getValue())),
185
215
  batchSize: adapter.pull.batchSize,
186
216
  },
187
217
  push: adapter.push
188
218
  ? {
219
+ // A push is held, never thrown or dropped, while latched, held for sign-in or paused: before the send, and
220
+ // after it until the pause ends. RxDB 17.5 drops a paused push's answer (plugins/replication/index.js 269, upstream.js
221
+ // 287), so its rows go twice. And the pages queued behind it (upstream.js 90-100) then find no rows and
222
+ // store the up checkpoint anyway (upstream.js 211), so those rows never go. A failed push is retried
223
+ // here, never thrown: RxDB's own retry wait (index.js 266) ends unsent if paused by then, with the same
224
+ // loss. Only a cancel ends a hold, with nothing sent.
189
225
  handler: async (rows) => {
190
- if (!connectivity) return adapter.push!.handler(rows, context);
191
- if (connectivity.current().updateRequired) throw new Error('update required: push held');
192
- try {
193
- const conflicts = await adapter.push!.handler(rows, context);
194
- connectivity.recordSuccess();
195
- return conflicts;
196
- } catch (error) {
197
- connectivity.recordFailure(error);
198
- throw error;
226
+ const events = state!.internalReplicationState!.events as ProtocolEvents;
227
+ const isHeld = () => tillHeld$.getValue() || Boolean(connectivity?.current().updateRequired);
228
+ const wake$ = connectivity ? merge(connectivity.snapshot$, tillHeld$) : tillHeld$;
229
+ for (;;) {
230
+ await hold(events, () => !isHeld() && !events.paused.getValue(), wake$);
231
+ if (events.canceled.getValue()) return [];
232
+ const sent = await adapter.push!.handler(rows, context).then(conflicts => ({ conflicts }), (error: unknown) => {
233
+ connectivity?.recordFailure(error);
234
+ // RxDB's own push error (index.js 260-265), on the feed its error$ forwards (index.js 281).
235
+ const errors = toArray(error as Error).map(errorToPlainJson);
236
+ events.error.next(newRxError('RC_PUSH', { pushRows: rows, errors, direction: 'push' }));
237
+ });
238
+ if (sent) {
239
+ connectivity?.recordSuccess();
240
+ await hold(events, () => !events.paused.getValue());
241
+ return sent.conflicts;
242
+ }
243
+ await retryWait(events, state!.retryTime ?? retryTime);
199
244
  }
200
245
  },
201
246
  batchSize: adapter.push.batchSize,
@@ -208,10 +253,23 @@ export function startReplication<RxDocType, CheckpointType = any>({
208
253
  state = replication;
209
254
  // Cancelled or, for a one-shot replication, completed: RxDB cancels it either way.
210
255
  const release = watchShared(adapter, collection);
211
- replication.canceled$.subscribe((canceled) => { if (canceled) release(); });
256
+ // The re-probe (v2: a fresh engine re-probes the store, so only it clears the latch; apps/main/lib/create-app-engine.ts):
257
+ // when the latch is reset, pull again from the checkpoint and re-run the push.
258
+ let latched = Boolean(connectivity?.current().updateRequired);
259
+ // Not while paused: an upstream pass run while paused sends nothing yet stores its checkpoint (upstream.js 211,
260
+ // 287), and RxDB's start() re-syncs after a pause anyway (plugins/replication/index.js 110).
261
+ const probe: Subscription | undefined = connectivity?.snapshot$.subscribe(({ updateRequired }) => {
262
+ if (latched && !updateRequired && !tillHeld$.getValue() && !replication.isPaused()) replication.reSync();
263
+ latched = updateRequired !== null;
264
+ });
265
+ replication.canceled$.subscribe((canceled) => {
266
+ if (!canceled) return;
267
+ release();
268
+ probe?.unsubscribe();
269
+ });
212
270
  const resume = async () => {
213
271
  notice$.next(undefined);
214
- tillStopped = false;
272
+ tillHeld$.next(false);
215
273
  storeError = undefined;
216
274
  storeRetryAt = 0;
217
275
  failures = 0;