Skip to content

Commit badcfda

Browse files
author
npub1x4hk035p3p9q39a3fcrd2fe30lpkrhr5dwe0cqzzjphxyyh8m0gsq4vqap
committed
fix(relay): preserve reconnect backoff
Co-authored-by: npub1x4hk035p3p9q39a3fcrd2fe30lpkrhr5dwe0cqzzjphxyyh8m0gsq4vqap <356f67c681884a0897b14e06d527317fc361dc746bb2fc0042906e6212e7dbd1@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1x4hk035p3p9q39a3fcrd2fe30lpkrhr5dwe0cqzzjphxyyh8m0gsq4vqap <356f67c681884a0897b14e06d527317fc361dc746bb2fc0042906e6212e7dbd1@sprout-oss.stage.blox.sqprod.co>
1 parent 6b5facb commit badcfda

3 files changed

Lines changed: 50 additions & 116 deletions

File tree

‎desktop/src/shared/api/relayReconnectController.test.mjs‎

Lines changed: 34 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
*/
88

99
import assert from "node:assert/strict";
10+
import { readFileSync } from "node:fs";
11+
import path from "node:path";
1012
import test, { mock } from "node:test";
13+
import { fileURLToPath } from "node:url";
1114

1215
import {
1316
DEFAULT_RECONNECT_TIMING_POLICY,
@@ -24,9 +27,7 @@ function makeDeps({
2427
connectionStateListener = null,
2528
} = {}) {
2629
const timers = [];
27-
const intervals = [];
2830
let timerSeq = 0;
29-
let intervalSeq = 0;
3031

3132
const deps = {
3233
preconnect: mock.fn(preconnectResult),
@@ -47,38 +48,44 @@ function makeDeps({
4748
const idx = timers.findIndex((t) => t.id === id);
4849
if (idx !== -1) timers.splice(idx, 1);
4950
}),
50-
setInterval: mock.fn((fn, ms) => {
51-
const id = ++intervalSeq;
52-
intervals.push({ id, fn, ms });
53-
return id;
54-
}),
55-
clearInterval: mock.fn((id) => {
56-
const idx = intervals.findIndex((t) => t.id === id);
57-
if (idx !== -1) intervals.splice(idx, 1);
58-
}),
59-
// Test helpers to fire timers/intervals.
51+
// Test helper to fire timers.
6052
_fireTimer: (id) => timers.find((t) => t.id === id)?.fn(),
61-
_fireInterval: (id) => intervals.find((t) => t.id === id)?.fn(),
6253
_timers: timers,
63-
_intervals: intervals,
6454
};
6555
return deps;
6656
}
6757

6858
// ── Timing policy ─────────────────────────────────────────────────────────────
6959

60+
const testDir = path.dirname(fileURLToPath(import.meta.url));
61+
62+
test("fast path outlives the native websocket connection timeout", () => {
63+
const rustSource = readFileSync(
64+
path.resolve(testDir, "../../../src-tauri/src/native_websocket.rs"),
65+
"utf8",
66+
);
67+
const match = rustSource.match(
68+
/const CONNECT_TIMEOUT: Duration = Duration::from_secs\((\d+)\);/,
69+
);
70+
assert.ok(match, "native websocket connect timeout is declared in seconds");
71+
72+
const nativeConnectTimeoutMs = Number(match[1]) * 1_000;
73+
assert.ok(
74+
DEFAULT_RECONNECT_TIMING_POLICY.fastPathTimeoutMs > nativeConnectTimeoutMs,
75+
"fast path must wait for the native websocket attempt to settle",
76+
);
77+
});
78+
7079
test("default timing policy preserves current reconnect timings", () => {
7180
assert.deepEqual(DEFAULT_RECONNECT_TIMING_POLICY, {
72-
fastPathTimeoutMs: 4_000,
73-
pollIntervalMs: 3_000,
81+
fastPathTimeoutMs: 11_000,
7482
backstopMs: 120_000,
7583
});
7684
});
7785

78-
test("injected timing policy drives fast-path, poll, and backstop timers", async () => {
86+
test("injected timing policy drives fast-path and backstop timers", async () => {
7987
const ctrl = new RelayReconnectController({
8088
fastPathTimeoutMs: 11,
81-
pollIntervalMs: 22,
8289
backstopMs: 33,
8390
});
8491
const deps = makeDeps({
@@ -91,7 +98,6 @@ test("injected timing policy drives fast-path, poll, and backstop timers", async
9198
await ctrl.start(deps);
9299

93100
assert.equal(deps.setTimeout.mock.calls[0].arguments[1], 11);
94-
assert.equal(deps.setInterval.mock.calls[0].arguments[1], 22);
95101
assert.equal(deps.setTimeout.mock.calls[1].arguments[1], 33);
96102
});
97103

@@ -113,13 +119,12 @@ test("fast-path success — hook never invoked, onSuccess fires, state resets",
113119
});
114120
});
115121

116-
test("fast-path success — no poll interval or backstop scheduled", async () => {
122+
test("fast-path success — no backstop scheduled", async () => {
117123
const ctrl = new RelayReconnectController();
118124
const deps = makeDeps({ preconnectResult: async () => {} });
119125

120126
await ctrl.start(deps);
121127

122-
assert.equal(deps.setInterval.mock.calls.length, 0, "no poll interval");
123128
// The fast-path withDeadline schedules one timeout for the deadline, but
124129
// that is cleared by finally(). After success no backstop should remain.
125130
assert.equal(
@@ -136,7 +141,7 @@ test("escalation fires only when fast path fails and hook is configured", async
136141
let callIdx = 0;
137142
const deps = makeDeps({
138143
preconnectResult: async () => {
139-
// First call (fast path) fails; subsequent calls (poll) succeed.
144+
// First call (fast path) fails.
140145
if (++callIdx === 1) throw new Error("relay unreachable");
141146
},
142147
hookConfiguredResult: async () => true,
@@ -174,7 +179,7 @@ test("escalation skipped when hook not configured", async () => {
174179
);
175180
});
176181

177-
test("hook failure is non-fatal — polling still starts", async () => {
182+
test("hook failure is non-fatal — background wait still starts", async () => {
178183
const ctrl = new RelayReconnectController();
179184
const deps = makeDeps({
180185
preconnectResult: async () => {
@@ -195,48 +200,12 @@ test("hook failure is non-fatal — polling still starts", async () => {
195200
}
196201

197202
assert.equal(threw, false, "hook failure does not propagate");
198-
assert.ok(
199-
deps._intervals.length > 0 || deps._timers.length > 0,
200-
"phase 3 timers scheduled",
201-
);
203+
assert.ok(deps._timers.length > 0, "phase 3 backstop scheduled");
202204
});
203205

204-
// ── Phase 3: poll-until-connected ─────────────────────────────────────────────
206+
// ── Phase 3: wait for background reconnect ───────────────────────────────────
205207

206-
test("poll preempts backstop — onSuccess fires when poll wins", async () => {
207-
const ctrl = new RelayReconnectController();
208-
let callIdx = 0;
209-
const deps = makeDeps({
210-
preconnectResult: async () => {
211-
if (++callIdx <= 2) throw new Error("not yet");
212-
// Third call succeeds — simulates poll winning.
213-
},
214-
hookConfiguredResult: async () => false,
215-
});
216-
217-
// Phase 1 fails, enters phase 3. start() returns false.
218-
const promise = ctrl.start(deps);
219-
await promise;
220-
221-
// Fire the poll interval twice to reach the succeeding call.
222-
const intervalId = deps._intervals[0]?.id;
223-
assert.ok(intervalId !== undefined, "poll interval is active");
224-
225-
await deps._fireInterval(intervalId); // call 2 — fails
226-
await deps._fireInterval(intervalId); // call 3 — succeeds
227-
228-
assert.equal(
229-
deps.onSuccess.mock.calls.length,
230-
1,
231-
"onSuccess fired after poll win",
232-
);
233-
assert.deepEqual(ctrl.getState(), {
234-
isPending: false,
235-
isWaitingOnReconnectHook: false,
236-
});
237-
});
238-
239-
test("connection-state emitter fires onSuccess and cancels poll/backstop", async () => {
208+
test("connection-state emitter fires onSuccess and cancels backstop", async () => {
240209
let capturedListener = null;
241210
const ctrl = new RelayReconnectController();
242211
const deps = makeDeps({
@@ -253,7 +222,7 @@ test("connection-state emitter fires onSuccess and cancels poll/backstop", async
253222

254223
await ctrl.start(deps);
255224

256-
// Emitter fires "connected" — should resolve without waiting for poll.
225+
// Emitter fires "connected" — should resolve without waiting for backstop.
257226
assert.ok(capturedListener !== null, "connection-state listener registered");
258227
capturedListener("connected");
259228

@@ -266,7 +235,6 @@ test("connection-state emitter fires onSuccess and cancels poll/backstop", async
266235
isPending: false,
267236
isWaitingOnReconnectHook: false,
268237
});
269-
assert.equal(deps._intervals.length, 0, "poll interval cancelled");
270238
assert.equal(deps._timers.length, 0, "backstop cancelled");
271239
});
272240

@@ -299,7 +267,7 @@ test("backstop fires onBackstop, not onSuccess, and resets state", async () => {
299267

300268
// ── Cancellation token ────────────────────────────────────────────────────────
301269

302-
test("cancellation token — superseded poll callback does not call onSuccess", async () => {
270+
test("cancellation token — superseded attempt does not call onSuccess", async () => {
303271
const ctrl = new RelayReconnectController();
304272
let preconnectCallCount = 0;
305273
let resolveFirstPreconnect;
@@ -375,11 +343,6 @@ test("cancel mid fast-path — preconnect resolves SUCCESSFULLY after cancel but
375343
"state is idle",
376344
);
377345
assert.equal(deps._timers.length, 0, "no timers outstanding after cancel");
378-
assert.equal(
379-
deps._intervals.length,
380-
0,
381-
"no intervals outstanding after cancel",
382-
);
383346
});
384347

385348
test("last subscriber unsubscribe cancels in-flight attempt", async () => {
@@ -505,7 +468,7 @@ test("OSS build (hookConfigured returns false) — runHook never called", async
505468

506469
// ── Synchronous connected emission ───────────────────────────────────────────
507470

508-
test("sync connected emission — onSuccess fires once, no interval/backstop installed, subscription cleaned up", async () => {
471+
test("sync connected emission — onSuccess fires once, no backstop installed, subscription cleaned up", async () => {
509472
const ctrl = new RelayReconnectController();
510473

511474
// subscribeToConnectionState fake that invokes the listener synchronously
@@ -538,7 +501,6 @@ test("sync connected emission — onSuccess fires once, no interval/backstop ins
538501
1,
539502
"onSuccess fires exactly once",
540503
);
541-
assert.equal(deps._intervals.length, 0, "no poll interval installed");
542504
assert.equal(deps._timers.length, 0, "no backstop timer installed");
543505
assert.equal(cleanupCalled, true, "subscription cleanup handle was called");
544506
assert.deepEqual(

‎desktop/src/shared/api/relayReconnectController.ts‎

Lines changed: 16 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,9 @@
1212
* returns quickly; any browser-based reconnect flow it triggers runs
1313
* asynchronously.
1414
*
15-
* 3. **Poll-until-connected** — retry `preconnect()` every POLL_INTERVAL_MS.
16-
* The moment the relay becomes reachable the next poll succeeds and
17-
* success is declared — the backstop is a ceiling, not a delay. The
18-
* connection-state emitter is also watched: if the session's background
19-
* retry loop reconnects first, we catch it immediately.
15+
* 3. **Wait for background reconnect** — observe the session's exponential-
16+
* backoff reconnect loop. Success is declared when its connection-state
17+
* emitter reports connected; the backstop is a UI ceiling, not a delay.
2018
*
2119
* The controller is a module-level singleton so all hook instances in the
2220
* same app share a single in-flight state. A cancellation token is bumped on
@@ -32,16 +30,13 @@
3230
export type ReconnectTimingPolicy = {
3331
/** Short deadline for the optimistic fast-path attempt. */
3432
fastPathTimeoutMs: number;
35-
/** Interval between poll attempts during phase 3. */
36-
pollIntervalMs: number;
37-
/** Maximum total time to keep polling before giving up. */
33+
/** Maximum total time to wait before returning control to the UI. */
3834
backstopMs: number;
3935
};
4036

4137
/** Current production reconnect timings. */
4238
export const DEFAULT_RECONNECT_TIMING_POLICY: ReconnectTimingPolicy = {
43-
fastPathTimeoutMs: 4_000,
44-
pollIntervalMs: 3_000,
39+
fastPathTimeoutMs: 11_000,
4540
backstopMs: 120_000,
4641
};
4742

@@ -61,8 +56,6 @@ export type ReconnectDeps = {
6156
onBackstop: () => void;
6257
setTimeout: (fn: () => void, ms: number) => number;
6358
clearTimeout: (id: number) => void;
64-
setInterval: (fn: () => void, ms: number) => number;
65-
clearInterval: (id: number) => void;
6659
};
6760

6861
function withDeadline<T>(
@@ -101,14 +94,12 @@ export class RelayReconnectController {
10194
// All async continuations capture the token at their creation point and
10295
// bail if it has since been superseded.
10396
private attemptToken = 0;
104-
// Active timers and subscription for the current attempt. The timer-clear
105-
// functions are stored from the deps of the most recent start() call so
106-
// that cancel() and teardown do not need the caller to supply deps again.
107-
private pollIntervalId: number | null = null;
97+
// Active timer and subscription for the current attempt. The timer-clear
98+
// function is stored from the deps of the most recent start() call so that
99+
// cancel() and teardown do not need the caller to supply deps again.
108100
private backstopId: number | null = null;
109101
private unsubscribeConnectionState: (() => void) | null = null;
110102
private clearTimeoutFn: ((id: number) => void) | null = null;
111-
private clearIntervalFn: ((id: number) => void) | null = null;
112103

113104
/** Subscribe to state changes. Fires immediately with the current state. */
114105
subscribe(listener: Listener): () => void {
@@ -117,7 +108,7 @@ export class RelayReconnectController {
117108
return () => {
118109
this.listeners.delete(listener);
119110
// Cancel the in-flight attempt when the last subscriber leaves — no UI
120-
// is watching the result, so letting poll/backstop callbacks fire
111+
// is watching the result, so letting backstop callbacks fire
121112
// (possibly mutating state or invoking onSuccess/onBackstop into a
122113
// stale closure) would be a resource and correctness leak.
123114
if (this.listeners.size === 0) {
@@ -141,7 +132,6 @@ export class RelayReconnectController {
141132

142133
// Store timer-clear fns so cancel() can clear timers without caller deps.
143134
this.clearTimeoutFn = deps.clearTimeout;
144-
this.clearIntervalFn = deps.clearInterval;
145135

146136
// Bump the cancellation token before any await.
147137
const token = ++this.attemptToken;
@@ -164,7 +154,7 @@ export class RelayReconnectController {
164154
return true;
165155
} catch {
166156
if (cancelled()) return false;
167-
// Fast path failed — continue to escalation or polling.
157+
// Fast path failed — continue to escalation or background reconnect.
168158
}
169159

170160
// ── Phase 2: escalation (hook-configured builds only) ───────────────────
@@ -184,7 +174,7 @@ export class RelayReconnectController {
184174
await deps.runHook();
185175
} catch (err) {
186176
// Non-fatal — hook failure means the browser-based reconnect flow may
187-
// not have opened, but we still poll for relay reachability.
177+
// not have opened, but the session still retries in the background.
188178
console.warn(
189179
"[RelayReconnectController] transport recovery hook failed:",
190180
err,
@@ -194,11 +184,10 @@ export class RelayReconnectController {
194184
this.setState({ isPending: true, isWaitingOnReconnectHook: true });
195185
}
196186

197-
// ── Phase 3: poll-until-connected ────────────────────────────────────────
198-
// Retry preconnect on a fixed interval. The moment the relay becomes
199-
// reachable the next poll fires success. The connection-state emitter is
200-
// also watched; if the session's background retry loop reconnects first,
201-
// we catch it here too.
187+
// ── Phase 3: wait for background reconnect ──────────────────────────────
188+
// The fast-path preconnect arms the session's exponential-backoff loop.
189+
// Observe it rather than issuing fixed-cadence attempts that consume its
190+
// pending retry timer.
202191
let resolved = false;
203192

204193
// Capture onSuccess/onBackstop at phase-3 entry so that cancel() (which
@@ -236,21 +225,10 @@ export class RelayReconnectController {
236225
return false;
237226
}
238227

239-
this.pollIntervalId = deps.setInterval(() => {
240-
if (resolved || cancelled()) return;
241-
void deps
242-
.preconnect()
243-
.then(onConnected)
244-
.catch(() => {
245-
// Poll failed — keep trying.
246-
});
247-
}, this.timingPolicy.pollIntervalMs);
248-
249228
this.backstopId = deps.setTimeout(() => {
250229
if (resolved || cancelled()) return;
251230
resolved = true;
252-
// keepAliveRequested remains true via preconnect() — the session's
253-
// background retry loop keeps running. The notification is soft.
231+
// The session's exponential-backoff reconnect loop remains armed.
254232
onBackstop();
255233
this.finish(() => {}, false);
256234
}, this.timingPolicy.backstopMs);
@@ -281,10 +259,6 @@ export class RelayReconnectController {
281259
}
282260

283261
private cancelTimers(): void {
284-
if (this.pollIntervalId !== null && this.clearIntervalFn !== null) {
285-
this.clearIntervalFn(this.pollIntervalId);
286-
this.pollIntervalId = null;
287-
}
288262
if (this.backstopId !== null && this.clearTimeoutFn !== null) {
289263
this.clearTimeoutFn(this.backstopId);
290264
this.backstopId = null;

‎desktop/src/shared/api/useReconnectRelay.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@ function buildDeps(onSuccess: () => void, onBackstop: () => void) {
3030
onBackstop,
3131
setTimeout: window.setTimeout.bind(window),
3232
clearTimeout: window.clearTimeout.bind(window),
33-
setInterval: window.setInterval.bind(window),
34-
clearInterval: window.clearInterval.bind(window),
3533
};
3634
}
3735

0 commit comments

Comments
 (0)