/
Connection.ts
225 lines (180 loc) · 6.64 KB
/
Connection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import WebSocket from "ws";
import { NodeState } from "./NodeState";
import type * as Lavalink from "@lavaclient/types";
import type { Node } from "./Node";
import type { Dictionary } from "../Utils";
/** @internal */
const _socket = Symbol("Connection#_socket")
export class Connection {
static CLIENT_NAME = "lavaclient";
reconnectTry = 0;
payloadQueue: OutgoingPayload[] = [];
connectedAt?: number;
private [_socket]?: WebSocket;
constructor(readonly node: Node, readonly info: ConnectionInfo) {
}
get active(): boolean {
return !!this[_socket] && this[_socket]!.readyState === WebSocket.OPEN;
}
get canReconnect() {
const maxTries = this.info.reconnect?.tries === -1 ? Infinity : this.info.reconnect?.tries ?? 5;
return !!this.info.reconnect && maxTries <= this.reconnectTry;
}
get uptime() {
if (!this.connectedAt) return -1;
return Date.now() - this.connectedAt;
}
send(important: boolean, data: Lavalink.OutgoingMessage): Promise<void> {
return new Promise((resolve, reject) => {
const payload: OutgoingPayload = { resolve, reject, data }
this.active
? this._send(payload)
: this.payloadQueue[important ? "unshift" : "push"](payload);
});
}
connect(): void {
this.disconnect();
const headers: Dictionary<string> = {
Authorization: this.info.password,
"User-Id": this.node.userId!,
"Client-Name": Connection.CLIENT_NAME,
"Num-Shards": "1"
};
if (this.info.resuming?.key) {
headers["Resume-Key"] = this.info.resuming.key;
}
if (this.node.state !== NodeState.Reconnecting) {
this.node.state = NodeState.Connecting;
this.node.debug("connection", "creating websocket...");
}
this.connectedAt = Date.now();
const socket = this[_socket] = new WebSocket(`ws${this.info.secure ? "s" : ""}://${this.info.host}:${this.info.port}`, { headers });
socket.onopen = this._onopen.bind(this);
socket.onclose = this._onclose.bind(this);
socket.onerror = this._onerror.bind(this);
socket.onmessage = this._onmessage.bind(this);
}
disconnect(code = 1000, reason = "closing"): void {
if (!this.active) {
return;
}
this.node.state = NodeState.Disconnecting;
this.node.debug("connection", `disconnecting... code=${code}, reason=${reason}`);
this[_socket]?.close(code, reason);
}
async configureResuming(): Promise<void> {
if (!this.info.resuming) {
return;
}
await this.send(true, {
op: "configureResuming",
key: this.info.resuming.key,
timeout: this.info.resuming.timeout ?? 60000
});
}
flushQueue() {
if (!this.active) {
return;
}
this.payloadQueue.forEach(this._send.bind(this));
this.payloadQueue = [];
}
reconnect(): boolean {
this.node.state = NodeState.Reconnecting;
try {
this.connect()
} catch (e) {
this.node.emit("error", e);
return false;
}
return true;
}
private async _onopen() {
await this.flushQueue();
await this.configureResuming();
this.node.emit("connect", { took: this.uptime, reconnect: this.node.state === NodeState.Reconnecting });
this.node.debug("connection", `connected in ${this.uptime}ms`);
this.node.state = NodeState.Connected;
}
private async _onclose({ reason, code, wasClean }: WebSocket.CloseEvent) {
if (this.node.state === NodeState.Reconnecting) {
return;
}
const reconnecting = this.canReconnect && this.node.state !== NodeState.Disconnecting;
this.node.emit("disconnect", { code, reason, wasClean, reconnecting });
if (!reconnecting) {
this.node.state = NodeState.Disconnected;
return;
}
while (!this.reconnect()) {
const duration = typeof this.info.reconnect?.delay === "function"
? await this.info.reconnect.delay(this.reconnectTry)
: this.info.reconnect?.delay ?? 10000;
this.reconnectTry++;
this.node.debug("connection", `attempting to reconnect in ${duration}ms, try=${this.reconnectTry}`);
await new Promise(res => setTimeout(res, duration));
}
}
private _onerror(event: WebSocket.ErrorEvent) {
const error = event.error ? event.error : event.message;
this.node.emit("error", new Error(error));
}
private _onmessage({ data }: WebSocket.MessageEvent) {
if (data instanceof ArrayBuffer) {
data = Buffer.from(data);
} else if (Array.isArray(data)) {
data = Buffer.concat(data);
}
let payload: Lavalink.IncomingMessage;
try {
payload = JSON.parse(data.toString());
} catch (e) {
this.node.emit("error", e);
return;
}
switch (payload.op) {
case "stats":
this.node.stats = payload;
break;
default:
const player = this.node.players.get(payload.guildId);
if (player) {
if (payload.op === "playerUpdate") {
player.position = payload.state.position ?? -1;
player.connected = payload.state.connected ?? player.connected;
return;
}
player.handleEvent(payload);
}
}
this.node.debug("connection", `${Connection.CLIENT_NAME} <<< ${payload.op}: ${data}`);
this.node.emit("raw", payload);
}
private _send({ data, reject, resolve }: OutgoingPayload) {
const json = JSON.stringify(data);
this.node.debug("connection", `${Connection.CLIENT_NAME} >>> ${data.op}: ${json}`);
return this[_socket]!.send(json, e => e ? reject(e) : resolve());
}
}
export type ReconnectDelay = (current: number) => number | Promise<number>;
export interface ConnectionInfo {
host: string;
port: number;
password: string;
secure?: boolean;
resuming?: ResumingOptions;
reconnect?: ReconnectOptions;
}
export interface ResumingOptions {
key: string;
timeout?: number;
}
export interface ReconnectOptions {
delay?: number | ReconnectDelay;
tries?: number;
}
export interface OutgoingPayload {
resolve: () => void;
reject: (error: Error) => void;
data: Lavalink.OutgoingMessage;
}