@tencent-connect/qqbot-nodejs 1.0.4 → 1.0.6
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 +114 -0
- package/LICENSE +21 -0
- package/README.md +181 -86
- package/README.zh-CN.md +293 -0
- package/USAGE.md +80 -27
- package/assets/docs/feedback.jpg +0 -0
- package/assets/docs/qqchannel.jpg +0 -0
- package/dist/QQBot.d.ts +66 -3
- package/dist/QQBot.d.ts.map +1 -1
- package/dist/QQBot.js +144 -33
- package/dist/QQBot.js.map +1 -1
- package/dist/index.d.ts +4 -1
- 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 +6 -2
- 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/event-dispatcher.d.ts +22 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -1
- package/dist/protocol/gateway/event-dispatcher.js +17 -0
- package/dist/protocol/gateway/event-dispatcher.js.map +1 -1
- package/dist/protocol/gateway/gateway-connection.d.ts +69 -4
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
- package/dist/protocol/gateway/gateway-connection.js +349 -146
- 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 +56 -9
- package/dist/protocol/gateway/reconnect.js.map +1 -1
- package/dist/protocol/index.d.ts +5 -4
- 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/types.d.ts +49 -10
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.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 +24 -7
- package/src/QQBot.ts +173 -36
- package/src/index.ts +6 -0
- package/src/protocol/api/token.ts +6 -2
- package/src/protocol/gateway/constants.ts +6 -1
- package/src/protocol/gateway/errors.ts +32 -0
- package/src/protocol/gateway/event-dispatcher.ts +41 -0
- package/src/protocol/gateway/gateway-connection.ts +389 -160
- package/src/protocol/gateway/reconnect.ts +76 -10
- package/src/protocol/index.ts +11 -1
- package/src/protocol/types.ts +46 -10
- 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,20 +74,45 @@ 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
|
+
/** Called when a reconnect sends RESUME (session recovery) before RESUMED/READY arrives. */
|
|
86
|
+
onResuming?: () => void;
|
|
87
|
+
/** Called when a connection sends IDENTIFY (fresh session: first connect, or RESUME was rejected). */
|
|
88
|
+
onIdentifying?: () => void;
|
|
89
|
+
/** Heartbeat ACK latency in milliseconds, measured from heartbeat send to ACK. */
|
|
90
|
+
onHeartbeat?: (latencyMs: number) => void;
|
|
91
|
+
/** Recoverable failures (connect errors, socket errors). Terminal failures reject `start()` instead. */
|
|
57
92
|
onError?: (error: Error) => void;
|
|
93
|
+
onDisconnected?: (event: GatewayDisconnect) => void;
|
|
58
94
|
onMessage: (msg: InboundMessage) => void | Promise<void>;
|
|
59
95
|
onInteraction?: (event: InteractionEvent) => void | Promise<void>;
|
|
60
96
|
onRawEvent?: (type: string, data: unknown) => void | Promise<void>;
|
|
61
97
|
}
|
|
62
98
|
|
|
63
|
-
/** Pure-protocol gateway connection. */
|
|
99
|
+
/** Pure-protocol gateway connection. Single-use: create a new instance to restart. */
|
|
64
100
|
export class GatewayConnection {
|
|
65
101
|
private isAborted = false;
|
|
102
|
+
private run: Promise<void> | null = null;
|
|
103
|
+
private finish: (error?: Error) => void = () => {};
|
|
66
104
|
private currentWs: WebSocket | null = null;
|
|
67
105
|
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
|
106
|
+
/** Server-provided heartbeat interval of the current connection (0 before HELLO). */
|
|
107
|
+
private heartbeatIntervalMs = 0;
|
|
108
|
+
/** Forces terminate() when the zombie-close handshake stalls in a network black hole. */
|
|
109
|
+
private zombieWatchdog: ReturnType<typeof setTimeout> | null = null;
|
|
110
|
+
/** Jittered first heartbeat after HELLO; tracked so cleanup() can release it immediately. */
|
|
111
|
+
private firstBeatTimer: ReturnType<typeof setTimeout> | null = null;
|
|
112
|
+
/** True while a heartbeat is awaiting its ACK; a second beat without ACK means a zombie link. */
|
|
113
|
+
private awaitingHeartbeatAck = false;
|
|
114
|
+
/** Send timestamp of the in-flight heartbeat (0 when none is pending). */
|
|
115
|
+
private lastHeartbeatSentAt = 0;
|
|
68
116
|
private sessionId: string | null = null;
|
|
69
117
|
private lastSeq: number | null = null;
|
|
70
118
|
private isConnecting = false;
|
|
@@ -77,19 +125,48 @@ export class GatewayConnection {
|
|
|
77
125
|
|
|
78
126
|
constructor(opts: GatewayConnectionOptions) {
|
|
79
127
|
this.opts = opts;
|
|
80
|
-
this.reconnect = new ReconnectState(opts.account.accountId, opts.log);
|
|
128
|
+
this.reconnect = new ReconnectState(opts.account.accountId, opts.log, opts.reconnect);
|
|
81
129
|
const ua = opts.userAgent ?? "qqbot-nodejs/unknown";
|
|
82
130
|
this.resolveUserAgent = typeof ua === "function" ? ua : () => ua;
|
|
83
131
|
}
|
|
84
132
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Start the connection loop.
|
|
135
|
+
*
|
|
136
|
+
* Resolves when `abortSignal` fires. Rejects with a {@link GatewayError} when
|
|
137
|
+
* a finite reconnect budget is exhausted (`RETRY_EXHAUSTED`) or the gateway sends
|
|
138
|
+
* a non-retryable close (`FATAL_CLOSE`). Repeated calls return the same promise.
|
|
139
|
+
*/
|
|
140
|
+
start(): Promise<void> {
|
|
141
|
+
this.run ??= new Promise<void>((resolve, reject) => {
|
|
142
|
+
const signal = this.opts.abortSignal;
|
|
143
|
+
const onAbort = () => this.finish();
|
|
144
|
+
this.finish = (error) => {
|
|
145
|
+
if (this.isAborted) return;
|
|
146
|
+
this.isAborted = true;
|
|
147
|
+
signal.removeEventListener("abort", onAbort);
|
|
148
|
+
this.clearReconnectTimer();
|
|
149
|
+
this.cleanup();
|
|
150
|
+
if (error) {
|
|
151
|
+
reject(error);
|
|
152
|
+
} else {
|
|
153
|
+
resolve();
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
if (signal.aborted) {
|
|
157
|
+
this.finish();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
161
|
+
try {
|
|
162
|
+
this.restoreSession();
|
|
163
|
+
} catch (error) {
|
|
164
|
+
this.finish(toError(error));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
void this.connect();
|
|
92
168
|
});
|
|
169
|
+
return this.run;
|
|
93
170
|
}
|
|
94
171
|
|
|
95
172
|
// ============ Session persistence ============
|
|
@@ -106,63 +183,102 @@ export class GatewayConnection {
|
|
|
106
183
|
}
|
|
107
184
|
|
|
108
185
|
private saveCurrentSession(): void {
|
|
109
|
-
|
|
186
|
+
const { session } = this.opts;
|
|
187
|
+
if (!this.sessionId || !session) {
|
|
110
188
|
return;
|
|
111
189
|
}
|
|
112
|
-
this.
|
|
113
|
-
|
|
114
|
-
lastSeq: this.lastSeq,
|
|
115
|
-
});
|
|
190
|
+
const snapshot = { sessionId: this.sessionId, lastSeq: this.lastSeq };
|
|
191
|
+
this.notify("session.save", () => session.save(snapshot));
|
|
116
192
|
}
|
|
117
193
|
|
|
118
|
-
|
|
194
|
+
private resetSession(): void {
|
|
195
|
+
this.sessionId = null;
|
|
196
|
+
this.lastSeq = null;
|
|
197
|
+
const { session } = this.opts;
|
|
198
|
+
if (session) this.notify("session.clear", () => session.clear());
|
|
199
|
+
}
|
|
119
200
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
201
|
+
// ============ Callbacks + cleanup ============
|
|
202
|
+
|
|
203
|
+
/** Invoke a user callback without letting sync throws or async rejections escape. */
|
|
204
|
+
private notify(name: string, invoke: () => unknown): void {
|
|
205
|
+
const report = (err: unknown) => {
|
|
206
|
+
this.opts.log?.error(
|
|
207
|
+
`[${this.opts.account.accountId}] ${name} handler threw: ${toError(err).message}`,
|
|
208
|
+
);
|
|
209
|
+
};
|
|
210
|
+
try {
|
|
211
|
+
const result = invoke();
|
|
212
|
+
if (isPromiseLike(result)) Promise.resolve(result).catch(report);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
report(err);
|
|
215
|
+
}
|
|
129
216
|
}
|
|
130
217
|
|
|
218
|
+
/** Release the socket and heartbeat. Emits nothing. */
|
|
131
219
|
private cleanup(): void {
|
|
132
220
|
if (this.heartbeatInterval) {
|
|
133
221
|
clearInterval(this.heartbeatInterval);
|
|
134
222
|
this.heartbeatInterval = null;
|
|
135
223
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
224
|
+
this.awaitingHeartbeatAck = false;
|
|
225
|
+
this.lastHeartbeatSentAt = 0;
|
|
226
|
+
if (this.zombieWatchdog) {
|
|
227
|
+
clearTimeout(this.zombieWatchdog);
|
|
228
|
+
this.zombieWatchdog = null;
|
|
229
|
+
}
|
|
230
|
+
if (this.firstBeatTimer) {
|
|
231
|
+
clearTimeout(this.firstBeatTimer);
|
|
232
|
+
this.firstBeatTimer = null;
|
|
142
233
|
}
|
|
234
|
+
const ws = this.currentWs;
|
|
235
|
+
// Retire ownership before close: ws can emit error/close after a replacement exists.
|
|
143
236
|
this.currentWs = null;
|
|
237
|
+
this.isConnecting = false;
|
|
238
|
+
if (ws && ws.readyState !== WebSocket.CLOSED) ws.terminate();
|
|
144
239
|
}
|
|
145
240
|
|
|
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
|
-
}
|
|
241
|
+
private clearReconnectTimer(): void {
|
|
155
242
|
if (this.reconnectTimer) {
|
|
156
243
|
clearTimeout(this.reconnectTimer);
|
|
157
244
|
this.reconnectTimer = null;
|
|
158
245
|
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ============ Reconnect ============
|
|
249
|
+
|
|
250
|
+
/** Schedule the next attempt, or return the terminal error when the budget is spent. */
|
|
251
|
+
private planReconnect(
|
|
252
|
+
customDelay?: number,
|
|
253
|
+
failure: { closeCode?: number; cause?: unknown } = {},
|
|
254
|
+
): GatewayError | null {
|
|
255
|
+
if (this.reconnect.isExhausted()) {
|
|
256
|
+
const error = new GatewayError(
|
|
257
|
+
`Max reconnect attempts reached (${this.reconnect.maxAttempts})`,
|
|
258
|
+
GatewayErrorCode.RETRY_EXHAUSTED,
|
|
259
|
+
failure.closeCode,
|
|
260
|
+
{ cause: failure.cause },
|
|
261
|
+
);
|
|
262
|
+
this.opts.log?.error(`[${this.opts.account.accountId}] ${error.message}`);
|
|
263
|
+
return error;
|
|
264
|
+
}
|
|
265
|
+
this.clearReconnectTimer();
|
|
159
266
|
const delay = this.reconnect.getNextDelay(customDelay);
|
|
160
267
|
this.reconnectTimer = setTimeout(() => {
|
|
161
268
|
this.reconnectTimer = null;
|
|
162
|
-
|
|
163
|
-
void this.connect();
|
|
164
|
-
}
|
|
269
|
+
void this.connect();
|
|
165
270
|
}, delay);
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Report a disconnect after the reconnect decision is made, then settle if terminal. */
|
|
275
|
+
private afterDisconnect(code: number, reason: string, terminal: GatewayError | null): void {
|
|
276
|
+
const { onDisconnected } = this.opts;
|
|
277
|
+
if (onDisconnected) {
|
|
278
|
+
const event: GatewayDisconnect = { code, reason, willReconnect: terminal === null };
|
|
279
|
+
this.notify("onDisconnected", () => onDisconnected(event));
|
|
280
|
+
}
|
|
281
|
+
if (terminal) this.finish(terminal);
|
|
166
282
|
}
|
|
167
283
|
|
|
168
284
|
// ============ Connect ============
|
|
@@ -170,14 +286,15 @@ export class GatewayConnection {
|
|
|
170
286
|
private async connect(): Promise<void> {
|
|
171
287
|
const { log, account } = this.opts;
|
|
172
288
|
|
|
289
|
+
if (this.isAborted) return;
|
|
173
290
|
if (this.isConnecting) {
|
|
174
291
|
log?.debug?.(`[${account.accountId}] Already connecting, skip`);
|
|
175
292
|
return;
|
|
176
293
|
}
|
|
294
|
+
this.cleanup();
|
|
177
295
|
this.isConnecting = true;
|
|
178
296
|
|
|
179
297
|
try {
|
|
180
|
-
this.cleanup();
|
|
181
298
|
if (this.shouldRefreshToken) {
|
|
182
299
|
log?.debug?.(`[${account.accountId}] Refreshing token...`);
|
|
183
300
|
this.opts.clearTokenCache?.();
|
|
@@ -185,121 +302,164 @@ export class GatewayConnection {
|
|
|
185
302
|
}
|
|
186
303
|
|
|
187
304
|
const accessToken = await this.opts.getAccessToken();
|
|
305
|
+
if (this.isAborted) return;
|
|
188
306
|
log?.info(`[${account.accountId}] ✅ Access token obtained`);
|
|
189
307
|
const gatewayUrl = await this.opts.getGatewayUrl(accessToken);
|
|
308
|
+
if (this.isAborted) return;
|
|
190
309
|
log?.info(`[${account.accountId}] Connecting to ${gatewayUrl}`);
|
|
191
310
|
|
|
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
|
-
});
|
|
311
|
+
this.openSocket(gatewayUrl, accessToken);
|
|
286
312
|
} catch (err) {
|
|
313
|
+
if (this.isAborted) return;
|
|
287
314
|
this.isConnecting = false;
|
|
288
|
-
const
|
|
289
|
-
log?.error(`[${account.accountId}] Connection failed: ${
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
}
|
|
315
|
+
const error = toError(err);
|
|
316
|
+
log?.error(`[${account.accountId}] Connection failed: ${error.message}`);
|
|
317
|
+
const terminal = this.planReconnect(
|
|
318
|
+
isRateLimitError(error.message) ? RATE_LIMIT_DELAY : undefined,
|
|
319
|
+
{ cause: error },
|
|
320
|
+
);
|
|
321
|
+
const { onError } = this.opts;
|
|
322
|
+
if (onError) this.notify("onError", () => onError(error));
|
|
323
|
+
if (terminal) this.finish(terminal);
|
|
295
324
|
}
|
|
296
325
|
}
|
|
297
326
|
|
|
327
|
+
private openSocket(gatewayUrl: string, accessToken: string): void {
|
|
328
|
+
const { log, account } = this.opts;
|
|
329
|
+
const ws = new WebSocket(gatewayUrl, {
|
|
330
|
+
headers: { "User-Agent": this.resolveUserAgent() },
|
|
331
|
+
handshakeTimeout: this.opts.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS,
|
|
332
|
+
});
|
|
333
|
+
this.currentWs = ws;
|
|
334
|
+
|
|
335
|
+
ws.on("open", () => {
|
|
336
|
+
if (ws !== this.currentWs) return;
|
|
337
|
+
log?.info(`[${account.accountId}] WebSocket connected`);
|
|
338
|
+
this.isConnecting = false;
|
|
339
|
+
this.reconnect.onSocketOpen();
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
ws.on("message", (data) => {
|
|
343
|
+
if (ws !== this.currentWs) return;
|
|
344
|
+
try {
|
|
345
|
+
const payload = JSON.parse(decodeGatewayMessageData(data)) as WSPayload;
|
|
346
|
+
this.handlePayload(ws, payload, accessToken);
|
|
347
|
+
} catch (err) {
|
|
348
|
+
log?.error(`[${account.accountId}] Message parse error: ${toError(err).message}`);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
ws.on("close", (code, reason) => {
|
|
353
|
+
if (ws !== this.currentWs) return;
|
|
354
|
+
const reasonText = reason.toString();
|
|
355
|
+
log?.info(`[${account.accountId}] WebSocket closed: ${code} ${reasonText}`);
|
|
356
|
+
this.isConnecting = false;
|
|
357
|
+
this.handleClose(code, reasonText);
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
ws.on("error", (err) => {
|
|
361
|
+
if (ws !== this.currentWs) return;
|
|
362
|
+
log?.error(`[${account.accountId}] WebSocket error: ${err.message}`);
|
|
363
|
+
const { onError } = this.opts;
|
|
364
|
+
if (onError) this.notify("onError", () => onError(err));
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
298
368
|
// ============ Protocol handlers ============
|
|
299
369
|
|
|
370
|
+
private handlePayload(ws: WebSocket, payload: WSPayload, accessToken: string): void {
|
|
371
|
+
const { op, d, s } = payload;
|
|
372
|
+
|
|
373
|
+
if (s) {
|
|
374
|
+
this.lastSeq = s;
|
|
375
|
+
this.saveCurrentSession();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
switch (op) {
|
|
379
|
+
case GatewayOp.HELLO:
|
|
380
|
+
this.handleHello(ws, d, accessToken);
|
|
381
|
+
break;
|
|
382
|
+
|
|
383
|
+
case GatewayOp.DISPATCH:
|
|
384
|
+
this.handleDispatch(payload);
|
|
385
|
+
break;
|
|
386
|
+
|
|
387
|
+
case GatewayOp.HEARTBEAT_ACK: {
|
|
388
|
+
this.awaitingHeartbeatAck = false;
|
|
389
|
+
if (this.lastHeartbeatSentAt !== 0) {
|
|
390
|
+
const latency = Date.now() - this.lastHeartbeatSentAt;
|
|
391
|
+
this.lastHeartbeatSentAt = 0;
|
|
392
|
+
const { onHeartbeat } = this.opts;
|
|
393
|
+
if (onHeartbeat) this.notify("onHeartbeat", () => onHeartbeat(latency));
|
|
394
|
+
}
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
case GatewayOp.RECONNECT:
|
|
399
|
+
this.handleGatewayReconnect("Gateway requested reconnect");
|
|
400
|
+
break;
|
|
401
|
+
|
|
402
|
+
case GatewayOp.INVALID_SESSION:
|
|
403
|
+
// d = whether the session can be resumed
|
|
404
|
+
if (!d) {
|
|
405
|
+
this.resetSession();
|
|
406
|
+
this.shouldRefreshToken = true;
|
|
407
|
+
}
|
|
408
|
+
this.handleGatewayReconnect("Invalid gateway session", INVALID_SESSION_DELAY);
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private handleDispatch(payload: WSPayload): void {
|
|
414
|
+
const { log, account } = this.opts;
|
|
415
|
+
const { d, t } = payload;
|
|
416
|
+
log?.debug?.(`[${account.accountId}] Dispatch event: t=${t} payload=${previewPayload(d)}`);
|
|
417
|
+
const result = dispatchEvent(t ?? "", d, account.accountId, log);
|
|
418
|
+
|
|
419
|
+
if (result.action === "ready") {
|
|
420
|
+
this.sessionId = result.sessionId;
|
|
421
|
+
this.reconnect.onConnected();
|
|
422
|
+
this.saveCurrentSession();
|
|
423
|
+
const { onReady } = this.opts;
|
|
424
|
+
if (onReady) this.notify("onReady", () => onReady(result.data));
|
|
425
|
+
} else if (result.action === "resumed") {
|
|
426
|
+
this.reconnect.onConnected();
|
|
427
|
+
this.saveCurrentSession();
|
|
428
|
+
const onResumed = this.opts.onResumed ?? this.opts.onReady;
|
|
429
|
+
if (onResumed) this.notify("onResumed", () => onResumed(result.data));
|
|
430
|
+
} else if (result.action === "interaction") {
|
|
431
|
+
// Interaction 有 handler → 调用;否则 fallback 到 rawEvent
|
|
432
|
+
const { onInteraction, onRawEvent } = this.opts;
|
|
433
|
+
if (onInteraction) {
|
|
434
|
+
this.notify("onInteraction", () => onInteraction(result.event));
|
|
435
|
+
} else if (onRawEvent) {
|
|
436
|
+
this.notify("onRawEvent", () => onRawEvent(t ?? "", d));
|
|
437
|
+
}
|
|
438
|
+
} else if (result.action === "message") {
|
|
439
|
+
this.notify("onMessage", () => this.opts.onMessage(result.msg));
|
|
440
|
+
} else if (result.action === "raw") {
|
|
441
|
+
const { onRawEvent } = this.opts;
|
|
442
|
+
if (onRawEvent) this.notify("onRawEvent", () => onRawEvent(result.type, result.data));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
300
446
|
private handleHello(ws: WebSocket, d: unknown, accessToken: string): void {
|
|
447
|
+
// Validate before IDENTIFY/RESUME: a malformed interval would clamp
|
|
448
|
+
// setInterval to 1ms and cause a heartbeat storm.
|
|
449
|
+
const interval = readHeartbeatInterval(d);
|
|
450
|
+
if (interval === null) {
|
|
451
|
+
const { log, account } = this.opts;
|
|
452
|
+
log?.error(
|
|
453
|
+
`[${account.accountId}] Invalid HELLO heartbeat interval: ${previewPayload(d)}`,
|
|
454
|
+
);
|
|
455
|
+
this.handleGatewayReconnect("Invalid HELLO heartbeat interval");
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
|
|
301
459
|
const intents = this.opts.intents ?? FULL_INTENTS;
|
|
302
460
|
if (this.sessionId && this.lastSeq !== null) {
|
|
461
|
+
const { onResuming } = this.opts;
|
|
462
|
+
if (onResuming) this.notify("onResuming", () => onResuming());
|
|
303
463
|
ws.send(
|
|
304
464
|
JSON.stringify({
|
|
305
465
|
op: GatewayOp.RESUME,
|
|
@@ -311,6 +471,8 @@ export class GatewayConnection {
|
|
|
311
471
|
}),
|
|
312
472
|
);
|
|
313
473
|
} else {
|
|
474
|
+
const { onIdentifying } = this.opts;
|
|
475
|
+
if (onIdentifying) this.notify("onIdentifying", () => onIdentifying());
|
|
314
476
|
ws.send(
|
|
315
477
|
JSON.stringify({
|
|
316
478
|
op: GatewayOp.IDENTIFY,
|
|
@@ -323,24 +485,63 @@ export class GatewayConnection {
|
|
|
323
485
|
);
|
|
324
486
|
}
|
|
325
487
|
|
|
326
|
-
const interval = (d as { heartbeat_interval: number }).heartbeat_interval;
|
|
327
488
|
if (this.heartbeatInterval) {
|
|
328
489
|
clearInterval(this.heartbeatInterval);
|
|
329
490
|
}
|
|
491
|
+
this.heartbeatIntervalMs = interval;
|
|
492
|
+
// HELLO 后先以 interval×random 的抖动发首拍(避免大规模部署下
|
|
493
|
+
// 心跳相位与服务器下发时刻对齐),之后按固定间隔
|
|
494
|
+
const jitter = Math.max(1, Math.floor(Math.random() * interval));
|
|
495
|
+
this.firstBeatTimer = setTimeout(() => {
|
|
496
|
+
this.firstBeatTimer = null;
|
|
497
|
+
if (ws === this.currentWs) this.sendHeartbeat(ws);
|
|
498
|
+
}, jitter);
|
|
330
499
|
this.heartbeatInterval = setInterval(() => {
|
|
331
|
-
if (ws
|
|
332
|
-
|
|
333
|
-
|
|
500
|
+
if (ws !== this.currentWs) return;
|
|
501
|
+
if (ws.readyState !== WebSocket.OPEN) return;
|
|
502
|
+
this.sendHeartbeat(ws);
|
|
334
503
|
}, interval);
|
|
335
504
|
}
|
|
336
505
|
|
|
337
|
-
|
|
506
|
+
/**
|
|
507
|
+
* Send one heartbeat. A still-unacknowledged previous beat means the link
|
|
508
|
+
* is dead: close with 4009 — the server-side code for "please reconnect" —
|
|
509
|
+
* so the reconnect path runs. The session is preserved server-side, so the
|
|
510
|
+
* reconnect resumes from the last seq and replays missed events. Leave a
|
|
511
|
+
* watchdog too: in a network black hole even the close handshake stalls.
|
|
512
|
+
*/
|
|
513
|
+
private sendHeartbeat(ws: WebSocket): void {
|
|
514
|
+
const { log, account } = this.opts;
|
|
515
|
+
if (this.awaitingHeartbeatAck) {
|
|
516
|
+
log?.warn?.(`[${account.accountId}] Heartbeat ACK timeout, closing ${GatewayCloseCode.SESSION_TIMEOUT}`);
|
|
517
|
+
ws.close(GatewayCloseCode.SESSION_TIMEOUT, "heartbeat ACK timeout");
|
|
518
|
+
if (this.zombieWatchdog) clearTimeout(this.zombieWatchdog);
|
|
519
|
+
this.zombieWatchdog = setTimeout(() => {
|
|
520
|
+
this.zombieWatchdog = null;
|
|
521
|
+
if (ws.readyState !== WebSocket.CLOSED) {
|
|
522
|
+
log?.warn?.(`[${account.accountId}] Close handshake stalled, terminating`);
|
|
523
|
+
ws.terminate();
|
|
524
|
+
}
|
|
525
|
+
}, Math.max(1_000, Math.min(this.heartbeatIntervalMs, 5_000)));
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
this.awaitingHeartbeatAck = true;
|
|
529
|
+
this.lastHeartbeatSentAt = Date.now();
|
|
530
|
+
ws.send(JSON.stringify({ op: GatewayOp.HEARTBEAT, d: this.lastSeq }));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Opcode 7 / 9: drop the socket locally and reconnect. */
|
|
534
|
+
private handleGatewayReconnect(reason: string, customDelay?: number): void {
|
|
535
|
+
this.cleanup();
|
|
536
|
+
const terminal = this.planReconnect(customDelay);
|
|
537
|
+
this.afterDisconnect(GatewayCloseCode.NORMAL, reason, terminal);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private handleClose(code: number, reason: string): void {
|
|
338
541
|
const action = this.reconnect.handleClose(code, this.isAborted);
|
|
339
542
|
|
|
340
543
|
if (action.clearSession) {
|
|
341
|
-
this.
|
|
342
|
-
this.lastSeq = null;
|
|
343
|
-
this.opts.session?.clear();
|
|
544
|
+
this.resetSession();
|
|
344
545
|
}
|
|
345
546
|
if (action.refreshToken) {
|
|
346
547
|
this.shouldRefreshToken = true;
|
|
@@ -348,13 +549,41 @@ export class GatewayConnection {
|
|
|
348
549
|
|
|
349
550
|
this.cleanup();
|
|
350
551
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
552
|
+
const terminal = action.shouldReconnect
|
|
553
|
+
? this.planReconnect(action.reconnectDelay, { closeCode: code })
|
|
554
|
+
: new GatewayError(
|
|
555
|
+
`Gateway closed (${code}): ${action.reason}`,
|
|
556
|
+
GatewayErrorCode.FATAL_CLOSE,
|
|
557
|
+
code,
|
|
558
|
+
);
|
|
559
|
+
this.afterDisconnect(code, reason, terminal);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function toError(err: unknown): Error {
|
|
564
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Read the HELLO heartbeat interval; numeric strings are coerced so a
|
|
569
|
+
* server-side serialization change stays non-breaking. Returns `null` for
|
|
570
|
+
* any value that cannot schedule a sane heartbeat.
|
|
571
|
+
*/
|
|
572
|
+
function readHeartbeatInterval(d: unknown): number | null {
|
|
573
|
+
const raw = (d as { heartbeat_interval?: unknown }).heartbeat_interval;
|
|
574
|
+
const value = typeof raw === "string" ? Number(raw.trim()) : raw;
|
|
575
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
576
|
+
return null;
|
|
357
577
|
}
|
|
578
|
+
return value;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
582
|
+
return typeof (value as PromiseLike<unknown> | null)?.then === "function";
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function isRateLimitError(message: string): boolean {
|
|
586
|
+
return message.includes("Too many requests") || message.includes("100001");
|
|
358
587
|
}
|
|
359
588
|
|
|
360
589
|
/**
|