-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
handleMessage.ts
156 lines (122 loc) · 5.06 KB
/
handleMessage.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
import { DiscordGatewayPayload, DiscordHello, DiscordReady } from "../../types/discord.ts";
import { GatewayOpcodes } from "../../types/shared.ts";
import { createLeakyBucket } from "../../util/bucket.ts";
import { delay } from "../../util/utils.ts";
import { decompressWith } from "./deps.ts";
import { GATEWAY_RATE_LIMIT_RESET_INTERVAL, Shard, ShardState } from "./types.ts";
const decoder = new TextDecoder();
export async function handleMessage(shard: Shard, message: MessageEvent<any>): Promise<void> {
message = message.data;
// If message compression is enabled,
// Discord might send zlib compressed payloads.
if (shard.gatewayConfig.compress && message instanceof Blob) {
message = decompressWith(
new Uint8Array(await message.arrayBuffer()),
0,
(slice: Uint8Array) => decoder.decode(slice),
);
}
// Safeguard incase decompression failed to make a string.
if (typeof message !== "string") return;
const messageData = JSON.parse(message) as DiscordGatewayPayload;
// Edge case start: https://github.com/discordeno/discordeno/issues/2311
shard.heart.lastAck = Date.now();
// Manually calculating the round trip time for users who need it.
if (shard.heart.lastBeat && !shard.heart.acknowledged) {
shard.heart.rtt = shard.heart.lastAck - shard.heart.lastBeat;
}
shard.heart.acknowledged = true;
// Edge case end!
switch (messageData.op) {
case GatewayOpcodes.Heartbeat: {
// TODO: can this actually happen
if (!shard.isOpen()) return;
shard.heart.lastBeat = Date.now();
// Discord randomly sends this requiring an immediate heartbeat back.
// Using a direct socket.send call here because heartbeat requests are reserved by us.
shard.socket?.send(
JSON.stringify({
op: GatewayOpcodes.Heartbeat,
d: shard.previousSequenceNumber,
}),
);
shard.events.heartbeat?.(shard);
break;
}
case GatewayOpcodes.Hello: {
const interval = (messageData.d as DiscordHello).heartbeat_interval;
shard.startHeartbeating(interval);
if (shard.state !== ShardState.Resuming) {
// HELLO has been send on a non resume action.
// This means that the shard starts a new session,
// therefore the rate limit interval has been reset too.
shard.bucket = createLeakyBucket({
max: shard.calculateSafeRequests(),
refillInterval: GATEWAY_RATE_LIMIT_RESET_INTERVAL,
refillAmount: shard.calculateSafeRequests(),
// Waiting acquires should not be lost on a re-identify.
waiting: shard.bucket.waiting,
});
}
shard.events.hello?.(shard);
break;
}
case GatewayOpcodes.HeartbeatACK: {
shard.events.heartbeatAck?.(shard);
break;
}
case GatewayOpcodes.Reconnect: {
// gateway.debug("GW RECONNECT", { shardId });
shard.events.requestedReconnect?.(shard);
await shard.resume();
break;
}
case GatewayOpcodes.InvalidSession: {
// gateway.debug("GW INVALID_SESSION", { shardId, payload: messageData });
const resumable = messageData.d as boolean;
shard.events.invalidSession?.(shard, resumable);
// We need to wait for a random amount of time between 1 and 5
// Reference: https://discord.com/developers/docs/topics/gateway#resuming
await delay(Math.floor((Math.random() * 4 + 1) * 1000));
shard.resolves.get("INVALID_SESSION")?.(messageData);
shard.resolves.delete("INVALID_SESSION");
// When resumable is false we need to re-identify
if (!resumable) {
await shard.identify();
break;
}
// The session is invalid but apparently it is resumable
await shard.resume();
break;
}
}
if (messageData.t === "RESUMED") {
// gateway.debug("GW RESUMED", { shardId });
shard.state = ShardState.Connected;
shard.events.resumed?.(shard);
// Continue the requests which have been queued since the shard went offline.
shard.offlineSendQueue.map((resolve) => resolve());
shard.resolves.get("RESUMED")?.(messageData);
shard.resolves.delete("RESUMED");
} // Important for future resumes.
else if (messageData.t === "READY") {
const payload = messageData.d as DiscordReady;
shard.resumeGatewayUrl = payload.resume_gateway_url;
shard.sessionId = payload.session_id;
shard.state = ShardState.Connected;
// Continue the requests which have been queued since the shard went offline.
// Important when this is a re-identify
shard.offlineSendQueue.map((resolve) => resolve());
shard.resolves.get("READY")?.(messageData);
shard.resolves.delete("READY");
}
// Update the sequence number if it is present
// `s` can be either `null` or a `number`.
// In order to prevent update misses when `s` is `0` we check against null.
if (messageData.s !== null) {
shard.previousSequenceNumber = messageData.s;
}
// The necessary handling required for the Shards connection has been finished.
// Now the event can be safely forwarded.
shard.events.message?.(shard, messageData);
}