-
Notifications
You must be signed in to change notification settings - Fork 11
/
metroplex.js
279 lines (235 loc) · 7.27 KB
/
metroplex.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
'use strict';
var https = require('https')
, fuse = require('fusing')
, path = require('path')
, ip = require('ip')
, fs = require('fs');
/**
* Add defaults to the supplied options. The following options are available:
*
* - redis: The Redis instance we should use to store data
* - namespace: The namespace prefix to prevent collision's.
* - interval: Expire interval to keep the server alive in Redis
* - timeout: Timeout for sparks who are alive.
* - latency: Time it takes for our Redis commands to execute.
*
* @param {Primus} primus The Primus instance that received the plugin.
* @param {Object} options Configuration.
* @returns {Object} Options.
* @api public
*/
function Metroplex(primus, options) {
if (!(this instanceof Metroplex)) return new Metroplex(primus, options);
options = options || {};
primus = primus || {};
var annihilate = fs.readFileSync(
path.join(__dirname, 'redis/annihilate.lua'),
'utf8'
);
var register = fs.readFileSync(
path.join(__dirname, 'redis/register.lua'),
'utf8'
);
var parsed = this.parse(primus.server);
this.fuse();
this.redis = options.redis || new require('ioredis')();
this.namespace = (options.namespace || 'metroplex') +':';
this.interval = options.interval || 5 * 60 * 1000;
this.timeout = options.timeout || 30 * 60;
this.latency = options.latency || 2000;
this.redis.defineCommand('annihilate', {
lua: annihilate.replace('{namespace}', this.namespace),
numberOfKeys: 1
});
this.redis.defineCommand('register', {
lua: register.replace('{namespace}', this.namespace),
numberOfKeys: 1
});
if (parsed || options.address) {
this.register(options.address || parsed);
}
}
fuse(Metroplex, require('eventemitter3'));
/**
* Parse our the connection URL from a given HTTP server instance or string.
*
* @param {Server} server HTTP or HTTPS server instance we should read address from
* @returns {String} The address
* @api public
*/
Metroplex.readable('parse', function parse(server) {
if ('string' === typeof server || !server) return server || '';
var secure = server instanceof https.Server || 'function' === typeof server.addContext
, address = server.address ? server.address() : undefined;
//
// If the HTTP server isn't listening yet to a port number the result of
// .address will be undefined. We can only get the location
//
if (!address) return '';
//
// Seriously, 0.0.0.0 is basically localhost. Get the correct address for it.
//
if (address.address === '0.0.0.0' || address.address === '::') {
address.address = ip.address();
}
return 'http'+ (secure ? 's' : '') +'://'+ address.address +':'+ address.port;
});
/**
* Register a new server/address in the Metroplex registry.
*
* @param {String|Server} address The server to add.
* @param {Function} fn Optional callback.
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('register', function register(address, fn) {
this.address = this.parse(address);
if (!this.address) {
if (fn) fn();
return this;
}
var metroplex = this;
this.redis.register(this.address, this.interval, Date.now(), function record(err) {
if (err) {
if (fn) return fn(err);
return metroplex.emit('error', err);
}
metroplex.emit('register', metroplex.address);
metroplex.setInterval();
if (fn) fn(err, metroplex.address);
});
return this;
});
/**
* Remove a server/address from the Metroplex registry.
*
* @param {String|Server} address The server to remove.
* @param {Function} fn Optional callback.
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('unregister', function unregister(address, fn) {
var metroplex = this;
address = this.parse(address || metroplex.address);
if (!address) {
if (fn) fn();
return this;
}
metroplex.redis.annihilate(address, function annihilate(err) {
if (err) {
if (fn) return fn(err);
return metroplex.emit('error', err);
}
metroplex.emit('unregister', address);
clearInterval(metroplex.timer);
if (fn) fn(err, address);
});
return this;
});
/**
* Add a new connection for our registered address.
*
* @param {Spark} spark The connection/spark from Primus.
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('connect', function connect(spark) {
this.redis.multi()
.hset(this.namespace +'sparks', spark.id, this.address)
.sadd(this.namespace + this.address +':sparks', spark.id)
.exec();
return this;
});
/**
* Remove a connection for our registered address.
*
* @param {Spark} spark The connection/spark from Primus.
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('disconnect', function disconnect(spark) {
this.redis.multi()
.hdel(this.namespace +'sparks', spark.id)
.srem(this.namespace + this.address +':sparks', spark.id)
.exec();
return this;
});
/**
* Get all current registered servers except our selfs.
*
* @param {Function} fn Callback
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('servers', function servers(self, fn) {
var metroplex = this;
if ('boolean' !== typeof self) {
fn = self;
self = 0;
}
metroplex.redis.smembers(this.namespace +'servers', function smembers(err, members) {
if (self) return fn(err, members);
fn(err, (members || []).filter(function filter(address) {
return address !== metroplex.address;
}));
});
return this;
});
/**
* Get the server address for a given spark id.
*
* @param {String} id The spark id who's server address we want to retrieve.
* @param {Function} fn Callback
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('spark', function spark(id, fn) {
this.redis.hget(this.namespace +'sparks', id, fn);
return this;
});
/**
* Get all server addresses for the given spark ids.
*
* @param {Array} ids The spark id's we need to look up
* @param {Function} fn Callback.
* @returns {Metroplex}
* @api public
*/
Metroplex.readable('sparks', function sparks(ids, fn) {
var key = this.namespace +'sparks';
this.redis.hmget.apply(this.redis, [key].concat(ids).concat(fn));
return this;
});
/**
* We need to make sure that this server is alive, the most easy and dirty way
* of doing this is setting an interval which bumps the expire of our
* dedicated server key. If we go off line, the key will expire and we will be
* K.O. The value indicates the last "ping" that we got from the node server
* so you can see when the last update was.
*
* @api private
*/
Metroplex.readable('setInterval', function setIntervals() {
clearInterval(this.timer);
var alive = this.namespace + this.address
, redis = this.redis
, metroplex = this;
this.timer = setInterval(function interval() {
redis.psetex(alive, metroplex.interval, Date.now());
metroplex.servers(function servers(err, list) {
if (err) return metroplex.emit('error', err);
list.forEach(function expired(address) {
redis.get(metroplex.namespace + address, function get(err, stamp) {
if (err || Date.now() - +stamp < metroplex.interval) return;
redis.annihilate(address, function murdered(err) {
if (err) return metroplex.emit('error', err);
});
});
});
});
}, this.interval - this.latency);
});
//
// Expose the Metroplex library/registry/api
//
module.exports = Metroplex;