-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathclient.js
More file actions
499 lines (387 loc) · 12.9 KB
/
client.js
File metadata and controls
499 lines (387 loc) · 12.9 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
// Copyright 2013 Mark Cavage. All rights reserved.
var dns = require('dns');
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var util = require('util');
var assert = require('assert-plus');
var backoff = require('backoff');
var once = require('once');
var WError = require('verror').WError;
var protocol = require('./protocol');
///--- Globals
var slice = Function.prototype.call.bind(Array.prototype.slice);
var sprintf = util.format;
/* JSSTYLED */
var IP_RE = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var MAX_MSGID = Math.pow(2, 31) - 1;
var MSGID = 0;
///--- Errors
function ConnectionClosedError(msg) {
WError.call(this, msg || 'the underlying connection has been closed');
}
util.inherits(ConnectionClosedError, WError);
ConnectionClosedError.prototype.name = 'ConnectionClosedError';
function ConnectionTimeoutError(time) {
WError.call(this, 'failed to establish connection after %dms', time);
}
util.inherits(ConnectionTimeoutError, WError);
ConnectionTimeoutError.prototype.name = 'ConnectionTimeoutError';
function DNSError(err, host) {
WError.call(this, err, host + ' could not be found in DNS');
}
util.inherits(DNSError, WError);
DNSError.prototype.name = 'DNSError';
function NoConnectionError() {
WError.call(this, 'no connection');
}
util.inherits(NoConnectionError, WError);
NoConnectionError.prototype.name = 'NoConnectionError';
function UnsolicitedMessageError(message) {
WError.call(this, 'unsolicited message');
this.msg = message;
}
util.inherits(UnsolicitedMessageError, WError);
///--- Helpers
function clone(obj) {
if (!obj) {
return (obj);
}
var copy = {};
Object.keys(obj).forEach(function (k) {
copy[k] = obj[k];
});
return (copy);
}
function cleanupListener(l) {
l.removeAllListeners('close');
l.removeAllListeners('data');
l.removeAllListeners('drain');
l.removeAllListeners('end');
l.removeAllListeners('error');
l.removeAllListeners('timeout');
}
function shuffle(array) {
var current;
var tmp;
var top = array.length;
if (top) {
while (--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
}
return (array);
}
// Blackhole for canceled requests
var blackhole = new EventEmitter();
blackhole.on('error', function () {});
///--- API
function Client(options) {
assert.object(options, 'options');
assert.number(options.connectTimeout, 'options.connectTimeout');
assert.string(options.host, 'options.host');
assert.number(options.port, 'options.port');
assert.object(options.retry, 'options.retry');
EventEmitter.call(this);
var self = this;
this.fast_msgid = 0;
this.fast_conn = null;
this._fast_connect_timeout = null;
this.fast_requests = {};
this._pending_requests = 0;
this._options = options;
this.__defineGetter__('countPending', function () {
return (self._pending_requests);
});
if (options.reconnect) {
var r = options.reconnect;
var num = (typeof (r) === 'number' ? r : 1000);
this.fast_reconnect = function () {
self.fast_timer = setTimeout(function () {
self.connect();
}, num);
};
} else {
this.fast_reconnect = false;
}
this.connect();
}
util.inherits(Client, EventEmitter);
Client.prototype.close = function close() {
this.closed = true;
this.fast_reconnect = false;
if (this._fast_connect_timeout) {
clearTimeout(this._fast_connect_timeout);
this._fast_connect_timeout = null;
}
if (this.fast_conn) {
this.fast_conn.destroy();
} else {
// Un-wire and destroy any pending connection
if (this._fast_pending_conn) {
// Swallow socket events as we assume the user doesn't care about
// state changes after calling close().
this._fast_pending_conn.removeAllListeners();
this._fast_pending_conn.on('error', function () {});
this._fast_pending_conn.destroy();
this._fast_pending_conn = null;
}
// Stop looping for any pending connection attempts
clearTimeout(this.fast_timer);
if (this._fast_retry)
this._fast_retry.abort();
setImmediate(this.emit.bind(this, 'close'));
}
};
Client.prototype.connect = function connect() {
if (this._fast_retry)
throw new Error('already connecting');
var self = this;
this.closed = false;
var max = Infinity;
var opts = this._options;
var retry = backoff.call(this._createSocket.bind(this), {},
function (err, conn) {
// Starting with backoff 2.5.0, the backoff callback is called when the
// backoff instance is aborted. In this case, the _onConnection callback
// should not be called, since its purpose is to handle the result of
// the bind call that is being backed off, not events in the backoff
// process itself.
if (!retry.isAborted()) {
self._onConnection(err, conn);
}
});
retry.on('backoff', this.emit.bind(this, 'connectAttempt'));
retry.setStrategy(new backoff.ExponentialStrategy({
initialDelay: opts.retry.minTimeout || 1000,
maxDelay: opts.retry.maxTimeout || Infinity
}));
if (typeof (opts.retry.retries) === 'number')
max = opts.retry.retries;
retry.failAfter(max);
this._fast_retry = retry;
this._fast_retry.start();
};
Client.prototype._createSocket = function _createSocket(_, cb) {
var self = this;
var options = this._options;
var callback = once(function (err, res) {
if (err && !self.closed) {
self.emit('connectError', err);
}
cb(err, res);
});
function _socket() {
var c = net.connect(options);
var to = options.connectTimeout;
if (options.connectTimeout > 0) {
self._fast_connect_timeout = setTimeout(function () {
c.removeAllListeners('connect');
c.removeAllListeners('error');
c.destroy();
callback(new ConnectionTimeoutError(to));
}, to);
}
function done(err, res) {
if (self._fast_connect_timeout) {
clearTimeout(self._fast_connect_timeout);
self._fast_connect_timeout = null;
}
self._fast_pending_conn = null;
callback(err, res);
}
c.once('connect', function onConnect() {
c.removeAllListeners('error');
done(null, c);
});
c.once('error', function onError(err) {
c.removeAllListeners('connect');
done(err);
});
self._fast_pending_conn = c;
}
if (IP_RE.test(options.host)) {
_socket();
} else if (options.host === 'localhost' || options.host === '::1') {
options.host = '127.0.0.1';
_socket();
} else {
dns.resolve4(options.host, function (err, addrs) {
if (err) {
callback(new DNSError(err, options.host));
return;
} else if (!addrs || addrs.length === 0) {
callback(new DNSError(options.host));
return;
}
options = clone(options);
options.host = shuffle(addrs).pop();
_socket();
});
}
};
Client.prototype.cancelRequests = function cancelRequests(err) {
var self = this;
Object.keys(this.fast_requests).forEach(function (msgid) {
self.cancel(msgid, err);
});
};
Client.prototype.cancel = function cancel(msgid, err) {
var req = this.fast_requests[msgid];
if (!err) {
err = new Error('RPC canceled');
err.name = 'RPCCanceled';
}
if (req && req != blackhole) {
req.emit('error', err);
cleanupListener(req);
if (this.fast_conn && this.fast_conn.writable) {
// notify server of canceled RPC
req._encoder.encode(err);
}
// Further responses for this msgid will be blackholed.
// This block will be cleared once an ERROR or END event is received
// from the server or the TCP connection is severed.
req.removeAllListeners();
this.fast_requests[msgid] = blackhole;
}
};
Client.prototype.rpc = function rpc(method) {
assert.string(method, 'method');
var req = new EventEmitter();
if (!this.fast_conn ||
!this.fast_conn.readable ||
!this.fast_conn.writable) {
setImmediate(req.emit.bind(req, 'error', new NoConnectionError()));
return (req);
}
var msgid = this._nextMessageId();
var self = this;
var encoder = new protocol.RpcEncoder({
connection: self.fast_conn,
encoder: self.messageEncoder,
msgid: msgid,
method: method
});
req._encoder = encoder;
req.cancel = this.cancel.bind(this, msgid);
encoder.encode.apply(encoder, slice(arguments, 1));
this.fast_requests[msgid] = req;
this._pending_requests++;
return (req);
};
Client.prototype.setTimeout = function setTimeout(timeout) {
assert.number(timeout, 'timeout');
if (!this.fast_conn)
throw new NoConnectionError();
this.fast_conn.setTimeout(timeout);
};
Client.prototype.toString = function toString() {
var c = this.fast_conn;
var str = sprintf('[object FastClient<remote=%s:%s>]',
c ? c.remoteAddress : 'no_host',
c ? c.remotePort : 'no_port');
return (str);
};
//-- "private" methods
Client.prototype._handleMessage = function _handleMessage(msg) {
if (!this.fast_conn) {
this.emit('unhandledMessage', msg);
return;
}
if (!msg.data || !msg.data.m || !msg.data.d) {
this.emit('error', new Error('bad message'));
return;
}
var args;
var err;
var req;
if ((req = this.fast_requests[msg.msgid])) {
switch (msg.status) {
case protocol.STATUS.DATA:
args = msg.data.d;
args.unshift('message');
req.emit.apply(req, args);
break;
case protocol.STATUS.END:
if (msg.data.d.length) {
args = msg.data.d;
args.unshift('message');
req.emit.apply(req, args);
}
delete this.fast_requests[msg.msgid];
this._pending_requests--;
req.emit('end');
cleanupListener(req);
break;
default:
err = new Error(msg.data.d.message);
err.name = msg.data.d.name;
err.stack = msg.data.d.stack;
err.context = msg.data.d.context || {};
err.ase_errors = msg.data.d.ase_errors || [];
delete this.fast_requests[msg.msgid];
this._pending_requests--;
req.emit('error', err);
cleanupListener(req);
break;
}
} else {
this.emit('error', new UnsolicitedMessageError(msg));
}
};
Client.prototype._nextMessageId = function _nextMessageId() {
if (++this.fast_msgid >= MAX_MSGID)
this.fast_msgid = 1;
return (this.fast_msgid);
};
Client.prototype._onConnection = function _onConnection(connect_err, conn) {
assert.notEqual(this.closed, true, 'connection state change after close');
if (connect_err) {
this.emit('error', connect_err);
return;
}
var self = this;
conn.on('close', function (had_err) {
cleanupListener(conn);
self.fast_conn = null;
// Clean up any pending requests with an error
self.cancelRequests(new ConnectionClosedError());
// Queue up a reconnection, if requested
if (self.fast_reconnect)
self.fast_reconnect();
self.emit('close', had_err);
});
conn.on('error', function (err) {
conn.end();
if (self.listeners('error').length > 0)
self.emit('error', err);
});
this.fast_conn = conn;
this.fast_conn.setKeepAlive(true, 60000);
this.messageDecoder = new protocol.MessageDecoder();
this.messageEncoder = new protocol.MessageEncoder();
this.fast_conn.pipe(this.messageDecoder);
this.messageEncoder.pipe(this.fast_conn);
this.messageDecoder.on('message', function onMessage(msg) {
self._handleMessage(msg);
});
this._fast_retry = null;
this.emit('connect');
};
///--- Exports
module.exports = {
createClient: function createClient(options) {
var opts = clone(options);
opts.connectTimeout = opts.connectTimeout || 1000;
opts.host = opts.host || '127.0.0.1';
if (opts.reconnect === undefined)
opts.reconnect = 1000;
opts.retry = opts.retry || {
retries: 3
};
return (new Client(opts));
}
};