-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathadapter.ts
More file actions
521 lines (456 loc) · 13.3 KB
/
adapter.ts
File metadata and controls
521 lines (456 loc) · 13.3 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import { ClusterAdapter, 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,
SUBSCRIBE,
XADD,
XRANGE,
XREAD,
hashCode,
duplicateClient,
SPUBLISH,
PUBLISH,
PUBSUB,
SSUBSCRIBE,
} 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 (or the prefix used when using multiple streams).
*
* @see streamCount
* @default "socket.io"
*/
streamName?: string;
/**
* The number of streams to use to scale horizontally.
*
* Each namespace is routed to a specific stream to ensure the ordering of messages.
*
* Note: using multiple streams is useless when using a single namespace.
*
* @default 1
*/
streamCount?: number;
/**
* The prefix of the Redis PUB/SUB channels used to communicate between the nodes.
* @default "socket.io"
*/
channelPrefix?: string;
/**
* Whether to use sharded PUB/SUB (added in Redis 7.0) to communicate between the nodes.
* @default false
* @see https://redis.io/docs/latest/develop/pubsub/#sharded-pubsub
*/
useShardedPubSub?: boolean;
/**
* 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 number of ms before the XREAD call times out.
* @default 5_000
* @see https://redis.io/docs/latest/commands/xread/#blocking-for-data
*/
blockTimeInMs?: 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;
/**
* Whether the transmitted data contains only JSON-serializable objects without binary data (Buffer, ArrayBuffer, etc.).
* When enabled, binary data checks are skipped for better performance.
* @default false
*/
onlyPlaintext?: boolean;
}
interface RawClusterMessage {
uid: string;
nsp: string;
type: string;
data?: string;
}
interface ReadOnlyClient {
client: any;
streamName: string;
}
async function createReadOnlyClients(
redisClient: any,
opts: RedisStreamsAdapterOptions
): Promise<ReadOnlyClient[]> {
if (opts.streamCount === 1) {
const newClient = await duplicateClient(redisClient);
return [
{
client: newClient,
streamName: opts.streamName,
},
];
} else {
const streamNames = [];
for (let i = 0; i < opts.streamCount; i++) {
const newClient = await duplicateClient(redisClient);
streamNames.push({
client: newClient,
streamName: opts.streamName + "-" + i,
});
}
return streamNames;
}
}
function startPolling(
redisClient: any,
streamName: string,
options: RedisStreamsAdapterOptions,
onMessage: (message: RawClusterMessage, offset: string) => void,
signal: AbortSignal
) {
let offset = "$";
async function poll() {
try {
let response = await XREAD(
redisClient,
streamName,
offset,
options.readCount,
options.blockTimeInMs
);
if (response) {
for (const entry of response[0].messages) {
debug("reading entry %s", entry.id);
const message = entry.message;
if (message.nsp) {
onMessage(message, entry.id);
}
offset = entry.id;
}
}
} catch (e) {
debug("something went wrong while consuming the stream: %s", e.message);
}
if (signal.aborted) {
redisClient.disconnect();
} else {
poll();
}
}
poll();
}
/**
* 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",
streamCount: 1,
channelPrefix: "socket.io",
useShardedPubSub: false,
maxLen: 10_000,
readCount: 100,
blockTimeInMs: 5_000,
sessionKeyPrefix: "sio:session:",
heartbeatInterval: 5_000,
heartbeatTimeout: 10_000,
onlyPlaintext: false,
},
opts
);
function onMessage(message: RawClusterMessage, offset: string) {
namespaceToAdapters.get(message.nsp)?.onRawMessage(message, offset);
}
let readOnlyClients: ReadOnlyClient[];
const controller = new AbortController();
// note: we create one Redis client per stream so they don't block each other. We could also have used one Redis
// client per master in the cluster (reading from the streams assigned to the given node), but that would have been
// trickier to implement.
createReadOnlyClients(redisClient, options).then((clients) => {
readOnlyClients = clients;
for (const { client, streamName } of readOnlyClients) {
startPolling(client, streamName, options, onMessage, controller.signal);
}
});
const subClientPromise = duplicateClient(redisClient);
controller.signal.addEventListener("abort", () => {
subClientPromise.then((subClient) => subClient.disconnect());
});
return function (nsp) {
const adapter = new RedisStreamsAdapter(
nsp,
redisClient,
subClientPromise,
options
);
namespaceToAdapters.set(nsp.name, adapter);
const defaultClose = adapter.close;
adapter.close = () => {
namespaceToAdapters.delete(nsp.name);
if (namespaceToAdapters.size === 0) {
controller.abort();
}
defaultClose.call(adapter);
};
return adapter;
};
}
function computeStreamName(
namespaceName: string,
opts: RedisStreamsAdapterOptions
) {
if (opts.streamCount === 1) {
return opts.streamName;
} else {
const i = hashCode(namespaceName) % opts.streamCount;
return opts.streamName + "-" + i;
}
}
function isEphemeral(message: ClusterMessage) {
const isBroadcastWithAck =
message.type === MessageType.BROADCAST &&
message.data.requestId !== undefined;
return (
isBroadcastWithAck ||
[MessageType.SERVER_SIDE_EMIT, MessageType.FETCH_SOCKETS].includes(
message.type
)
);
}
class RedisStreamsAdapter extends ClusterAdapter {
readonly #redisClient: any;
readonly #opts: Required<RedisStreamsAdapterOptions>;
readonly #streamName: string;
readonly #publicChannel: string;
constructor(
nsp: any,
redisClient: any,
subClientPromise: Promise<any>,
opts: Required<RedisStreamsAdapterOptions> & ClusterAdapterOptions
) {
super(nsp);
this.#redisClient = redisClient;
this.#opts = opts;
// each namespace is routed to a specific stream to ensure the ordering of messages
this.#streamName = computeStreamName(nsp.name, opts);
this.#publicChannel = `${opts.channelPrefix}#${nsp.name}#`;
const privateChannel = `${opts.channelPrefix}#${nsp.name}#${this.uid}#`;
subClientPromise.then((subClient) => {
(this.#opts.useShardedPubSub ? SSUBSCRIBE : SUBSCRIBE)(
subClient,
[this.#publicChannel, privateChannel],
(payload: Buffer) => {
try {
const message = decode(payload) as ClusterMessage;
this.onMessage(message);
} catch (e) {
return debug("invalid format: %s", e.message);
}
}
);
});
}
override doPublish(message: ClusterMessage) {
debug("publishing %o", message);
if (isEphemeral(message)) {
// ephemeral messages are sent with Redis PUB/SUB
const payload = Buffer.from(encode(message));
(this.#opts.useShardedPubSub ? SPUBLISH : PUBLISH)(
this.#redisClient,
this.#publicChannel,
payload
);
return Promise.resolve("");
}
return XADD(
this.#redisClient,
this.#streamName,
this.encode(message),
this.#opts.maxLen
);
}
protected doPublishResponse(
requesterUid: ServerId,
response: ClusterResponse
): Promise<void> {
const responseChannel = `${this.#opts.channelPrefix}#${
this.nsp.name
}#${requesterUid}#`;
const payload = Buffer.from(encode(response));
return (this.#opts.useShardedPubSub ? SPUBLISH : PUBLISH)(
this.#redisClient,
responseChannel,
payload
).then();
}
private 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);
if (
!this.#opts.onlyPlaintext &&
mayContainBinary &&
// @ts-ignore
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 serverCount(): Promise<number> {
return PUBSUB(
this.#redisClient,
this.#opts.useShardedPubSub ? "SHARDNUMSUB" : "NUMSUB",
this.#publicChannel
);
}
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.#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.#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) as {
data: any;
};
const { packet, opts } = message.data;
if (shouldIncludePacket(session.rooms, opts)) {
packet.data.push(entry.id);
session.missedPackets.push(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;
}