Skip to content

Commit f293ef4

Browse files
authored
fix(client): reset websocket reconnect attempt only after a healthy connection (#2506)
## Problem The WebSocket link reset the reconnect `attempt` as soon as a socket reached `OPEN`. If a server completes the handshake and then closes the socket straight away, `attempt` never goes above 1. That happens when auth is rejected after the upgrade (1008/4001), when the server is at a connection limit, or when it is draining. With `reconnect: { onClose: true }`, the default `delay` (`attempt === 1 ? 0 : 2_000`) and `onClose.delay` (0) then cause a reconnect on every handshake round trip with no pause. The documented backoff and `maxAttempt` never apply. ```ts new RPCLink({ connect: () => new WebSocket(url), connectOnInit: true, reconnect: { onClose: true } }) // against a server that accepts and immediately closes: reconnects forever, no delay ``` ## Fix `attempt` now resets only once a connection proves healthy: - it receives a message from the server, or - it stays open for at least 5 seconds before closing. This covers healthy connections that stay idle. A connection that closes sooner counts as a failed attempt. It gets the `delay` backoff, and it counts toward `maxAttempt`. Before this change, `maxAttempt` was only checked when `connect` itself failed. Now, once `attempt` reaches `maxAttempt`, the next attempt fails right away with the last close reason. It goes through the same `.catch` as a failed connect. Every call waiting on that connection gets `WebSocket reconnect failed after N attempt(s)`, with the close reason as its `cause`, before a later call can start a new cycle. Health is judged when the next attempt starts, in `getConnectedPeer`, and no timer is added. A socket still in `CLOSING` (its `close` event hasn't fired) is measured up to now. So a call made during the close handshake of a long-lived socket reconnects immediately as attempt 1, and the late `close` event can't reset the new cycle's count. A socket that closed is measured up to its `close`. So one that closed after a few milliseconds still counts as failed, even if the next call comes much later. ## Docs - JSDoc on `WebSocketLinkTransportAttemptInfo.attempt` describes when a connection counts as healthy. - `apps/content/docs/adapters/websocket.mdx` has a `:::info` note under Auto Reconnect. ## Tests New fake-timer tests in `rpc-link.test.ts`: - sockets that close right after opening get the default backoff (attempt 1 immediately, then 2 and 3 at 2 s each). **Fails without the fix.** - those sockets count toward `maxAttempt`. **Fails without the fix.** - a server message resets `attempt`. - when a cycle gives up after quick closes, two concurrent calls both fail with the give-up error, whose `cause` is the last close reason, and no new connection is made. - a call made while a healthy socket is still `CLOSING` reconnects as attempt 1, and the late `close` doesn't reset the new cycle. **Fails on the first commit of this PR.** - a socket that closed quickly still counts as failed when the next call comes 60 s later. The test "stops proactive reconnects once a reconnect cycle gives up" now keeps its first socket open for 5 s. That makes the socket count as healthy, which the test had assumed. `pnpm check` passes. `pnpm exec vitest run` passes except `openapi-generator.test.ts` > "names the nearest tsconfig when it does not include the file, and why", which also fails on `main`.
1 parent baa3350 commit f293ef4

3 files changed

Lines changed: 182 additions & 4 deletions

File tree

‎apps/content/docs/adapters/websocket.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,3 +323,7 @@ const link = new RPCLink({
323323
},
324324
})
325325
```
326+
327+
:::info
328+
A connection proves healthy once it receives a message from the server or stays open for 5 seconds. Only then does `attempt` reset to 1. A server that closes connections right after the handshake, for example to reject authentication, gets the `delay` backoff and the `maxAttempt` limit instead of an immediate reconnect loop.
329+
:::

‎packages/client/src/adapters/websocket/rpc-link.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,10 +680,156 @@ describe('rpcLink', () => {
680680
await vi.advanceTimersByTimeAsync(0)
681681
expect(connect).toHaveBeenCalledTimes(1)
682682

683+
await vi.advanceTimersByTimeAsync(5_000)
683684
await firstSocket.close()
684685
await vi.advanceTimersByTimeAsync(10_000)
685686

686687
expect(connect).toHaveBeenCalledTimes(3)
688+
expect(connect).toHaveBeenNthCalledWith(2, { totalAttempt: 2, attempt: 1 })
689+
expect(connect).toHaveBeenNthCalledWith(3, { totalAttempt: 3, attempt: 2 })
690+
})
691+
692+
it('treats a healthy socket that is still closing as healthy', async ({ onTestFinished }) => {
693+
vi.useFakeTimers()
694+
onTestFinished(() => {
695+
vi.useRealTimers()
696+
})
697+
698+
const firstSocket = createWs()
699+
const secondSocket = createWs(WEBSOCKET_CONNECTING)
700+
const connect = vi
701+
.fn()
702+
.mockImplementationOnce(() => firstSocket)
703+
.mockImplementationOnce(() => secondSocket)
704+
.mockImplementation(() => createWs(WEBSOCKET_CONNECTING))
705+
const orpc = createORPCClient(
706+
new RPCLink({ connect, connectOnInit: true, reconnect: true }),
707+
) as any
708+
709+
await vi.advanceTimersByTimeAsync(10_000)
710+
firstSocket.readyState = WEBSOCKET_CLOSING
711+
712+
void orpc.ping('input').catch(() => {})
713+
await vi.advanceTimersByTimeAsync(0)
714+
expect(connect).toHaveBeenNthCalledWith(2, { totalAttempt: 2, attempt: 1 })
715+
716+
// the late close event must not reset the new cycle
717+
await firstSocket.close()
718+
await secondSocket.close()
719+
await vi.advanceTimersByTimeAsync(2_000)
720+
expect(connect).toHaveBeenNthCalledWith(3, { totalAttempt: 3, attempt: 2 })
721+
})
722+
723+
describe('connections that close right after opening', () => {
724+
beforeEach(() => {
725+
vi.useFakeTimers()
726+
})
727+
728+
afterEach(() => {
729+
vi.useRealTimers()
730+
})
731+
732+
const createRejectingConnect = () =>
733+
vi.fn((_info: { totalAttempt: number; attempt: number }) => {
734+
const ws = createWs()
735+
setTimeout(() => ws.close({ code: 4001, reason: 'unauthorized' }))
736+
return ws
737+
})
738+
739+
it('keep the default backoff instead of reconnecting without delay', async () => {
740+
const connect = createRejectingConnect()
741+
742+
createORPCClient(new RPCLink({ connect, connectOnInit: true, reconnect: { onClose: true } }))
743+
744+
await vi.advanceTimersByTimeAsync(1_000)
745+
expect(connect).toHaveBeenCalledTimes(1)
746+
expect(connect).toHaveBeenNthCalledWith(1, { totalAttempt: 1, attempt: 1 })
747+
748+
await vi.advanceTimersByTimeAsync(2_000)
749+
expect(connect).toHaveBeenCalledTimes(2)
750+
expect(connect).toHaveBeenNthCalledWith(2, { totalAttempt: 2, attempt: 2 })
751+
752+
await vi.advanceTimersByTimeAsync(2_000)
753+
expect(connect).toHaveBeenCalledTimes(3)
754+
expect(connect).toHaveBeenNthCalledWith(3, { totalAttempt: 3, attempt: 3 })
755+
})
756+
757+
it('count toward maxAttempt', async () => {
758+
const connect = createRejectingConnect()
759+
760+
createORPCClient(
761+
new RPCLink({
762+
connect,
763+
connectOnInit: true,
764+
reconnect: { delay: () => 0, maxAttempt: 3, onClose: true },
765+
}),
766+
)
767+
768+
await vi.advanceTimersByTimeAsync(10_000)
769+
expect(connect).toHaveBeenCalledTimes(3)
770+
})
771+
772+
it('fail every waiting call with the last close reason when giving up', async () => {
773+
const connect = createRejectingConnect()
774+
const orpc = createORPCClient(
775+
new RPCLink({ connect, reconnect: { delay: () => 0, maxAttempt: 2 } }),
776+
) as any
777+
778+
const call = async (input: string) => {
779+
const result = orpc.ping(input).catch((error: unknown) => error)
780+
await vi.advanceTimersByTimeAsync(100)
781+
return result
782+
}
783+
784+
const closed = new AbortError('WebSocket closed (code 4001: unauthorized)')
785+
await expect(call('1')).resolves.toEqual(closed)
786+
await expect(call('2')).resolves.toEqual(closed)
787+
788+
const errors = await Promise.all([call('3'), call('4')])
789+
for (const error of errors) {
790+
expect(error).toEqual(new AbortError('WebSocket reconnect failed after 2 attempt(s)'))
791+
expect(error.cause).toEqual(closed)
792+
}
793+
expect(connect).toHaveBeenCalledTimes(2)
794+
})
795+
796+
it('count as failed even when the next call comes much later', async () => {
797+
const connect = createRejectingConnect()
798+
const orpc = createORPCClient(
799+
new RPCLink({ connect, connectOnInit: true, reconnect: true }),
800+
) as any
801+
802+
await vi.advanceTimersByTimeAsync(60_000)
803+
void orpc.ping('input').catch(() => {})
804+
await vi.advanceTimersByTimeAsync(2_000)
805+
806+
expect(connect).toHaveBeenCalledTimes(2)
807+
expect(connect).toHaveBeenNthCalledWith(2, { totalAttempt: 2, attempt: 2 })
808+
})
809+
810+
it('reset the attempt once the server sends a message', async () => {
811+
const firstSocket = createWs()
812+
const secondSocket = createWs()
813+
const connect = vi
814+
.fn()
815+
.mockImplementationOnce(() => firstSocket)
816+
.mockImplementationOnce(() => secondSocket)
817+
const orpc = createORPCClient(new RPCLink({ connect, reconnect: true })) as any
818+
819+
const call = orpc.ping('first')
820+
821+
await vi.waitFor(() => expect(firstSocket.send).toHaveBeenCalledTimes(1))
822+
await firstSocket.receive(
823+
await createResponseMessage({ id: getSentRequest(firstSocket).message.id }),
824+
)
825+
await expect(call).resolves.toEqual('pong')
826+
await firstSocket.close()
827+
828+
void orpc.ping('second').catch(() => {})
829+
await vi.advanceTimersByTimeAsync(0)
830+
831+
expect(connect).toHaveBeenNthCalledWith(2, { totalAttempt: 2, attempt: 1 })
832+
})
687833
})
688834

689835
// `ws` is EventEmitter-based, so an `error` event without a listener throws and crashes the process

‎packages/client/src/adapters/websocket/transport.ts‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ import type { StandardLinkTransport } from '../standard/index'
2626
const WEBSOCKET_CONNECTING = 0 satisfies WebSocket['CONNECTING']
2727
const WEBSOCKET_OPEN = 1 satisfies WebSocket['OPEN']
2828

29+
const HEALTHY_CONNECTION_DURATION = 5_000
30+
2931
export type WebSocketLike = Pick<
3032
WebSocket,
3133
'addEventListener' | 'removeEventListener' | 'send' | 'readyState'
@@ -42,7 +44,10 @@ export interface WebSocketLinkTransportAttemptInfo {
4244
/**
4345
* Attempt number within the current (re)connect cycle.
4446
* Starts at 1, increments on each consecutive failure, and resets to 1
45-
* once a connection succeeds or the cycle gives up. Use this for backoff calculations.
47+
* once a connection proves healthy or the cycle gives up. Use this for backoff calculations.
48+
*
49+
* A connection proves healthy when it receives a message from the server or stays
50+
* open for 5 seconds. A connection that closes sooner counts as a failure.
4651
*/
4752
attempt: number
4853
}
@@ -135,6 +140,13 @@ export interface WebSocketLinkTransportOptions<_T extends ClientContext> {
135140
decodePeerMessage?: DecodePeerMessageOptions | undefined
136141
}
137142

143+
interface Connection {
144+
websocket: WebSocketLike
145+
peer: ClientPeer
146+
isHealthy: () => boolean
147+
closeReason: () => undefined | AbortError
148+
}
149+
138150
export class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
139151
private readonly connect: WebSocketLinkTransportOptions<T>['connect']
140152
private readonly reconnectEnabled: boolean
@@ -179,7 +191,7 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
179191

180192
private totalAttempt = 0
181193
private attempt = 0
182-
private current: undefined | Promise<void | { websocket: WebSocketLike; peer: ClientPeer }>
194+
private current: undefined | Promise<void | Connection>
183195
private async getConnectedPeer(): Promise<ClientPeer> {
184196
const current = this.current
185197
const resolved = await current
@@ -192,13 +204,22 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
192204
return this.getConnectedPeer()
193205
}
194206

207+
if (resolved?.isHealthy()) {
208+
this.attempt = 0
209+
}
210+
195211
if (this.totalAttempt >= this.reconnectMaxTotalAttempt) {
196212
throw new AbortError(
197213
`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`,
198214
)
199215
}
200216

201217
this.current = (async () => {
218+
// Rejecting `current` lets the `.catch` below fail every call waiting on it
219+
if (this.attempt >= this.reconnectMaxAttempt) {
220+
throw resolved?.closeReason() ?? new AbortError('WebSocket is already closing or closed')
221+
}
222+
202223
this.totalAttempt += 1
203224
this.attempt += 1
204225

@@ -218,6 +239,8 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
218239
}
219240

220241
let closeReason: undefined | AbortError
242+
let closedAt: undefined | number
243+
let receivedMessage = false
221244

222245
const peer = new ClientPeer(async (message) => {
223246
// `send` silently discards data once the socket is closed, so requests would never settle
@@ -249,6 +272,7 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
249272
event.data instanceof Blob ? await loadBytes(event.data) : toStringOrBytes(event.data)
250273
const result = decodePeerMessage(message, this.decodePeerMessageOptions)
251274
if (result.matched && isServerPeerSendMessage(result.message)) {
275+
receivedMessage = true
252276
// Not awaited: `peer.message` runs handling message may be slow,
253277
// and awaiting it would block decoding of subsequent messages.
254278
void peer.message(result.message)
@@ -258,6 +282,7 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
258282

259283
websocket.addEventListener('close', async (event) => {
260284
closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`)
285+
closedAt = Date.now()
261286
connectingResolvers?.resolve()
262287
await peer.close(closeReason)
263288
})
@@ -280,8 +305,11 @@ export class WebSocketLinkTransport<T extends ClientContext> implements Standard
280305
})
281306
}
282307

283-
this.attempt = 0
284-
return { websocket, peer }
308+
const openedAt = Date.now()
309+
const isHealthy = () =>
310+
receivedMessage || (closedAt ?? Date.now()) - openedAt >= HEALTHY_CONNECTION_DURATION
311+
312+
return { websocket, peer, isHealthy, closeReason: () => closeReason }
285313
})().catch((error) => {
286314
if (!this.reconnectEnabled) {
287315
throw error

0 commit comments

Comments
 (0)