Skip to content

Commit b01fcbf

Browse files
committed
feat(#141): integrate automatic reconnection workflow when upgrade/please-reconnect notice arrives
1 parent e5020db commit b01fcbf

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/util/BaseWSClient.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,37 @@ export abstract class BaseWebsocketClient<
449449
});
450450
}
451451

452+
/**
453+
* Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously.
454+
* If closed, trigger a reconnect immediately
455+
*/
456+
public executeReconnectableClose(wsKey: TWSKey, reason: string) {
457+
this.logger.info(`${reason} - closing socket to reconnect`, {
458+
...WS_LOGGER_CATEGORY,
459+
wsKey,
460+
reason,
461+
});
462+
463+
this.clearTimers(wsKey);
464+
465+
const wasOpen = this.wsStore.isWsOpen(wsKey);
466+
if (wasOpen) {
467+
safeTerminateWs(this.wsStore.getWs(wsKey), true);
468+
}
469+
470+
if (!wasOpen) {
471+
this.logger.info(
472+
`${reason} - socket already closed - trigger immediate reconnect`,
473+
{
474+
...WS_LOGGER_CATEGORY,
475+
wsKey,
476+
reason,
477+
},
478+
);
479+
this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
480+
}
481+
}
482+
452483
public isConnected(wsKey: TWSKey): boolean {
453484
return this.wsStore.isConnectionState(
454485
wsKey,

src/websocket-client.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,31 @@ export class WebsocketClient extends BaseWebsocketClient<
704704
return results;
705705
}
706706

707+
if (msg.event === 'notice') {
708+
const WSNOTICE = {
709+
CLOSING_FOR_UPGRADE_RECOMMEND_RECONNECT: '64008',
710+
};
711+
if (msg?.code === WSNOTICE.CLOSING_FOR_UPGRADE_RECOMMEND_RECONNECT) {
712+
const closeReason = `Received notice (${msg.code} - "${msg?.msg}") - closing socket to reconnect`;
713+
this.logger.info(closeReason, {
714+
...WS_LOGGER_CATEGORY,
715+
...msg,
716+
wsKey,
717+
});
718+
719+
// Queue immediate reconnection workflow
720+
this.executeReconnectableClose(wsKey, closeReason);
721+
722+
// Emit notice to client for visibility
723+
results.push({
724+
eventType: 'update',
725+
event: emittableEvent,
726+
});
727+
728+
return results;
729+
}
730+
}
731+
707732
this.logger.info('Unhandled/unrecognised ws event message', {
708733
...WS_LOGGER_CATEGORY,
709734
message: msg || 'no message',

0 commit comments

Comments
 (0)