/
index.js
488 lines (392 loc) · 11.3 KB
/
index.js
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
/**
* Module dependencies.
*/
var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-lite');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io-redis');
var async = require('async');
/**
* Module exports.
*/
module.exports = adapter;
/**
* Request types, for messages between nodes
*/
var requestTypes = {
clients: 0,
clientRooms: 1,
};
/**
* Returns a redis Adapter class.
*
* @param {String} optional, redis uri
* @return {RedisAdapter} adapter
* @api public
*/
function adapter(uri, opts){
opts = opts || {};
// handle options only
if ('object' == typeof uri) {
opts = uri;
uri = null;
}
// opts
var pub = opts.pubClient;
var sub = opts.subClient;
var prefix = opts.key || 'socket.io';
var subEvent = opts.subEvent || 'messageBuffer';
var requestsTimeout = opts.requestsTimeout || 1000;
var withChannelMultiplexing = false !== opts.withChannelMultiplexing;
// init clients if needed
function createClient() {
if (uri) {
// handle uri string
return redis(uri, opts);
} else {
return redis(opts);
}
}
if (!pub) pub = createClient();
if (!sub) sub = createClient();
// this server's key
var uid = uid2(6);
/**
* Adapter constructor.
*
* @param {String} namespace name
* @api public
*/
function Redis(nsp){
Adapter.call(this, nsp);
this.uid = uid;
this.prefix = prefix;
this.requestsTimeout = requestsTimeout;
this.withChannelMultiplexing = withChannelMultiplexing;
this.channel = prefix + '#' + nsp.name + '#';
this.requestChannel = prefix + '-request#' + this.nsp.name + '#';
this.responseChannel = prefix + '-response#' + this.nsp.name + '#';
this.requests = {};
if (String.prototype.startsWith) {
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.startsWith(subscribedChannel);
}
} else { // Fallback to other impl for older Node.js
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.substr(0, subscribedChannel.length) === subscribedChannel;
}
}
this.pubClient = pub;
this.subClient = sub;
var self = this;
sub.subscribe([this.channel, this.requestChannel, this.responseChannel], function(err){
if (err) self.emit('error', err);
});
sub.on(subEvent, this.onmessage.bind(this));
}
/**
* Inherits from `Adapter`.
*/
Redis.prototype.__proto__ = Adapter.prototype;
/**
* Called with a subscription message
*
* @api private
*/
Redis.prototype.onmessage = function(channel, msg){
channel = channel.toString();
if (this.channelMatches(channel, this.requestChannel)) {
return this.onrequest(channel, msg);
} else if (this.channelMatches(channel, this.responseChannel)) {
return this.onresponse(channel, msg);
} else if (!this.channelMatches(channel, this.channel)) {
return debug('ignore different channel');
}
var args = msgpack.decode(msg);
var packet;
if (uid == args.shift()) return debug('ignore same uid');
packet = args[0];
if (packet && packet.nsp === undefined) {
packet.nsp = '/';
}
if (!packet || packet.nsp != this.nsp.name) {
return debug('ignore different namespace');
}
args.push(true);
this.broadcast.apply(this, args);
};
/**
* Called on request from another node
*
* @api private
*/
Redis.prototype.onrequest = function(channel, msg){
var self = this;
var request;
try {
request = JSON.parse(msg);
} catch(err){
self.emit('error', err);
return;
}
debug('received request %j', request);
switch (request.type) {
case requestTypes.clients:
Adapter.prototype.clients.call(self, request.rooms, function(err, clients){
if(err){
self.emit('error', err);
return;
}
var response = JSON.stringify({
requestid: request.requestid,
clients: clients
});
pub.publish(self.responseChannel, response);
});
break;
case requestTypes.clientRooms:
Adapter.prototype.clientRooms.call(self, request.sid, function(err, rooms){
if(err){
self.emit('error', err);
return;
}
if (!rooms) { return; }
var response = JSON.stringify({
requestid: request.requestid,
rooms: rooms
});
pub.publish(self.responseChannel, response);
});
break;
default:
debug('ignoring unknown request type: %s', request.type);
}
};
/**
* Called on response from another node
*
* @api private
*/
Redis.prototype.onresponse = function(channel, msg){
var self = this;
var response;
try {
response = JSON.parse(msg);
} catch(err){
self.emit('error', err);
return;
}
if (!response.requestid || !self.requests[response.requestid]) {
debug('ignoring unknown request');
return;
}
debug('received response %j', response);
var request = self.requests[response.requestid];
switch (request.type) {
case requestTypes.clients:
request.msgCount++;
// ignore if response does not contain 'clients' key
if(!response.clients || !Array.isArray(response.clients)) return;
for(var i = 0; i < response.clients.length; i++){
request.clients[response.clients[i]] = true;
}
if (request.msgCount === request.numsub) {
clearTimeout(request.timeout);
if (request.callback) process.nextTick(request.callback.bind(null, null, Object.keys(request.clients)));
delete self.requests[request.requestid];
}
break;
case requestTypes.clientRooms:
clearTimeout(request.timeout);
if (request.callback) process.nextTick(request.callback.bind(null, null, response.rooms));
delete self.requests[request.requestid];
break;
default:
debug('ignoring unknown request type: %s', request.type);
}
};
/**
* Broadcasts a packet.
*
* @param {Object} packet to emit
* @param {Object} options
* @param {Boolean} whether the packet came from another node
* @api public
*/
Redis.prototype.broadcast = function(packet, opts, remote){
packet.nsp = this.nsp.name;
if (!(remote || (opts && opts.flags && opts.flags.local))) {
var self = this;
var msg = msgpack.encode([uid, packet, opts]);
if (self.withChannelMultiplexing && opts.rooms && opts.rooms.length === 1) {
pub.publish(self.channel + opts.rooms[0] + '#', msg);
} else {
pub.publish(self.channel, msg);
}
}
Adapter.prototype.broadcast.call(this, packet, opts);
};
/**
* Subscribe client to room messages.
*
* @param {String} client id
* @param {String} room
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.add = function(id, room, fn){
debug('adding %s to %s ', id, room);
var self = this;
Adapter.prototype.add.call(this, id, room);
if (!this.withChannelMultiplexing) {
if (fn) fn(null);
return;
}
var channel = this.channel + room + '#';
sub.subscribe(channel, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
if (fn) fn(null);
});
};
/**
* Unsubscribe client from room messages.
*
* @param {String} session id
* @param {String} room id
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.del = function(id, room, fn){
debug('removing %s from %s', id, room);
var self = this;
var hasRoom = this.rooms.hasOwnProperty(room);
Adapter.prototype.del.call(this, id, room);
if (this.withChannelMultiplexing && hasRoom && !this.rooms[room]) {
var channel = this.channel + room + '#';
sub.unsubscribe(channel, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
if (fn) fn(null);
});
} else {
if (fn) process.nextTick(fn.bind(null, null));
}
};
/**
* Unsubscribe client completely.
*
* @param {String} client id
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.delAll = function(id, fn){
debug('removing %s from all rooms', id);
var self = this;
var rooms = this.sids[id];
if (!rooms) {
if (fn) process.nextTick(fn.bind(null, null));
return;
}
async.each(Object.keys(rooms), function(room, next){
self.del(id, room, next);
}, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
delete self.sids[id];
if (fn) fn(null);
});
};
/**
* Gets a list of clients by sid.
*
* @param {Array} explicit set of rooms to check.
* @param {Function} callback
* @api public
*/
Redis.prototype.clients = function(rooms, fn){
if ('function' == typeof rooms){
fn = rooms;
rooms = null;
}
rooms = rooms || [];
var self = this;
var requestid = uid2(6);
pub.send_command('pubsub', ['numsub', self.requestChannel], function(err, numsub){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
numsub = parseInt(numsub[1], 10);
var request = JSON.stringify({
requestid : requestid,
type: requestTypes.clients,
rooms : rooms
});
// if there is no response for x second, return result
var timeout = setTimeout(function() {
var request = self.requests[requestid];
if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for clients response'), Object.keys(request.clients)));
delete self.requests[requestid];
}, self.requestsTimeout);
self.requests[requestid] = {
type: requestTypes.clients,
numsub: numsub,
msgCount: 0,
clients: {},
callback: fn,
timeout: timeout
};
pub.publish(self.requestChannel, request);
});
};
/**
* Gets the list of rooms a given client has joined.
*
* @param {String} client id
* @param {Function} callback
* @api public
*/
Redis.prototype.clientRooms = function(id, fn){
var self = this;
var requestid = uid2(6);
var rooms = this.sids[id];
if (rooms) {
if (fn) process.nextTick(fn.bind(null, null, Object.keys(rooms)));
return;
}
var request = JSON.stringify({
requestid : requestid,
type: requestTypes.clientRooms,
sid : id
});
// if there is no response for x second, return result
var timeout = setTimeout(function() {
if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for rooms response')));
delete self.requests[requestid];
}, self.requestsTimeout);
self.requests[requestid] = {
type: requestTypes.clientRooms,
callback: fn,
timeout: timeout
};
pub.publish(self.requestChannel, request);
};
Redis.uid = uid;
Redis.pubClient = pub;
Redis.subClient = sub;
Redis.prefix = prefix;
Redis.requestsTimeout = requestsTimeout;
return Redis;
}