-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathadapter.ts
328 lines (278 loc) · 8.13 KB
/
adapter.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { ClusterAdapterWithHeartbeat, MessageType } from "socket.io-adapter";
import type {
ClusterAdapterOptions,
ClusterMessage,
PrivateSessionId,
Session,
ServerId,
ClusterResponse,
} from "socket.io-adapter";
import { decode, encode } from "@msgpack/msgpack";
import debugModule from "debug";
import { hasBinary, GETDEL, SET, XADD, XRANGE, XREAD } from "./util";
const debug = debugModule("socket.io-redis-streams-adapter");
const RESTORE_SESSION_MAX_XRANGE_CALLS = 100;
export interface RedisStreamsAdapterOptions {
/**
* The name of the Redis stream.
* @default "socket.io"
*/
streamName?: string;
/**
* The maximum size of the stream. Almost exact trimming (~) is used.
* @default 10_000
*/
maxLen?: number;
/**
* The number of elements to fetch per XREAD call.
* @default 100
*/
readCount?: number;
/**
* The prefix of the key used to store the Socket.IO session, when the connection state recovery feature is enabled.
* @default "sio:session:"
*/
sessionKeyPrefix?: string;
}
interface RawClusterMessage {
uid: string;
nsp: string;
type: string;
data?: string;
}
/**
* Returns a function that will create a new adapter instance.
*
* @param redisClient - a Redis client that will be used to publish messages
* @param opts - additional options
*/
export function createAdapter(
redisClient: any,
opts?: RedisStreamsAdapterOptions & ClusterAdapterOptions
) {
const namespaceToAdapters = new Map<string, RedisStreamsAdapter>();
const options = Object.assign(
{
streamName: "socket.io",
maxLen: 10_000,
readCount: 100,
sessionKeyPrefix: "sio:session:",
heartbeatInterval: 5_000,
heartbeatTimeout: 10_000,
},
opts
);
let offset = "$";
let polling = false;
let shouldClose = false;
async function poll() {
try {
let response = await XREAD(
redisClient,
options.streamName,
offset,
options.readCount
);
if (response) {
for (const entry of response[0].messages) {
debug("reading entry %s", entry.id);
const message = entry.message;
if (message.nsp) {
namespaceToAdapters
.get(message.nsp)
?.onRawMessage(message, entry.id);
}
offset = entry.id;
}
}
} catch (e) {
debug("something went wrong while consuming the stream: %s", e.message);
}
if (namespaceToAdapters.size > 0 && !shouldClose) {
poll();
} else {
polling = false;
}
}
return function (nsp) {
const adapter = new RedisStreamsAdapter(nsp, redisClient, options);
namespaceToAdapters.set(nsp.name, adapter);
if (!polling) {
polling = true;
shouldClose = false;
poll();
}
const defaultClose = adapter.close;
adapter.close = () => {
namespaceToAdapters.delete(nsp.name);
if (namespaceToAdapters.size === 0) {
shouldClose = true;
}
defaultClose.call(adapter);
};
return adapter;
};
}
class RedisStreamsAdapter extends ClusterAdapterWithHeartbeat {
readonly #redisClient: any;
readonly #opts: Required<RedisStreamsAdapterOptions>;
constructor(
nsp,
redisClient,
opts: Required<RedisStreamsAdapterOptions> & ClusterAdapterOptions
) {
super(nsp, opts);
this.#redisClient = redisClient;
this.#opts = opts;
this.init();
}
override doPublish(message: ClusterMessage) {
debug("publishing %o", message);
return XADD(
this.#redisClient,
this.#opts.streamName,
RedisStreamsAdapter.encode(message),
this.#opts.maxLen
);
}
protected doPublishResponse(
requesterUid: ServerId,
response: ClusterResponse
): Promise<void> {
// @ts-ignore
return this.doPublish(response);
}
static encode(message: ClusterMessage): RawClusterMessage {
const rawMessage: RawClusterMessage = {
uid: message.uid,
nsp: message.nsp,
type: message.type.toString(),
};
// @ts-ignore
if (message.data) {
const mayContainBinary = [
MessageType.BROADCAST,
MessageType.FETCH_SOCKETS_RESPONSE,
MessageType.SERVER_SIDE_EMIT,
MessageType.SERVER_SIDE_EMIT_RESPONSE,
MessageType.BROADCAST_ACK,
].includes(message.type);
// @ts-ignore
if (mayContainBinary && hasBinary(message.data)) {
// @ts-ignore
rawMessage.data = Buffer.from(encode(message.data)).toString("base64");
} else {
// @ts-ignore
rawMessage.data = JSON.stringify(message.data);
}
}
return rawMessage;
}
public onRawMessage(rawMessage: RawClusterMessage, offset: string) {
let message;
try {
message = RedisStreamsAdapter.decode(rawMessage);
} catch (e) {
return debug("invalid format: %s", e.message);
}
this.onMessage(message, offset);
}
static decode(rawMessage: RawClusterMessage): ClusterMessage {
const message: ClusterMessage = {
uid: rawMessage.uid,
nsp: rawMessage.nsp,
type: parseInt(rawMessage.type, 10),
};
if (rawMessage.data) {
if (rawMessage.data.startsWith("{")) {
// @ts-ignore
message.data = JSON.parse(rawMessage.data);
} else {
// @ts-ignore
message.data = decode(Buffer.from(rawMessage.data, "base64")) as Record<
string,
unknown
>;
}
}
return message;
}
override persistSession(session) {
debug("persisting session %o", session);
const sessionKey = this.#opts.sessionKeyPrefix + session.pid;
const encodedSession = Buffer.from(encode(session)).toString("base64");
SET(
this.#redisClient,
sessionKey,
encodedSession,
this.nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration
);
}
override async restoreSession(
pid: PrivateSessionId,
offset: string
): Promise<Session> {
debug("restoring session %s from offset %s", pid, offset);
if (!/^[0-9]+-[0-9]+$/.test(offset)) {
return Promise.reject("invalid offset");
}
const sessionKey = this.#opts.sessionKeyPrefix + pid;
const results = await Promise.all([
GETDEL(this.#redisClient, sessionKey),
XRANGE(this.#redisClient, this.#opts.streamName, offset, offset),
]);
const rawSession = results[0][0];
const offsetExists = results[1][0];
if (!rawSession || !offsetExists) {
return Promise.reject("session or offset not found");
}
const session = decode(Buffer.from(rawSession, "base64")) as Session;
debug("found session %o", session);
session.missedPackets = [];
// FIXME we need to add an arbitrary limit here, because if entries are added faster than what we can consume, then
// we will loop endlessly. But if we stop before reaching the end of the stream, we might lose messages.
for (let i = 0; i < RESTORE_SESSION_MAX_XRANGE_CALLS; i++) {
const entries = await XRANGE(
this.#redisClient,
this.#opts.streamName,
RedisStreamsAdapter.nextOffset(offset),
"+"
);
if (entries.length === 0) {
break;
}
for (const entry of entries) {
if (entry.message.nsp === this.nsp.name && entry.message.type === "3") {
const message = RedisStreamsAdapter.decode(entry.message);
// @ts-ignore
if (shouldIncludePacket(session.rooms, message.data.opts)) {
// @ts-ignore
session.missedPackets.push(message.data.packet.data);
}
}
offset = entry.id;
}
}
return session;
}
/**
* Exclusive ranges were added in Redis 6.2, so this is necessary for previous versions.
*
* @see https://redis.io/commands/xrange/
*
* @param offset
*/
static nextOffset(offset) {
const [timestamp, sequence] = offset.split("-");
return timestamp + "-" + (parseInt(sequence) + 1);
}
}
function shouldIncludePacket(sessionRooms, opts) {
const included =
opts.rooms.length === 0 ||
sessionRooms.some((room) => opts.rooms.indexOf(room) !== -1);
const notExcluded = sessionRooms.every(
(room) => opts.except.indexOf(room) === -1
);
return included && notExcluded;
}