-
Notifications
You must be signed in to change notification settings - Fork 484
/
Copy pathsharded-adapter.ts
191 lines (167 loc) · 5.62 KB
/
sharded-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
import { ClusterAdapter, ClusterMessage, MessageType } from "./cluster-adapter";
import { decode, encode } from "notepack.io";
import { hasBinary, PUBSUB, SPUBLISH, SSUBSCRIBE, SUNSUBSCRIBE } from "./util";
import debugModule from "debug";
const debug = debugModule("socket.io-redis");
export interface ShardedRedisAdapterOptions {
/**
* The prefix for the Redis Pub/Sub channels.
*
* @default "socket.io"
*/
channelPrefix?: string;
/**
* The subscription mode impacts the number of Redis Pub/Sub channels:
*
* - "static": 2 channels per namespace
*
* Useful when used with dynamic namespaces.
*
* - "dynamic": (2 + 1 per public room) channels per namespace
*
* The default value, useful when some rooms have a low number of clients (so only a few Socket.IO servers are notified).
*
* Only public rooms (i.e. not related to a particular Socket ID) are taken in account, because:
*
* - a lot of connected clients would mean a lot of subscription/unsubscription
* - the Socket ID attribute is ephemeral
*
* @default "dynamic"
*/
subscriptionMode?: "static" | "dynamic";
}
/**
* Create a new Adapter based on Redis sharded Pub/Sub introduced in Redis 7.0.
*
* @see https://redis.io/docs/manual/pubsub/#sharded-pubsub
*
* @param pubClient - the Redis client used to publish (from the `redis` package)
* @param subClient - the Redis client used to subscribe (from the `redis` package)
* @param opts - some additional options
*/
export function createShardedAdapter(
pubClient: any,
subClient: any,
opts?: ShardedRedisAdapterOptions
) {
return function (nsp) {
return new ShardedRedisAdapter(nsp, pubClient, subClient, opts);
};
}
class ShardedRedisAdapter extends ClusterAdapter {
private readonly pubClient: any;
private readonly subClient: any;
private readonly opts: Required<ShardedRedisAdapterOptions>;
private readonly channel: string;
private readonly responseChannel: string;
constructor(nsp, pubClient, subClient, opts: ShardedRedisAdapterOptions) {
super(nsp);
this.pubClient = pubClient;
this.subClient = subClient;
this.opts = Object.assign(
{
channelPrefix: "socket.io",
subscriptionMode: "dynamic",
},
opts
);
this.channel = `${this.opts.channelPrefix}#${nsp.name}#`;
this.responseChannel = `${this.opts.channelPrefix}#${nsp.name}#${this.uid}#`;
const handler = (message, channel) => this.onRawMessage(message, channel);
SSUBSCRIBE(this.subClient, this.channel, handler);
SSUBSCRIBE(this.subClient, this.responseChannel, handler);
if (this.opts.subscriptionMode === "dynamic") {
this.on("create-room", (room) => {
const isPublicRoom = !this.sids.has(room);
if (isPublicRoom) {
SSUBSCRIBE(this.subClient, this.dynamicChannel(room), handler);
}
});
this.on("delete-room", (room) => {
const isPublicRoom = !this.sids.has(room);
if (isPublicRoom) {
SUNSUBSCRIBE(this.subClient, this.dynamicChannel(room));
}
});
}
}
override close(): Promise<void> | void {
const channels = [this.channel, this.responseChannel];
if (this.opts.subscriptionMode === "dynamic") {
this.rooms.forEach((_sids, room) => {
const isPublicRoom = !this.sids.has(room);
if (isPublicRoom) {
channels.push(this.dynamicChannel(room));
}
});
}
return Promise.all(
channels.map((channel) => SUNSUBSCRIBE(this.subClient, channel))
).then();
}
override publishMessage(message) {
const channel = this.computeChannel(message);
debug("publishing message of type %s to %s", message.type, channel);
SPUBLISH(this.pubClient, channel, this.encode(message));
return Promise.resolve("");
}
private computeChannel(message) {
// broadcast with ack can not use a dynamic channel, because the serverCount() method return the number of all
// servers, not only the ones where the given room exists
const useDynamicChannel =
this.opts.subscriptionMode === "dynamic" &&
message.type === MessageType.BROADCAST &&
message.data.requestId === undefined &&
message.data.opts.rooms.length === 1;
if (useDynamicChannel) {
return this.dynamicChannel(message.data.opts.rooms[0]);
} else {
return this.channel;
}
}
private dynamicChannel(room) {
return this.channel + room + "#";
}
override publishResponse(requesterUid, response) {
debug("publishing response of type %s to %s", response.type, requesterUid);
SPUBLISH(
this.pubClient,
`${this.channel}${requesterUid}#`,
this.encode(response)
);
}
private encode(message: ClusterMessage) {
const mayContainBinary = [
MessageType.BROADCAST,
MessageType.BROADCAST_ACK,
MessageType.FETCH_SOCKETS_RESPONSE,
MessageType.SERVER_SIDE_EMIT,
MessageType.SERVER_SIDE_EMIT_RESPONSE,
].includes(message.type);
if (mayContainBinary && hasBinary(message.data)) {
return encode(message);
} else {
return JSON.stringify(message);
}
}
private onRawMessage(rawMessage: Buffer, channel: Buffer) {
let message;
try {
if (rawMessage[0] === 0x7b) {
message = JSON.parse(rawMessage.toString());
} else {
message = decode(rawMessage);
}
} catch (e) {
return debug("invalid format: %s", e.message);
}
if (channel.toString() === this.responseChannel) {
this.onResponse(message);
} else {
this.onMessage(message);
}
}
override serverCount(): Promise<number> {
return PUBSUB(this.pubClient, "SHARDNUMSUB", this.channel);
}
}