This repository has been archived by the owner on Sep 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
channelService.js
356 lines (319 loc) · 8.16 KB
/
channelService.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
var countDownLatch = require('../../util/countDownLatch');
var utils = require('../../util/utils');
var logger = require('pomelo-logger').getLogger(__filename);
var async = require('async');
/**
* constant
*/
var DEFAULT_GROUP_ID = 'default';
var ST_INITED = 0;
var ST_DESTROYED = 1;
/**
* Create and maintain channels for server local.
*
* ChannelService is created by channel component which is a default loaded
* component of pomelo and channel service would be accessed by `app.get('channelService')`.
*
* @class
* @constructor
*/
var ChannelService = function(app) {
this.app = app;
this.channels = {};
};
module.exports = ChannelService;
/**
* Create channel with name.
*
* @param {String} name channel's name
* @memberOf ChannelService
*/
ChannelService.prototype.createChannel = function(name) {
if(this.channels[name]) {
return this.channels[name];
}
var c = new Channel(name, this);
this.channels[name] = c;
return c;
};
/**
* Get channel by name.
*
* @param {String} name channel's name
* @param {Boolean} create if true, create channel
* @return {Channel}
* @memberOf ChannelService
*/
ChannelService.prototype.getChannel = function(name, create) {
var channel = this.channels[name];
if(!channel && !!create) {
channel = this.channels[name] = new Channel(name, this);
}
return channel;
};
/**
* Destroy channel by name.
*
* @param {String} name channel name
* @memberOf ChannelService
*/
ChannelService.prototype.destroyChannel = function(name) {
delete this.channels[name];
};
/**
* Push message by uids.
* Group the uids by group. ignore any uid if sid not specified.
*
* @param {String} route message route
* @param {Object} msg message that would be sent to client
* @param {Array} uids the receiver info list, [{uid: userId, sid: frontendServerId}]
* @param {Function} cb cb(err)
* @memberOf ChannelService
*/
ChannelService.prototype.pushMessageByUids = function(route, msg, uids, cb) {
if(typeof route !== 'string') {
cb = uids;
uids = msg;
msg = route;
route = msg.route;
}
if(!uids || uids.length === 0) {
utils.invokeCallback(cb, new Error('uids should not be empty'));
return;
}
var groups = {}, record;
for(var i=0, l=uids.length; i<l; i++) {
record = uids[i];
add(record.uid, record.sid, groups);
}
sendMessageByGroup(this, route, msg, groups, cb);
};
/**
* Broadcast message to all the connected clients.
*
* @param {String} stype frontend server type string
* @param {String} route route string
* @param {Object} msg message
* @param {Boolean} opts broadcast options. opts.binded: push to binded sessions or all the sessions
* @param {Function} cb callback
* @memberOf ChannelService
*/
ChannelService.prototype.broadcast = function(stype, route, msg, opts, cb) {
opts = opts || {};
var app = this.app;
var namespace = 'sys';
var service = 'channelRemote';
var method = 'broadcast';
var failIds = [];
var servers = app.getServersByType(stype);
if(!servers || servers.length === 0) {
// server list is empty
cb();
return;
}
var count = servers.length;
var successFlag = false;
var latch = countDownLatch.createCountDownLatch(count, function(){
if(!successFlag) {
utils.invokeCallback(cb, new Error('broadcast fails'));
return;
}
utils.invokeCallback(cb, null, failIds);
});
var rpcCB = function(err, fails) {
if(err) {
logger.error('[pushMessage] fail to dispatch msg, err:' + err.stack);
latch.done();
return;
}
if(fails) {
failIds = failIds.concat(fails);
}
successFlag = true;
latch.done();
};
for(var i=0, l=count; i<l; i++) {
app.rpcInvoke(servers[i].id, {namespace: namespace, service: service,
method: method, args: [route, msg, opts.binded]}, rpcCB);
}
};
/**
* Channel maintains the receiver collection for a subject. You can
* add users into a channel and then broadcast message to them by channel.
*
* @class channel
* @constructor
*/
var Channel = function(name, service) {
this.name = name;
this.groups = {}; // group map for uids. key: sid, value: [uid]
this.records = {}; // member records. key: uid
this.__channelService__ = service;
this.state = ST_INITED;
};
/**
* Add user to channel.
*
* @param {Number} uid user id
* @param {String} sid frontend server id which user has connected to
*/
Channel.prototype.add = function(uid, sid) {
if(this.state > ST_INITED) {
return false;
} else {
var res = add(uid, sid, this.groups);
if(res) {
this.records[uid] = {sid: sid, uid: uid};
}
return res;
}
};
/**
* Remove user from channel.
*
* @param {Number} uid user id
* @param {String} sid frontend server id which user has connected to.
* @return [Boolean] true if success or false if fail
*/
Channel.prototype.leave = function(uid, sid) {
if(!uid || !sid) {
return false;
}
delete this.records[uid];
return deleteFrom(uid, sid, this.groups[sid]);
};
/**
* Get channel members.
*
* <b>Notice:</b> Heavy operation.
*
* @return {Array} channel member uid list
*/
Channel.prototype.getMembers = function() {
var res = [], groups = this.groups;
var group, i, l;
for(var sid in this.groups) {
group = this.groups[sid];
for(i=0, l=group.length; i<l; i++) {
res.push(group[i]);
}
}
return res;
};
/**
* Get Member info.
*
* @param {String} uid user id
* @return {Object} member info
*/
Channel.prototype.getMember = function(uid) {
return this.records[uid];
};
/**
* Destroy channel.
*/
Channel.prototype.destroy = function() {
this.state = ST_DESTROYED;
this.__channelService__.destroyChannel(this.name);
};
/**
* Push message to all the members in the channel
*
* @param {String} route message route
* @param {Object} msg message that would be sent to client
* @param {Functioin} cb callback function
*/
Channel.prototype.pushMessage = function(route, msg, cb) {
if(this.state !== ST_INITED) {
utils.invokeCallback(new Error('channel is not running now'));
return;
}
if(typeof route !== 'string') {
cb = msg;
msg = route;
route = msg.route;
}
sendMessageByGroup(this.__channelService__, route, msg, this.groups, cb);
};
/**
* add uid and sid into group. ignore any uid that uid not specified.
*
* @param uid user id
* @param sid server id
* @param groups {Object} grouped uids, , key: sid, value: [uid]
*/
var add = function(uid, sid, groups) {
if(!sid) {
logger.warn('ignore uid %j for sid not specified.', uid);
return false;
}
var group = groups[sid];
if(!group) {
group = [];
groups[sid] = group;
}
group.push(uid);
return true;
};
/**
* delete element from array
*/
var deleteFrom = function(uid, sid, group) {
if(!group) {
return true;
}
for(var i=0, l=group.length; i<l; i++) {
if(group[i] === uid) {
group.splice(i, 1);
return true;
}
}
return false;
};
/**
* push message by group
*
* @param route {String} route route message
* @param msg {Object} message that would be sent to client
* @param groups {Object} grouped uids, , key: sid, value: [uid]
* @param cb {Function} cb(err)
*
* @api private
*/
var sendMessageByGroup = function(channelService, route, msg, groups, cb) {
var app = channelService.app;
var namespace = 'sys';
var service = 'channelRemote';
var method = 'pushMessage';
var count = utils.size(groups);
var successFlag = false;
var failIds = [];
if(count === 0) {
// group is empty
utils.invokeCallback(cb);
return;
}
var latch = countDownLatch.createCountDownLatch(count, function(){
if(!successFlag) {
utils.invokeCallback(cb, new Error('all uids push message fail'));
return;
}
utils.invokeCallback(cb, null, failIds);
});
var rpcCB = function(err, fails) {
if(err) {
logger.error('[pushMessage] fail to dispatch msg, err:' + err.stack);
latch.done();
return;
}
if(fails) {
failIds = failIds.concat(fails);
}
successFlag = true;
latch.done();
};
for(var sid in groups) {
app.rpcInvoke(sid, {namespace: namespace, service: service,
method: method, args: [route, msg, groups[sid]]}, rpcCB);
}
};