fix(websocket): settle failed sends and enforce SDK request deadlines

Settle queued sends once when a connection fails or closes before opening,
and reject further sends while preserving the original failure.

Include connection waits in SDK request deadlines without closing shared
connections or sending expired actions after a late connection.

Refs #665
Refs #666
This commit is contained in:
DrSmoothl committed 2026-11-07 12:57:25 +08:00
1 parent 9edc255a02
commit 87f7bd8c54
7 files changed
+442 -103

No files matched your search

+67 -25
View File
@@ -15,6 +15,7 @@ import {
WebSocket as InternalWebSocket,
CONNECTING,
OPEN,
CLOSING,
CLOSED,
isValidCloseCode,
type SendCallback,
@@ -137,6 +138,10 @@ export class WebSocketClient extends EventEmitter {
} as net.NetConnectOpts & tls.ConnectionOptions;
const onConnect = () => {
if (this._readyState !== CONNECTING) {
return;
}
const pathAndQuery = (this._url.pathname || '/') + (this._url.search || '');
const hostHeader =
this._url.port && Number(this._url.port) !== (this._secure ? 443 : 80)
@@ -194,6 +199,10 @@ export class WebSocketClient extends EventEmitter {
}
private _onHandshakeData(chunk: Buffer): void {
if (this._readyState !== CONNECTING) {
return;
}
this._handshakeBuf = Buffer.concat([this._handshakeBuf, chunk]);
const idx = this._handshakeBuf.indexOf('\r\n\r\n');
@@ -256,6 +265,7 @@ export class WebSocketClient extends EventEmitter {
this._socket.removeAllListeners('error');
this._socket.removeAllListeners('close');
this._handshakeBuf = Buffer.alloc(0);
this._readyState = OPEN;
this._ws = new InternalWebSocket(this._socket, {
isServer: false,
@@ -279,36 +289,65 @@ export class WebSocketClient extends EventEmitter {
this._ws._onData(rest);
}
for (const entry of this._pendingQueue) {
this._ws.send(entry.data, entry.options, entry.cb);
if (this._ws.readyState !== OPEN) {
this._failPendingSends(new Error('WebSocket is not open'));
return;
}
const pending = this._pendingQueue;
this._pendingQueue = [];
for (const entry of pending) {
this._ws.send(entry.data, entry.options, entry.cb);
}
}
private _onEarlyError(err: Error): void {
if (this._ws || this._readyState === CLOSED) {
return;
}
this._stopHandshake(err);
this.emit('error', err);
}
private _onEarlyClose(): void {
if (!this._ws) {
this._readyState = CLOSED;
this.emit('close', 1006, '');
if (this._ws || this._readyState === CLOSED) {
return;
}
this._stopHandshake(new Error('WebSocket closed before handshake completed'));
this._readyState = CLOSED;
this.emit('close', 1006, '');
}
private _failPendingSends(err: Error): void {
const pending = this._pendingQueue;
this._pendingQueue = [];
// Release queued payloads before invoking user code. Each callback is
// scheduled independently so reentrant sends cannot rejoin this queue.
for (const entry of pending) {
if (entry.cb) {
process.nextTick(entry.cb, err);
}
}
}
private _abort(msg: string): void {
const err = new Error('WebSocket handshake failed: ' + msg);
try {
this._socket.destroy();
} catch {
/* noop */
private _stopHandshake(err: Error): void {
if (this._readyState !== CONNECTING) {
return;
}
this.emit('error', err);
this._readyState = CLOSED;
this.emit('close', 1006, '');
this._readyState = CLOSING;
this._handshakeBuf = Buffer.alloc(0);
this._failPendingSends(err);
this._socket.destroy();
}
private _abort(msg: string): void {
this._onEarlyError(new Error('WebSocket handshake failed: ' + msg));
this._onEarlyClose();
}
send(
@@ -325,6 +364,17 @@ export class WebSocketClient extends EventEmitter {
options = undefined;
}
if (this._readyState !== CONNECTING) {
const err = new Error('WebSocket is not open');
if (cb) {
cb(err);
return;
}
throw err;
}
this._pendingQueue.push({ data, options, cb });
}
@@ -344,11 +394,7 @@ export class WebSocketClient extends EventEmitter {
return this._ws.close(code, reason);
}
try {
this._socket.destroy();
} catch {
/* noop */
}
this._stopHandshake(new Error('WebSocket closed before handshake completed'));
}
terminate(): void {
@@ -356,10 +402,6 @@ export class WebSocketClient extends EventEmitter {
return this._ws.terminate();
}
try {
this._socket.destroy();
} catch {
/* noop */
}
this._stopHandshake(new Error('WebSocket terminated before handshake completed'));
}
}
+106
View File
@@ -875,6 +875,112 @@ describe('WebSocketClient', () => {
expect(second.payload).toEqual(Buffer.from('bin'));
});
it('settles queued sends once on a rejected handshake and rejects further sends', async () => {
const { port, nextSocket } = await listenPlain();
const client = createClient(`ws://127.0.0.1:${port}`);
const events = track(client);
const reentrant = vi.fn();
const fromError = vi.fn();
const first = vi.fn(() => client.send('from failed callback', reentrant));
const second = vi.fn();
client.on('error', () => client.send('from error listener', fromError));
client.send('first', first);
client.send('second', { binary: true }, second);
client.send('without callback');
const socket = await nextSocket();
await readRequest(socket);
socket.end('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n');
await events.waitClose();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(first).toHaveBeenCalledExactlyOnceWith(events.errors[0]);
expect(second).toHaveBeenCalledExactlyOnceWith(events.errors[0]);
expect(reentrant).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(fromError).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(events.errors[0]?.message).toContain('Unexpected response status 401');
expect(events.closes).toEqual([{ code: 1006, reason: '' }]);
const afterClose = vi.fn();
client.send('after close', afterClose);
expect(afterClose).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(() => client.send('after close without callback')).toThrow('WebSocket is not open');
client.close();
client.terminate();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(first).toHaveBeenCalledTimes(1);
expect(second).toHaveBeenCalledTimes(1);
expect(events.closes).toHaveLength(1);
});
it.each(['close', 'terminate', 'peer close'] as const)(
'settles queued callbacks exactly once after %s before opening',
async (outcome) => {
const { port, nextSocket } = await listenPlain();
const client = createClient(`ws://127.0.0.1:${port}`);
const events = track(client);
const first = vi.fn();
const second = vi.fn();
client.send('first', first);
client.send('second', { binary: true }, second);
client.send('without callback');
const socket = await nextSocket();
await readRequest(socket);
if (outcome === 'peer close') {
socket.destroy();
} else {
client[outcome]();
const whileClosing = vi.fn();
client.send('while closing', whileClosing);
expect(whileClosing).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
}
await events.waitClose();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(first).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(second).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(client.readyState).toBe(WebSocketClient.CLOSED);
expect(() => client.send('after close')).toThrow('WebSocket is not open');
client.close();
client.terminate();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(first).toHaveBeenCalledTimes(1);
expect(second).toHaveBeenCalledTimes(1);
expect(events.closes).toEqual([{ code: 1006, reason: '' }]);
},
);
it('passes the original connection error to queued send callbacks', async () => {
const port = await unusedPort();
const client = createClient(`ws://127.0.0.1:${port}`);
const events = track(client);
const callback = vi.fn();
client.send('queued', callback);
await events.waitClose();
expect(events.errors[0]).toHaveProperty('code', 'ECONNREFUSED');
expect(callback).toHaveBeenCalledExactlyOnceWith(events.errors[0]);
expect(events.closes).toHaveLength(1);
});
it('settles the pre-open queue if an open listener immediately terminates the connection', async () => {
const { port, nextSocket } = await listenPlain();
const client = createClient(`ws://127.0.0.1:${port}`);
const events = track(client);
const first = vi.fn();
const second = vi.fn();
client.send('without callback');
client.send('first', first);
client.send('second', second);
client.once('open', () => client.terminate());
const socket = await nextSocket();
const req = await readRequest(socket);
socket.write(handshakeResponse(req.headers['sec-websocket-key']!));
await events.waitClose();
expect(first).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(second).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
expect(events.closes).toHaveLength(1);
});
it('delegates send/ping/pong/close after open and forwards control events', async () => {
const { port, nextSocket } = await listenPlain();
const client = createClient(`ws://127.0.0.1:${port}`);