forked from sebastienhatton/riak-pb
/
connections.js
64 lines (46 loc) · 1.27 KB
/
connections.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
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var extend = require('util')._extend;
var defaultOptions = {
innactivityTimeout: 3000
};
module.exports =
function Pool(options) {
if (! options) options = {};
options = extend({}, options);
if (options.nodes && ! Array.isArray(options.nodes))
options.nodes = [options.nodes];
if (! options.nodes) throw new Error('No options.nodes defined');
var nodes = options.nodes;
var e = new EventEmitter();
/// Connect
e.connect =
function connect() {
var node = randomNode();
var nodeStr = node.host + ':' + node.port;
connection = net.connect(node);
connection.___node__ = node;
connection.setTimeout(options.innactivityTimeout);
connection.once('timeout', onTimeout.bind(connection));
connection.once('error', onError.bind(connection));
connection.once('end', onEnd.bind(connection));
return connection;
};
/// Events
function onError(err) {
e.emit('error', err);
connection.end();
}
function onEnd() {
e.emit('end', this.___node__);
}
function onTimeout() {
connection.end();
}
/// Random node
function randomNode() {
var index = Math.floor(Math.random() * nodes.length);
return nodes[index];
}
return e;
};