diff --git a/packages/net/src/auth.ts b/packages/net/src/auth.ts index 7bb1407..f69b470 100644 --- a/packages/net/src/auth.ts +++ b/packages/net/src/auth.ts @@ -82,7 +82,7 @@ export class AuthState extends EventEmitter { } }), on(socket, SocketEvent.Status, (status: SocketStatus) => { - if (status === SocketStatus.Closed) { + if (status === SocketStatus.Closed || status === SocketStatus.Error) { this.challenge = undefined this.request = undefined this.details = undefined diff --git a/packages/net/src/policy.ts b/packages/net/src/policy.ts index e601d6e..cd97a3e 100644 --- a/packages/net/src/policy.ts +++ b/packages/net/src/policy.ts @@ -95,8 +95,10 @@ export const socketPolicyConnectOnSend = (socket: Socket) => { } }), on(socket, SocketEvent.Sending, (message: ClientMessage) => { + const isClosed = [SocketStatus.Closed, SocketStatus.Error].includes(socket.status) + // When a new message is sent, make sure the socket is open (unless there was a recent error) - if (socket.status === SocketStatus.Closed && lastError < ago(30)) { + if (isClosed && lastError < ago(30)) { socket.open() } }), @@ -146,13 +148,15 @@ export const socketPolicyReopenActive = (socket: Socket) => { const unsubscribers = [ on(socket, SocketEvent.Status, (newStatus: SocketStatus) => { + const isClosed = [SocketStatus.Closed, SocketStatus.Error].includes(socket.status) + // Keep track of the most recent error if (newStatus === SocketStatus.Open) { lastOpen = Date.now() } // If the socket closed and we have no error, reopen it but don't flap - if (newStatus === SocketStatus.Closed && pending.size) { + if (isClosed && pending.size) { sleep(Math.max(0, 10_000 - (Date.now() - lastOpen))).then(() => { for (const message of pending.values()) { socket.send(message) diff --git a/packages/net/src/socket.ts b/packages/net/src/socket.ts index fa91f7a..b678255 100644 --- a/packages/net/src/socket.ts +++ b/packages/net/src/socket.ts @@ -89,7 +89,10 @@ export class Socket extends EventEmitter { this._ws.onclose = () => { this._ws = undefined this._sendQueue.stop() - this.emit(SocketEvent.Status, SocketStatus.Closed, this.url) + + if (this.status !== SocketStatus.Error) { + this.emit(SocketEvent.Status, SocketStatus.Closed, this.url) + } } this._ws.onmessage = (event: any) => {