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:
7 files changed
+442
-103
No files matched your search
@@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Fix ordinary WebSocket request deadlines to include connection waits, prevent expired requests from being sent after a late open, and preserve shared connections when an individual request times out or is cancelled. Refs #666.
|
||||
|
||||
- Add typed public contact profiles and opt-in friend-list enrichment via `getFriendList({ withProfile: true })` or `with_profile` on either list action; existing request options remain compatible. See [contact profiles](../onebot/CONTACT_PROFILES.md).
|
||||
|
||||
- Add a Node reverse WebSocket server with authenticated per-account sessions, Universal and paired API/Event channels, existing action/event/stream helpers, bounded buffers and explicit disconnect handling; see [REVERSE_WEBSOCKET.md](REVERSE_WEBSOCKET.md).
|
||||
|
||||
@@ -375,6 +375,9 @@ await status;
|
||||
```
|
||||
|
||||
`timeoutMs: 0` 表示关闭该请求的超时控制。
|
||||
WebSocket 普通请求的超时从调用时开始,包含等待连接建立和等待响应的总时间,
|
||||
连接成功后不会重新计时。等待连接时已超时或取消的请求不会在连接晚到后补发;
|
||||
取消单个请求不会关闭其他请求正在使用或等待的共享连接。
|
||||
|
||||
## 错误处理
|
||||
|
||||
|
||||
@@ -512,91 +512,94 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
params?: ActionParams<TAction>,
|
||||
options?: RequestOptions,
|
||||
): Promise<ApiResponse<ActionResult<TAction>>> {
|
||||
throwIfAborted(options?.signal);
|
||||
await raceWithAbort(
|
||||
this.connect(),
|
||||
options?.signal,
|
||||
'SnowLuma WebSocket request aborted before connection opened',
|
||||
);
|
||||
throwIfAborted(options?.signal);
|
||||
|
||||
const socket = this.connection?.socket;
|
||||
|
||||
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
|
||||
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
|
||||
}
|
||||
|
||||
const echo = options?.echo ?? createEcho();
|
||||
const key = echoKey(echo);
|
||||
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
|
||||
const abort = createRequestAbortState(timeoutMs, options?.signal);
|
||||
|
||||
if (this.pending.has(key)) {
|
||||
throw new SnowLumaConnectionError(
|
||||
'A WebSocket request with this echo is already pending',
|
||||
try {
|
||||
throwIfAborted(abort.signal);
|
||||
await raceWithAbort(
|
||||
this.connect(),
|
||||
abort.signal,
|
||||
'SnowLuma WebSocket request aborted before connection opened',
|
||||
);
|
||||
}
|
||||
throwIfAborted(abort.signal);
|
||||
|
||||
return new Promise<ApiResponse<ActionResult<TAction>>>((resolve, reject) => {
|
||||
const cleanup = (): void => {
|
||||
this.pending.delete(key);
|
||||
const socket = this.connection?.socket;
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
|
||||
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
|
||||
}
|
||||
|
||||
options?.signal?.removeEventListener('abort', abortListener);
|
||||
};
|
||||
const echo = options?.echo ?? createEcho();
|
||||
const key = echoKey(echo);
|
||||
|
||||
const pending: PendingRequest = {
|
||||
resolve: (response) => {
|
||||
cleanup();
|
||||
resolve(response as ApiResponse<ActionResult<TAction>>);
|
||||
},
|
||||
reject: (error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
},
|
||||
};
|
||||
|
||||
const timer =
|
||||
timeoutMs > 0
|
||||
? setTimeout(() => {
|
||||
pending.reject(
|
||||
new SnowLumaTimeoutError(
|
||||
`SnowLuma WebSocket request timed out after ${timeoutMs}ms`,
|
||||
timeoutMs,
|
||||
),
|
||||
);
|
||||
}, timeoutMs)
|
||||
: null;
|
||||
|
||||
const abortListener = () => {
|
||||
pending.reject(
|
||||
new SnowLumaAbortError('SnowLuma WebSocket request aborted', {
|
||||
cause: options?.signal?.reason,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
this.pending.set(key, pending);
|
||||
options?.signal?.addEventListener('abort', abortListener, { once: true });
|
||||
|
||||
try {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
action,
|
||||
params: toJsonObject(params as JsonObject | undefined),
|
||||
echo,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
pending.reject(
|
||||
new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', {
|
||||
cause: error,
|
||||
}),
|
||||
if (this.pending.has(key)) {
|
||||
throw new SnowLumaConnectionError(
|
||||
'A WebSocket request with this echo is already pending',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return await new Promise<ApiResponse<ActionResult<TAction>>>((resolve, reject) => {
|
||||
const cleanup = (): void => {
|
||||
if (this.pending.get(key) === pending) {
|
||||
this.pending.delete(key);
|
||||
}
|
||||
|
||||
abort.signal.removeEventListener('abort', abortListener);
|
||||
abort.cleanup();
|
||||
};
|
||||
|
||||
const pending: PendingRequest = {
|
||||
resolve: (response) => {
|
||||
cleanup();
|
||||
resolve(response as ApiResponse<ActionResult<TAction>>);
|
||||
},
|
||||
reject: (error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
},
|
||||
};
|
||||
|
||||
const abortListener = (): void => {
|
||||
pending.reject(
|
||||
new SnowLumaAbortError('SnowLuma WebSocket request aborted', {
|
||||
cause: abort.signal.reason,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
this.pending.set(key, pending);
|
||||
abort.signal.addEventListener('abort', abortListener, { once: true });
|
||||
|
||||
try {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
action,
|
||||
params: toJsonObject(params as JsonObject | undefined),
|
||||
echo,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
pending.reject(
|
||||
new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', {
|
||||
cause: error,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (abort.isTimedOut()) {
|
||||
throw new SnowLumaTimeoutError(
|
||||
`SnowLuma WebSocket request timed out after ${timeoutMs}ms`,
|
||||
timeoutMs,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
abort.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
override async *requestStream<TAction extends SnowLumaStreamAction>(
|
||||
|
||||
@@ -28,7 +28,7 @@ export type MessageFormat = 'array' | 'string';
|
||||
export interface RequestOptions {
|
||||
/** Echo value used to correlate OneBot request and response packets. */
|
||||
echo?: JsonValue;
|
||||
/** Override the client's default timeout for this request. Set to 0 to disable timeout. */
|
||||
/** Total request timeout, including connection and response waits. Set to 0 to disable. */
|
||||
timeoutMs?: number;
|
||||
/** Cancels the request before a SnowLuma response arrives. */
|
||||
signal?: AbortSignal;
|
||||
@@ -38,6 +38,6 @@ export interface RequestOptions {
|
||||
export interface SnowLumaClientOptions {
|
||||
/** Access token configured in SnowLuma's OneBot settings. */
|
||||
accessToken?: string;
|
||||
/** Default timeout for API calls in milliseconds. Defaults to 30000. */
|
||||
/** Default total timeout for API calls in milliseconds, including connection waits. Defaults to 30000. */
|
||||
requestTimeoutMs?: number;
|
||||
}
|
||||
@@ -302,6 +302,189 @@ describe('SnowLumaWebSocketClient', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('times out while opening and never sends the expired action after a late open', async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = new SnowLumaWebSocketClient({ webSocket: MockWebSocket });
|
||||
const settled = vi.fn();
|
||||
const request = client.getStatus({ timeoutMs: 20 }).then(settled, settled);
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(settled).toHaveBeenCalledExactlyOnceWith(expect.any(SnowLumaTimeoutError));
|
||||
expect(settled.mock.calls[0]![0]).toHaveProperty('timeoutMs', 20);
|
||||
socket.open();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(socket.sent).toHaveLength(0);
|
||||
expect(client.isConnected).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
client.close();
|
||||
await request;
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the client default as one deadline across connection and response waits', async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = new SnowLumaWebSocketClient({
|
||||
webSocket: MockWebSocket,
|
||||
requestTimeoutMs: 30,
|
||||
});
|
||||
const settled = vi.fn();
|
||||
const request = client.getStatus({ echo: 'deadline' }).then(settled, settled);
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
socket.open();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
await vi.advanceTimersByTimeAsync(9);
|
||||
expect(settled).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(settled).toHaveBeenCalledExactlyOnceWith(expect.any(SnowLumaTimeoutError));
|
||||
expect(settled.mock.calls[0]![0]).toHaveProperty('timeoutMs', 30);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
client.close();
|
||||
await request;
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['timeout', 'abort'] as const)(
|
||||
'keeps a shared opening connection usable after one request ends by %s',
|
||||
async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const client = new SnowLumaWebSocketClient({ webSocket: MockWebSocket });
|
||||
const controller = new AbortController();
|
||||
const remove = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
const firstSettled = vi.fn();
|
||||
const first = client
|
||||
.getStatus({ echo: 'first', timeoutMs: 20, signal: controller.signal })
|
||||
.then(firstSettled, firstSettled);
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
const second = client.getStatus({ echo: 'second', timeoutMs: 100 });
|
||||
const secondResult = second.catch((error: unknown) => error);
|
||||
|
||||
try {
|
||||
if (outcome === 'abort') {
|
||||
controller.abort('caller cancelled');
|
||||
}
|
||||
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(firstSettled).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.any(outcome === 'timeout' ? SnowLumaTimeoutError : SnowLumaAbortError),
|
||||
);
|
||||
|
||||
if (outcome === 'abort') {
|
||||
expect(firstSettled.mock.calls[0]![0]).toHaveProperty(
|
||||
'cause',
|
||||
'caller cancelled',
|
||||
);
|
||||
}
|
||||
|
||||
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
|
||||
expect(socket.readyState).toBe(0);
|
||||
socket.open();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(socket.sent.map((value) => JSON.parse(value).echo)).toEqual(['second']);
|
||||
socket.message(
|
||||
JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { online: true },
|
||||
echo: 'second',
|
||||
}),
|
||||
);
|
||||
await expect(second).resolves.toEqual({ online: true });
|
||||
expect(client.isConnected).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
client.close();
|
||||
await Promise.all([first, secondResult]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('allows zero timeout through connection and response waits', async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = new SnowLumaWebSocketClient({
|
||||
webSocket: MockWebSocket,
|
||||
requestTimeoutMs: 10,
|
||||
});
|
||||
const settled = vi.fn();
|
||||
const request = client
|
||||
.getStatus({ timeoutMs: 0, echo: 'unlimited' })
|
||||
.then(settled, settled);
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(settled).not.toHaveBeenCalled();
|
||||
socket.open();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(settled).not.toHaveBeenCalled();
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
socket.message(
|
||||
JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { online: true },
|
||||
echo: 'unlimited',
|
||||
}),
|
||||
);
|
||||
await request;
|
||||
expect(settled).toHaveBeenCalledExactlyOnceWith({ online: true });
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
client.close();
|
||||
await request;
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['close', 'constructor failure', 'pre-aborted'] as const)(
|
||||
'cleans request controls when opening ends with %s',
|
||||
async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const failure = new Error('opening failed');
|
||||
class OpeningSocket extends MockWebSocket {
|
||||
constructor(url: string) {
|
||||
if (outcome === 'constructor failure') {
|
||||
throw failure;
|
||||
}
|
||||
|
||||
super(url);
|
||||
}
|
||||
}
|
||||
const client = new SnowLumaWebSocketClient({ webSocket: OpeningSocket });
|
||||
const controller = new AbortController();
|
||||
const remove = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
|
||||
if (outcome === 'pre-aborted') {
|
||||
controller.abort(failure);
|
||||
}
|
||||
|
||||
const before = MockWebSocket.instances.length;
|
||||
const result = client
|
||||
.getStatus({ timeoutMs: 20, signal: controller.signal })
|
||||
.catch((error: unknown) => error);
|
||||
|
||||
if (outcome === 'close') {
|
||||
MockWebSocket.instances.at(-1)!.close();
|
||||
expect(await result).toBeInstanceOf(SnowLumaConnectionError);
|
||||
} else if (outcome === 'constructor failure') {
|
||||
expect(await result).toBe(failure);
|
||||
} else {
|
||||
expect(await result).toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(MockWebSocket.instances).toHaveLength(before);
|
||||
}
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
|
||||
client.close();
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects duplicate in-flight echoes without replacing the original request', async () => {
|
||||
const client = new SnowLumaWebSocketClient({ webSocket: MockWebSocket });
|
||||
const opening = client.connect();
|
||||
|
||||
Reference in new issue
Block a user