@tencent-connect/qqbot-nodejs 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +96 -0
- package/LICENSE +21 -0
- package/README.md +168 -85
- package/README.zh-CN.md +280 -0
- package/USAGE.md +87 -32
- package/dist/QQBot.d.ts +33 -3
- package/dist/QQBot.d.ts.map +1 -1
- package/dist/QQBot.js +84 -34
- package/dist/QQBot.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/protocol/api/token.d.ts.map +1 -1
- package/dist/protocol/api/token.js +29 -9
- package/dist/protocol/api/token.js.map +1 -1
- package/dist/protocol/gateway/constants.d.ts +6 -1
- package/dist/protocol/gateway/constants.d.ts.map +1 -1
- package/dist/protocol/gateway/constants.js +6 -1
- package/dist/protocol/gateway/constants.js.map +1 -1
- package/dist/protocol/gateway/errors.d.ts +22 -0
- package/dist/protocol/gateway/errors.d.ts.map +1 -0
- package/dist/protocol/gateway/errors.js +24 -0
- package/dist/protocol/gateway/errors.js.map +1 -0
- package/dist/protocol/gateway/gateway-connection.d.ts +45 -4
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
- package/dist/protocol/gateway/gateway-connection.js +252 -143
- package/dist/protocol/gateway/gateway-connection.js.map +1 -1
- package/dist/protocol/gateway/reconnect.d.ts +24 -1
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -1
- package/dist/protocol/gateway/reconnect.js +42 -6
- package/dist/protocol/gateway/reconnect.js.map +1 -1
- package/dist/protocol/index.d.ts +4 -3
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js +3 -2
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/utils/file-utils.d.ts +2 -2
- package/dist/protocol/utils/file-utils.js +2 -2
- package/dist/protocol/utils/image-size.d.ts +3 -3
- package/dist/protocol/utils/image-size.js +3 -3
- package/dist/protocol/utils/ref-index-store.d.ts +1 -1
- package/dist/protocol/utils/ref-index-store.js +1 -1
- package/package.json +23 -7
- package/src/QQBot.ts +93 -37
- package/src/index.ts +5 -0
- package/src/protocol/api/token.ts +34 -9
- package/src/protocol/gateway/constants.ts +6 -1
- package/src/protocol/gateway/errors.ts +32 -0
- package/src/protocol/gateway/gateway-connection.ts +288 -157
- package/src/protocol/gateway/reconnect.ts +61 -7
- package/src/protocol/index.ts +10 -1
- package/src/protocol/utils/file-utils.ts +2 -2
- package/src/protocol/utils/image-size.ts +3 -3
- package/src/protocol/utils/ref-index-store.ts +1 -1
|
@@ -8,14 +8,28 @@
|
|
|
8
8
|
* (delegated via callbacks), business policies, message queueing.
|
|
9
9
|
*
|
|
10
10
|
* All state injected through the constructor — no module-level globals.
|
|
11
|
+
*
|
|
12
|
+
* Lifecycle invariants:
|
|
13
|
+
* - State transitions (reconnect scheduling / settling) happen before any
|
|
14
|
+
* user callback is notified, and every callback is isolated, so a throwing
|
|
15
|
+
* handler can never stall the loop.
|
|
16
|
+
* - Terminal failures are reported once, by rejecting `start()`.
|
|
11
17
|
*/
|
|
12
18
|
|
|
13
19
|
import WebSocket from "ws";
|
|
14
20
|
import type { GatewayAccount, InteractionEvent, Logger, WSPayload } from "../types.js";
|
|
15
21
|
import { decodeGatewayMessageData } from "./codec.js";
|
|
16
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
FULL_INTENTS,
|
|
24
|
+
GatewayCloseCode,
|
|
25
|
+
GatewayOp,
|
|
26
|
+
HANDSHAKE_TIMEOUT_MS,
|
|
27
|
+
INVALID_SESSION_DELAY,
|
|
28
|
+
RATE_LIMIT_DELAY,
|
|
29
|
+
} from "./constants.js";
|
|
30
|
+
import { GatewayError, GatewayErrorCode } from "./errors.js";
|
|
17
31
|
import { dispatchEvent, type InboundMessage } from "./event-dispatcher.js";
|
|
18
|
-
import { ReconnectState } from "./reconnect.js";
|
|
32
|
+
import { ReconnectState, type ReconnectPolicy } from "./reconnect.js";
|
|
19
33
|
|
|
20
34
|
/** Persisted session info for RESUME after reconnection. */
|
|
21
35
|
export interface PersistedSession {
|
|
@@ -30,6 +44,15 @@ export interface SessionPersistencePort {
|
|
|
30
44
|
clear: () => void;
|
|
31
45
|
}
|
|
32
46
|
|
|
47
|
+
/** A transport disconnect, reported before any reconnect attempt. */
|
|
48
|
+
export interface GatewayDisconnect {
|
|
49
|
+
/** Remote close code; `1000` for gateway-requested reconnects (opcode 7 / 9). */
|
|
50
|
+
code: number;
|
|
51
|
+
reason: string;
|
|
52
|
+
/** `false` means the retry budget is spent or the close is fatal; `start()` is about to reject. */
|
|
53
|
+
willReconnect: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
33
56
|
export interface GatewayConnectionOptions {
|
|
34
57
|
account: GatewayAccount;
|
|
35
58
|
abortSignal: AbortSignal;
|
|
@@ -51,18 +74,27 @@ export interface GatewayConnectionOptions {
|
|
|
51
74
|
/** Custom intent mask. Defaults to FULL_INTENTS. */
|
|
52
75
|
intents?: number;
|
|
53
76
|
|
|
77
|
+
/** Reconnect budget. Unlimited by default; set `maxAttempts` when an outer supervisor owns restarts. */
|
|
78
|
+
reconnect?: Partial<ReconnectPolicy>;
|
|
79
|
+
/** WebSocket upgrade timeout in ms. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */
|
|
80
|
+
handshakeTimeoutMs?: number;
|
|
81
|
+
|
|
54
82
|
// ---- Event handlers ----
|
|
55
83
|
onReady?: (data: unknown) => void;
|
|
56
84
|
onResumed?: (data: unknown) => void;
|
|
85
|
+
/** Recoverable failures (connect errors, socket errors). Terminal failures reject `start()` instead. */
|
|
57
86
|
onError?: (error: Error) => void;
|
|
87
|
+
onDisconnected?: (event: GatewayDisconnect) => void;
|
|
58
88
|
onMessage: (msg: InboundMessage) => void | Promise<void>;
|
|
59
89
|
onInteraction?: (event: InteractionEvent) => void | Promise<void>;
|
|
60
90
|
onRawEvent?: (type: string, data: unknown) => void | Promise<void>;
|
|
61
91
|
}
|
|
62
92
|
|
|
63
|
-
/** Pure-protocol gateway connection. */
|
|
93
|
+
/** Pure-protocol gateway connection. Single-use: create a new instance to restart. */
|
|
64
94
|
export class GatewayConnection {
|
|
65
95
|
private isAborted = false;
|
|
96
|
+
private run: Promise<void> | null = null;
|
|
97
|
+
private finish: (error?: Error) => void = () => {};
|
|
66
98
|
private currentWs: WebSocket | null = null;
|
|
67
99
|
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
|
68
100
|
private sessionId: string | null = null;
|
|
@@ -77,19 +109,48 @@ export class GatewayConnection {
|
|
|
77
109
|
|
|
78
110
|
constructor(opts: GatewayConnectionOptions) {
|
|
79
111
|
this.opts = opts;
|
|
80
|
-
this.reconnect = new ReconnectState(opts.account.accountId, opts.log);
|
|
112
|
+
this.reconnect = new ReconnectState(opts.account.accountId, opts.log, opts.reconnect);
|
|
81
113
|
const ua = opts.userAgent ?? "qqbot-nodejs/unknown";
|
|
82
114
|
this.resolveUserAgent = typeof ua === "function" ? ua : () => ua;
|
|
83
115
|
}
|
|
84
116
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
117
|
+
/**
|
|
118
|
+
* Start the connection loop.
|
|
119
|
+
*
|
|
120
|
+
* Resolves when `abortSignal` fires. Rejects with a {@link GatewayError} when
|
|
121
|
+
* a finite reconnect budget is exhausted (`RETRY_EXHAUSTED`) or the gateway sends
|
|
122
|
+
* a non-retryable close (`FATAL_CLOSE`). Repeated calls return the same promise.
|
|
123
|
+
*/
|
|
124
|
+
start(): Promise<void> {
|
|
125
|
+
this.run ??= new Promise<void>((resolve, reject) => {
|
|
126
|
+
const signal = this.opts.abortSignal;
|
|
127
|
+
const onAbort = () => this.finish();
|
|
128
|
+
this.finish = (error) => {
|
|
129
|
+
if (this.isAborted) return;
|
|
130
|
+
this.isAborted = true;
|
|
131
|
+
signal.removeEventListener("abort", onAbort);
|
|
132
|
+
this.clearReconnectTimer();
|
|
133
|
+
this.cleanup();
|
|
134
|
+
if (error) {
|
|
135
|
+
reject(error);
|
|
136
|
+
} else {
|
|
137
|
+
resolve();
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
if (signal.aborted) {
|
|
141
|
+
this.finish();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
145
|
+
try {
|
|
146
|
+
this.restoreSession();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
this.finish(toError(error));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
void this.connect();
|
|
92
152
|
});
|
|
153
|
+
return this.run;
|
|
93
154
|
}
|
|
94
155
|
|
|
95
156
|
// ============ Session persistence ============
|
|
@@ -106,63 +167,92 @@ export class GatewayConnection {
|
|
|
106
167
|
}
|
|
107
168
|
|
|
108
169
|
private saveCurrentSession(): void {
|
|
109
|
-
|
|
170
|
+
const { session } = this.opts;
|
|
171
|
+
if (!this.sessionId || !session) {
|
|
110
172
|
return;
|
|
111
173
|
}
|
|
112
|
-
this.
|
|
113
|
-
|
|
114
|
-
lastSeq: this.lastSeq,
|
|
115
|
-
});
|
|
174
|
+
const snapshot = { sessionId: this.sessionId, lastSeq: this.lastSeq };
|
|
175
|
+
this.notify("session.save", () => session.save(snapshot));
|
|
116
176
|
}
|
|
117
177
|
|
|
118
|
-
|
|
178
|
+
private resetSession(): void {
|
|
179
|
+
this.sessionId = null;
|
|
180
|
+
this.lastSeq = null;
|
|
181
|
+
const { session } = this.opts;
|
|
182
|
+
if (session) this.notify("session.clear", () => session.clear());
|
|
183
|
+
}
|
|
119
184
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
185
|
+
// ============ Callbacks + cleanup ============
|
|
186
|
+
|
|
187
|
+
/** Invoke a user callback without letting sync throws or async rejections escape. */
|
|
188
|
+
private notify(name: string, invoke: () => unknown): void {
|
|
189
|
+
const report = (err: unknown) => {
|
|
190
|
+
this.opts.log?.error(
|
|
191
|
+
`[${this.opts.account.accountId}] ${name} handler threw: ${toError(err).message}`,
|
|
192
|
+
);
|
|
193
|
+
};
|
|
194
|
+
try {
|
|
195
|
+
const result = invoke();
|
|
196
|
+
if (isPromiseLike(result)) Promise.resolve(result).catch(report);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
report(err);
|
|
199
|
+
}
|
|
129
200
|
}
|
|
130
201
|
|
|
202
|
+
/** Release the socket and heartbeat. Emits nothing. */
|
|
131
203
|
private cleanup(): void {
|
|
132
204
|
if (this.heartbeatInterval) {
|
|
133
205
|
clearInterval(this.heartbeatInterval);
|
|
134
206
|
this.heartbeatInterval = null;
|
|
135
207
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
(this.currentWs.readyState === WebSocket.OPEN ||
|
|
139
|
-
this.currentWs.readyState === WebSocket.CONNECTING)
|
|
140
|
-
) {
|
|
141
|
-
this.currentWs.close();
|
|
142
|
-
}
|
|
208
|
+
const ws = this.currentWs;
|
|
209
|
+
// Retire ownership before close: ws can emit error/close after a replacement exists.
|
|
143
210
|
this.currentWs = null;
|
|
211
|
+
this.isConnecting = false;
|
|
212
|
+
if (ws && ws.readyState !== WebSocket.CLOSED) ws.terminate();
|
|
144
213
|
}
|
|
145
214
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
private scheduleReconnect(customDelay?: number): void {
|
|
149
|
-
if (this.isAborted || this.reconnect.isExhausted()) {
|
|
150
|
-
this.opts.log?.error(
|
|
151
|
-
`[${this.opts.account.accountId}] Max reconnect attempts reached or aborted`,
|
|
152
|
-
);
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
215
|
+
private clearReconnectTimer(): void {
|
|
155
216
|
if (this.reconnectTimer) {
|
|
156
217
|
clearTimeout(this.reconnectTimer);
|
|
157
218
|
this.reconnectTimer = null;
|
|
158
219
|
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ============ Reconnect ============
|
|
223
|
+
|
|
224
|
+
/** Schedule the next attempt, or return the terminal error when the budget is spent. */
|
|
225
|
+
private planReconnect(
|
|
226
|
+
customDelay?: number,
|
|
227
|
+
failure: { closeCode?: number; cause?: unknown } = {},
|
|
228
|
+
): GatewayError | null {
|
|
229
|
+
if (this.reconnect.isExhausted()) {
|
|
230
|
+
const error = new GatewayError(
|
|
231
|
+
`Max reconnect attempts reached (${this.reconnect.maxAttempts})`,
|
|
232
|
+
GatewayErrorCode.RETRY_EXHAUSTED,
|
|
233
|
+
failure.closeCode,
|
|
234
|
+
{ cause: failure.cause },
|
|
235
|
+
);
|
|
236
|
+
this.opts.log?.error(`[${this.opts.account.accountId}] ${error.message}`);
|
|
237
|
+
return error;
|
|
238
|
+
}
|
|
239
|
+
this.clearReconnectTimer();
|
|
159
240
|
const delay = this.reconnect.getNextDelay(customDelay);
|
|
160
241
|
this.reconnectTimer = setTimeout(() => {
|
|
161
242
|
this.reconnectTimer = null;
|
|
162
|
-
|
|
163
|
-
void this.connect();
|
|
164
|
-
}
|
|
243
|
+
void this.connect();
|
|
165
244
|
}, delay);
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Report a disconnect after the reconnect decision is made, then settle if terminal. */
|
|
249
|
+
private afterDisconnect(code: number, reason: string, terminal: GatewayError | null): void {
|
|
250
|
+
const { onDisconnected } = this.opts;
|
|
251
|
+
if (onDisconnected) {
|
|
252
|
+
const event: GatewayDisconnect = { code, reason, willReconnect: terminal === null };
|
|
253
|
+
this.notify("onDisconnected", () => onDisconnected(event));
|
|
254
|
+
}
|
|
255
|
+
if (terminal) this.finish(terminal);
|
|
166
256
|
}
|
|
167
257
|
|
|
168
258
|
// ============ Connect ============
|
|
@@ -170,14 +260,15 @@ export class GatewayConnection {
|
|
|
170
260
|
private async connect(): Promise<void> {
|
|
171
261
|
const { log, account } = this.opts;
|
|
172
262
|
|
|
263
|
+
if (this.isAborted) return;
|
|
173
264
|
if (this.isConnecting) {
|
|
174
265
|
log?.debug?.(`[${account.accountId}] Already connecting, skip`);
|
|
175
266
|
return;
|
|
176
267
|
}
|
|
268
|
+
this.cleanup();
|
|
177
269
|
this.isConnecting = true;
|
|
178
270
|
|
|
179
271
|
try {
|
|
180
|
-
this.cleanup();
|
|
181
272
|
if (this.shouldRefreshToken) {
|
|
182
273
|
log?.debug?.(`[${account.accountId}] Refreshing token...`);
|
|
183
274
|
this.opts.clearTokenCache?.();
|
|
@@ -185,118 +276,139 @@ export class GatewayConnection {
|
|
|
185
276
|
}
|
|
186
277
|
|
|
187
278
|
const accessToken = await this.opts.getAccessToken();
|
|
279
|
+
if (this.isAborted) return;
|
|
188
280
|
log?.info(`[${account.accountId}] ✅ Access token obtained`);
|
|
189
281
|
const gatewayUrl = await this.opts.getGatewayUrl(accessToken);
|
|
282
|
+
if (this.isAborted) return;
|
|
190
283
|
log?.info(`[${account.accountId}] Connecting to ${gatewayUrl}`);
|
|
191
284
|
|
|
192
|
-
|
|
193
|
-
headers: { "User-Agent": this.resolveUserAgent() },
|
|
194
|
-
});
|
|
195
|
-
this.currentWs = ws;
|
|
196
|
-
|
|
197
|
-
ws.on("open", () => {
|
|
198
|
-
log?.info(`[${account.accountId}] WebSocket connected`);
|
|
199
|
-
this.isConnecting = false;
|
|
200
|
-
this.reconnect.onConnected();
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
ws.on("message", async (data) => {
|
|
204
|
-
try {
|
|
205
|
-
const rawData = decodeGatewayMessageData(data);
|
|
206
|
-
const payload = JSON.parse(rawData) as WSPayload;
|
|
207
|
-
const { op, d, s, t } = payload;
|
|
208
|
-
|
|
209
|
-
if (s) {
|
|
210
|
-
this.lastSeq = s;
|
|
211
|
-
this.saveCurrentSession();
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
switch (op) {
|
|
215
|
-
case GatewayOp.HELLO:
|
|
216
|
-
this.handleHello(ws, d, accessToken);
|
|
217
|
-
break;
|
|
218
|
-
|
|
219
|
-
case GatewayOp.DISPATCH: {
|
|
220
|
-
log?.debug?.(
|
|
221
|
-
`[${account.accountId}] Dispatch event: t=${t} payload=${previewPayload(d)}`,
|
|
222
|
-
);
|
|
223
|
-
const result = dispatchEvent(t ?? "", d, account.accountId, log);
|
|
224
|
-
if (result.action === "ready") {
|
|
225
|
-
this.sessionId = result.sessionId;
|
|
226
|
-
this.saveCurrentSession();
|
|
227
|
-
this.opts.onReady?.(result.data);
|
|
228
|
-
} else if (result.action === "resumed") {
|
|
229
|
-
(this.opts.onResumed ?? this.opts.onReady)?.(result.data);
|
|
230
|
-
this.saveCurrentSession();
|
|
231
|
-
} else if (result.action === "interaction") {
|
|
232
|
-
// Interaction 有 handler → 调用;否则 fallback 到 rawEvent
|
|
233
|
-
if (this.opts.onInteraction) {
|
|
234
|
-
void Promise.resolve(this.opts.onInteraction(result.event));
|
|
235
|
-
} else if (this.opts.onRawEvent) {
|
|
236
|
-
void Promise.resolve(this.opts.onRawEvent(payload.t!, payload.d));
|
|
237
|
-
}
|
|
238
|
-
} else if (result.action === "message") {
|
|
239
|
-
void Promise.resolve(this.opts.onMessage(result.msg));
|
|
240
|
-
} else if (result.action === "raw") {
|
|
241
|
-
if (this.opts.onRawEvent) {
|
|
242
|
-
void Promise.resolve(this.opts.onRawEvent(result.type, result.data));
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
break;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
case GatewayOp.HEARTBEAT_ACK:
|
|
249
|
-
break;
|
|
250
|
-
|
|
251
|
-
case GatewayOp.RECONNECT:
|
|
252
|
-
this.cleanup();
|
|
253
|
-
this.scheduleReconnect();
|
|
254
|
-
break;
|
|
255
|
-
|
|
256
|
-
case GatewayOp.INVALID_SESSION: {
|
|
257
|
-
const canResume = d as boolean;
|
|
258
|
-
if (!canResume) {
|
|
259
|
-
this.sessionId = null;
|
|
260
|
-
this.lastSeq = null;
|
|
261
|
-
this.opts.session?.clear();
|
|
262
|
-
this.shouldRefreshToken = true;
|
|
263
|
-
}
|
|
264
|
-
this.cleanup();
|
|
265
|
-
this.scheduleReconnect(3000);
|
|
266
|
-
break;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
} catch (err) {
|
|
270
|
-
log?.error(
|
|
271
|
-
`[${account.accountId}] Message parse error: ${err instanceof Error ? err.message : String(err)}`,
|
|
272
|
-
);
|
|
273
|
-
}
|
|
274
|
-
});
|
|
275
|
-
|
|
276
|
-
ws.on("close", (code, reason) => {
|
|
277
|
-
log?.info(`[${account.accountId}] WebSocket closed: ${code} ${reason.toString()}`);
|
|
278
|
-
this.isConnecting = false;
|
|
279
|
-
this.handleClose(code);
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
ws.on("error", (err) => {
|
|
283
|
-
log?.error(`[${account.accountId}] WebSocket error: ${err.message}`);
|
|
284
|
-
this.opts.onError?.(err);
|
|
285
|
-
});
|
|
285
|
+
this.openSocket(gatewayUrl, accessToken);
|
|
286
286
|
} catch (err) {
|
|
287
|
+
if (this.isAborted) return;
|
|
287
288
|
this.isConnecting = false;
|
|
288
|
-
const
|
|
289
|
-
log?.error(`[${account.accountId}] Connection failed: ${
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
}
|
|
289
|
+
const error = toError(err);
|
|
290
|
+
log?.error(`[${account.accountId}] Connection failed: ${error.message}`);
|
|
291
|
+
const terminal = this.planReconnect(
|
|
292
|
+
isRateLimitError(error.message) ? RATE_LIMIT_DELAY : undefined,
|
|
293
|
+
{ cause: error },
|
|
294
|
+
);
|
|
295
|
+
const { onError } = this.opts;
|
|
296
|
+
if (onError) this.notify("onError", () => onError(error));
|
|
297
|
+
if (terminal) this.finish(terminal);
|
|
295
298
|
}
|
|
296
299
|
}
|
|
297
300
|
|
|
301
|
+
private openSocket(gatewayUrl: string, accessToken: string): void {
|
|
302
|
+
const { log, account } = this.opts;
|
|
303
|
+
const ws = new WebSocket(gatewayUrl, {
|
|
304
|
+
headers: { "User-Agent": this.resolveUserAgent() },
|
|
305
|
+
handshakeTimeout: this.opts.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS,
|
|
306
|
+
});
|
|
307
|
+
this.currentWs = ws;
|
|
308
|
+
|
|
309
|
+
ws.on("open", () => {
|
|
310
|
+
if (ws !== this.currentWs) return;
|
|
311
|
+
log?.info(`[${account.accountId}] WebSocket connected`);
|
|
312
|
+
this.isConnecting = false;
|
|
313
|
+
this.reconnect.onSocketOpen();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
ws.on("message", (data) => {
|
|
317
|
+
if (ws !== this.currentWs) return;
|
|
318
|
+
try {
|
|
319
|
+
const payload = JSON.parse(decodeGatewayMessageData(data)) as WSPayload;
|
|
320
|
+
this.handlePayload(ws, payload, accessToken);
|
|
321
|
+
} catch (err) {
|
|
322
|
+
log?.error(`[${account.accountId}] Message parse error: ${toError(err).message}`);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
ws.on("close", (code, reason) => {
|
|
327
|
+
if (ws !== this.currentWs) return;
|
|
328
|
+
const reasonText = reason.toString();
|
|
329
|
+
log?.info(`[${account.accountId}] WebSocket closed: ${code} ${reasonText}`);
|
|
330
|
+
this.isConnecting = false;
|
|
331
|
+
this.handleClose(code, reasonText);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
ws.on("error", (err) => {
|
|
335
|
+
if (ws !== this.currentWs) return;
|
|
336
|
+
log?.error(`[${account.accountId}] WebSocket error: ${err.message}`);
|
|
337
|
+
const { onError } = this.opts;
|
|
338
|
+
if (onError) this.notify("onError", () => onError(err));
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
298
342
|
// ============ Protocol handlers ============
|
|
299
343
|
|
|
344
|
+
private handlePayload(ws: WebSocket, payload: WSPayload, accessToken: string): void {
|
|
345
|
+
const { op, d, s } = payload;
|
|
346
|
+
|
|
347
|
+
if (s) {
|
|
348
|
+
this.lastSeq = s;
|
|
349
|
+
this.saveCurrentSession();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
switch (op) {
|
|
353
|
+
case GatewayOp.HELLO:
|
|
354
|
+
this.handleHello(ws, d, accessToken);
|
|
355
|
+
break;
|
|
356
|
+
|
|
357
|
+
case GatewayOp.DISPATCH:
|
|
358
|
+
this.handleDispatch(payload);
|
|
359
|
+
break;
|
|
360
|
+
|
|
361
|
+
case GatewayOp.HEARTBEAT_ACK:
|
|
362
|
+
break;
|
|
363
|
+
|
|
364
|
+
case GatewayOp.RECONNECT:
|
|
365
|
+
this.handleGatewayReconnect("Gateway requested reconnect");
|
|
366
|
+
break;
|
|
367
|
+
|
|
368
|
+
case GatewayOp.INVALID_SESSION:
|
|
369
|
+
// d = whether the session can be resumed
|
|
370
|
+
if (!d) {
|
|
371
|
+
this.resetSession();
|
|
372
|
+
this.shouldRefreshToken = true;
|
|
373
|
+
}
|
|
374
|
+
this.handleGatewayReconnect("Invalid gateway session", INVALID_SESSION_DELAY);
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private handleDispatch(payload: WSPayload): void {
|
|
380
|
+
const { log, account } = this.opts;
|
|
381
|
+
const { d, t } = payload;
|
|
382
|
+
log?.debug?.(`[${account.accountId}] Dispatch event: t=${t} payload=${previewPayload(d)}`);
|
|
383
|
+
const result = dispatchEvent(t ?? "", d, account.accountId, log);
|
|
384
|
+
|
|
385
|
+
if (result.action === "ready") {
|
|
386
|
+
this.sessionId = result.sessionId;
|
|
387
|
+
this.reconnect.onConnected();
|
|
388
|
+
this.saveCurrentSession();
|
|
389
|
+
const { onReady } = this.opts;
|
|
390
|
+
if (onReady) this.notify("onReady", () => onReady(result.data));
|
|
391
|
+
} else if (result.action === "resumed") {
|
|
392
|
+
this.reconnect.onConnected();
|
|
393
|
+
this.saveCurrentSession();
|
|
394
|
+
const onResumed = this.opts.onResumed ?? this.opts.onReady;
|
|
395
|
+
if (onResumed) this.notify("onResumed", () => onResumed(result.data));
|
|
396
|
+
} else if (result.action === "interaction") {
|
|
397
|
+
// Interaction 有 handler → 调用;否则 fallback 到 rawEvent
|
|
398
|
+
const { onInteraction, onRawEvent } = this.opts;
|
|
399
|
+
if (onInteraction) {
|
|
400
|
+
this.notify("onInteraction", () => onInteraction(result.event));
|
|
401
|
+
} else if (onRawEvent) {
|
|
402
|
+
this.notify("onRawEvent", () => onRawEvent(t ?? "", d));
|
|
403
|
+
}
|
|
404
|
+
} else if (result.action === "message") {
|
|
405
|
+
this.notify("onMessage", () => this.opts.onMessage(result.msg));
|
|
406
|
+
} else if (result.action === "raw") {
|
|
407
|
+
const { onRawEvent } = this.opts;
|
|
408
|
+
if (onRawEvent) this.notify("onRawEvent", () => onRawEvent(result.type, result.data));
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
300
412
|
private handleHello(ws: WebSocket, d: unknown, accessToken: string): void {
|
|
301
413
|
const intents = this.opts.intents ?? FULL_INTENTS;
|
|
302
414
|
if (this.sessionId && this.lastSeq !== null) {
|
|
@@ -334,13 +446,18 @@ export class GatewayConnection {
|
|
|
334
446
|
}, interval);
|
|
335
447
|
}
|
|
336
448
|
|
|
337
|
-
|
|
449
|
+
/** Opcode 7 / 9: drop the socket locally and reconnect. */
|
|
450
|
+
private handleGatewayReconnect(reason: string, customDelay?: number): void {
|
|
451
|
+
this.cleanup();
|
|
452
|
+
const terminal = this.planReconnect(customDelay);
|
|
453
|
+
this.afterDisconnect(GatewayCloseCode.NORMAL, reason, terminal);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
private handleClose(code: number, reason: string): void {
|
|
338
457
|
const action = this.reconnect.handleClose(code, this.isAborted);
|
|
339
458
|
|
|
340
459
|
if (action.clearSession) {
|
|
341
|
-
this.
|
|
342
|
-
this.lastSeq = null;
|
|
343
|
-
this.opts.session?.clear();
|
|
460
|
+
this.resetSession();
|
|
344
461
|
}
|
|
345
462
|
if (action.refreshToken) {
|
|
346
463
|
this.shouldRefreshToken = true;
|
|
@@ -348,15 +465,29 @@ export class GatewayConnection {
|
|
|
348
465
|
|
|
349
466
|
this.cleanup();
|
|
350
467
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
468
|
+
const terminal = action.shouldReconnect
|
|
469
|
+
? this.planReconnect(action.reconnectDelay, { closeCode: code })
|
|
470
|
+
: new GatewayError(
|
|
471
|
+
`Gateway closed (${code}): ${action.reason}`,
|
|
472
|
+
GatewayErrorCode.FATAL_CLOSE,
|
|
473
|
+
code,
|
|
474
|
+
);
|
|
475
|
+
this.afterDisconnect(code, reason, terminal);
|
|
357
476
|
}
|
|
358
477
|
}
|
|
359
478
|
|
|
479
|
+
function toError(err: unknown): Error {
|
|
480
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
484
|
+
return typeof (value as PromiseLike<unknown> | null)?.then === "function";
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function isRateLimitError(message: string): boolean {
|
|
488
|
+
return message.includes("Too many requests") || message.includes("100001");
|
|
489
|
+
}
|
|
490
|
+
|
|
360
491
|
/**
|
|
361
492
|
* Serialize a gateway event payload for debug logging.
|
|
362
493
|
*
|
|
@@ -21,28 +21,80 @@ export interface CloseAction {
|
|
|
21
21
|
reason: string;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/** Connection-level reconnect budget. */
|
|
25
|
+
export interface ReconnectPolicy {
|
|
26
|
+
/**
|
|
27
|
+
* Consecutive reconnect attempts before giving up. Defaults to `Infinity`
|
|
28
|
+
* ({@link MAX_RECONNECT_ATTEMPTS}): only fatal closes end the loop.
|
|
29
|
+
*/
|
|
30
|
+
maxAttempts: number;
|
|
31
|
+
/** Backoff delays (ms) indexed by attempt; the last entry repeats. Defaults to {@link RECONNECT_DELAYS}. */
|
|
32
|
+
delays: readonly number[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const DEFAULT_RECONNECT_POLICY: ReconnectPolicy = {
|
|
36
|
+
maxAttempts: MAX_RECONNECT_ATTEMPTS,
|
|
37
|
+
delays: RECONNECT_DELAYS,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Merge a partial policy with defaults, rejecting values that would break the retry loop. */
|
|
41
|
+
export function resolveReconnectPolicy(policy?: Partial<ReconnectPolicy>): ReconnectPolicy {
|
|
42
|
+
const maxAttempts = policy?.maxAttempts ?? DEFAULT_RECONNECT_POLICY.maxAttempts;
|
|
43
|
+
const delays = policy?.delays ?? DEFAULT_RECONNECT_POLICY.delays;
|
|
44
|
+
const isUnlimited = maxAttempts === Number.POSITIVE_INFINITY;
|
|
45
|
+
if (!isUnlimited && (!Number.isInteger(maxAttempts) || maxAttempts < 0)) {
|
|
46
|
+
throw new RangeError(
|
|
47
|
+
`reconnect.maxAttempts must be a non-negative integer or Infinity, got ${maxAttempts}`,
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
if (delays.length === 0 || delays.some((d) => !Number.isFinite(d) || d < 0)) {
|
|
51
|
+
throw new RangeError("reconnect.delays must be a non-empty list of non-negative numbers");
|
|
52
|
+
}
|
|
53
|
+
return { maxAttempts, delays: [...delays] };
|
|
54
|
+
}
|
|
55
|
+
|
|
24
56
|
export class ReconnectState {
|
|
25
57
|
private attempts = 0;
|
|
26
58
|
private lastConnectTime = 0;
|
|
27
59
|
private quickDisconnectCount = 0;
|
|
60
|
+
private readonly policy: ReconnectPolicy;
|
|
28
61
|
|
|
29
62
|
constructor(
|
|
30
63
|
private readonly accountId: string,
|
|
31
64
|
private readonly log?: Logger,
|
|
32
|
-
|
|
65
|
+
policy?: Partial<ReconnectPolicy>,
|
|
66
|
+
) {
|
|
67
|
+
this.policy = resolveReconnectPolicy(policy);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Socket opened — starts the quick-disconnect window. Does not reset the budget. */
|
|
71
|
+
onSocketOpen(): void {
|
|
72
|
+
this.lastConnectTime = Date.now();
|
|
73
|
+
}
|
|
33
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Session established (READY / RESUMED) — resets the reconnect budget.
|
|
77
|
+
*
|
|
78
|
+
* Resetting on socket open instead would let "open then immediately kicked"
|
|
79
|
+
* loops (e.g. repeated 4004) retry forever.
|
|
80
|
+
*/
|
|
34
81
|
onConnected(): void {
|
|
35
82
|
this.attempts = 0;
|
|
36
83
|
this.lastConnectTime = Date.now();
|
|
37
84
|
}
|
|
38
85
|
|
|
39
86
|
isExhausted(): boolean {
|
|
40
|
-
return this.attempts >=
|
|
87
|
+
return this.attempts >= this.policy.maxAttempts;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Maximum consecutive attempts allowed by the active policy. */
|
|
91
|
+
get maxAttempts(): number {
|
|
92
|
+
return this.policy.maxAttempts;
|
|
41
93
|
}
|
|
42
94
|
|
|
43
95
|
getNextDelay(customDelay?: number): number {
|
|
44
|
-
const
|
|
45
|
-
|
|
96
|
+
const { delays } = this.policy;
|
|
97
|
+
const delay = customDelay ?? delays[Math.min(this.attempts, delays.length - 1)];
|
|
46
98
|
this.attempts++;
|
|
47
99
|
this.log?.debug?.(`[${this.accountId}] Reconnecting in ${delay}ms (attempt ${this.attempts})`);
|
|
48
100
|
return delay;
|
|
@@ -111,7 +163,7 @@ export class ReconnectState {
|
|
|
111
163
|
if (code >= GatewayCloseCode.SERVER_ERROR_START && code <= GatewayCloseCode.SERVER_ERROR_END) {
|
|
112
164
|
this.log?.info(`[${this.accountId}] Internal error (${code}), will re-identify`);
|
|
113
165
|
return {
|
|
114
|
-
shouldReconnect: !isAborted
|
|
166
|
+
shouldReconnect: !isAborted,
|
|
115
167
|
clearSession: true,
|
|
116
168
|
refreshToken: true,
|
|
117
169
|
fatal: false,
|
|
@@ -132,7 +184,7 @@ export class ReconnectState {
|
|
|
132
184
|
);
|
|
133
185
|
this.quickDisconnectCount = 0;
|
|
134
186
|
return {
|
|
135
|
-
shouldReconnect: !isAborted
|
|
187
|
+
shouldReconnect: !isAborted,
|
|
136
188
|
reconnectDelay: RATE_LIMIT_DELAY,
|
|
137
189
|
clearSession: false,
|
|
138
190
|
refreshToken: false,
|
|
@@ -144,8 +196,10 @@ export class ReconnectState {
|
|
|
144
196
|
this.quickDisconnectCount = 0;
|
|
145
197
|
}
|
|
146
198
|
|
|
199
|
+
// A remote 1000 is a server-side graceful close (deploy / drain), not a
|
|
200
|
+
// client shutdown: local closes retire the socket before its close event.
|
|
147
201
|
return {
|
|
148
|
-
shouldReconnect: !isAborted
|
|
202
|
+
shouldReconnect: !isAborted,
|
|
149
203
|
clearSession: false,
|
|
150
204
|
refreshToken: false,
|
|
151
205
|
fatal: false,
|