Harden client reconnect and protocol guards

This commit is contained in:
nav
2026-04-08 23:03:54 +00:00
parent 07c2438fb8
commit ddeed9a7b7
2 changed files with 81 additions and 9 deletions

View File

@@ -40,6 +40,7 @@ export class YonexusClientTransport implements ClientTransport {
private reconnectAttempts = 0;
private reconnectTimer: NodeJS.Timeout | null = null;
private heartbeatTimer: NodeJS.Timeout | null = null;
private shouldReconnect = false;
// Reconnect configuration
private readonly maxReconnectAttempts = 10;
@@ -67,6 +68,8 @@ export class YonexusClientTransport implements ClientTransport {
return;
}
this.shouldReconnect = true;
this.clearReconnectTimer();
this.setState("connecting");
const { mainHost } = this.options.config;
@@ -75,12 +78,13 @@ export class YonexusClientTransport implements ClientTransport {
this.ws = new WebSocket(mainHost);
const onOpen = () => {
this.ws?.off("error", onInitialError);
this.setState("connected");
this.reconnectAttempts = 0; // Reset on successful connection
resolve();
};
const onError = (error: Error) => {
const onInitialError = (error: Error) => {
this.setState("error");
if (this.options.onError) {
this.options.onError(error);
@@ -89,7 +93,7 @@ export class YonexusClientTransport implements ClientTransport {
};
this.ws.once("open", onOpen);
this.ws.once("error", onError);
this.ws.once("error", onInitialError);
this.ws.on("message", (data) => {
const message = data.toString("utf8");
@@ -114,6 +118,7 @@ export class YonexusClientTransport implements ClientTransport {
}
disconnect(): void {
this.shouldReconnect = false;
this.clearReconnectTimer();
this.stopHeartbeat();
@@ -153,18 +158,16 @@ export class YonexusClientTransport implements ClientTransport {
}
private handleDisconnect(code: number, reason: string): void {
const wasAuthenticated = this._state === "authenticated";
this.ws = null;
this.stopHeartbeat();
this.setState("disconnected");
// Don't reconnect if it was a normal close
if (code === 1000) {
// Don't reconnect if it was a normal close or caller explicitly stopped reconnects.
if (code === 1000 || !this.shouldReconnect) {
return;
}
// Attempt reconnect if we were previously authenticated
if (wasAuthenticated && this.reconnectAttempts < this.maxReconnectAttempts) {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.scheduleReconnect();
}
}