fix(onebot): ignore close events from stale ws-client sockets (#97)
A hot reload that changes the binding signature (url / role / accessToken / reconnectIntervalMs) drives `await this.close()` then `await this.open()` back-to-back. `WsClientAdapter.close()` is synchronous and `WebSocket.close()` just schedules the close frame, so the OLD socket's `'close'` event fires AFTER the new socket has already been assigned to `this.socket`. The close handler did not check the event's origin, so it would null out `this.socket`, drop `connected`, and schedule an unwanted reconnect against the freshly-opened connection. Against a single-connection backend that kicks duplicates this snowballed into a reconnect storm where the bot and the backend repeatedly kicked each other off; against a permissive backend it still left the new connection in a degraded state (events couldn't be sent until the bogus reconnect rebuilt the socket). Add a one-line identity guard at the top of the close handler — when the event arrives from a socket that is no longer the current one, do nothing. The explicitlyClosed / isEnabled checks are kept as the second line of defence for the normal (current-socket) close path. Add three regression tests under tests/ws-client-stale-close.test.ts that mock `@snowluma/websocket` (same approach as adapter-reload-state-machine. test.ts, which avoids the native addon dependency): the reload race scenario from the issue, a real-current-socket close that MUST still drive reconnect, and a close() race against an in-flight close event.
This commit is contained in:
2 files changed
+189
No files matched your search
@@ -105,6 +105,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
// Ignore close events from a socket that is no longer the current
|
||||
// connection. A hot reload (signature change) calls close() then open()
|
||||
// back-to-back; the old socket's `'close'` event fires AFTER the new
|
||||
// one is already assigned to `this.socket`, and without this guard it
|
||||
// would null out `this.socket`, drop `connected`, and schedule an
|
||||
// unwanted reconnect — observable as a reconnect storm against a
|
||||
// single-connection backend that kicks duplicates. See issue #97.
|
||||
if (this.socket !== socket) return;
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
|
||||
Reference in new issue
Block a user