-
Notifications
You must be signed in to change notification settings - Fork 156
/
sock.js
327 lines (281 loc) · 6.88 KB
/
sock.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
/**
* Module dependencies.
*/
var net = require('net')
, Parser = require('../parser')
, Message = require('../message')
, codecs = require('../codecs')
, Emitter = require('events').EventEmitter
, debug = require('debug')('axon:sock')
, Configurable = require('configurable')
, url = require('url');
/**
* Expose `Socket`.
*/
module.exports = Socket;
/**
* Initialize a new `Socket`.
*
* A "Socket" encapsulates the ability of being
* the "client" or the "server" depending on
* whether `connect()` or `bind()` was called.
*
* Upon sending and recieving messages, the correct codec
* set by `format` will be applied. Both sides must elect
* the same codec, or all hell will break loose on the app.
*
* @api private
*/
function Socket() {
var self = this;
this.opts = {};
this.server = null;
this.socks = [];
this.settings = {};
this.format('none');
this.set('identity', String(process.pid));
this.set('retry timeout', 100);
this.set('retry max timeout', 2000);
}
/**
* Inherit from `Emitter.prototype`.
*/
Socket.prototype.__proto__ = Emitter.prototype;
/**
* Make it configurable `.set()` etc.
*/
Configurable(Socket.prototype);
/**
* Use the given `plugin`.
*
* @param {Function} plugin
* @api private
*/
Socket.prototype.use = function(plugin){
plugin(this);
return this;
};
/**
* Set format to `type`.
*
* @param {String} type
* @return {Socket}
* @api public
*/
Socket.prototype.format = function(type){
var codec = codecs.byName(type);
if (!codec) throw new Error('unknown format "' + type + '"');
this.codec = codec;
return this;
};
/**
* Creates a new `Message` and writes `data` using the
* `codec` set already by `format`.
*
* This will only work for single part messages or multi
* part message that all use the same codec. If you need
* otherwise, use the `Message` constructor to craft
* your own message.
*
* @param {Mixed} data
* @return {Buffer}
* @api private
*/
Socket.prototype.pack = function(data){
var msg = new Message
, codec = this.codec;
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
msg.write(codec.encode(data[i]), codec.id);
}
} else {
msg.write(codec.encode(data), codec.id);
}
return msg.toBuffer();
};
/**
* Close the socket.
*
* Delegates to the server or clients
* based on the socket `type`.
*
* @api public
*/
Socket.prototype.close = function(){
debug('close');
this.closing = true;
if ('server' == this.type) {
this.server && this.server.close();
} else {
this.socks.forEach(function(sock){
sock.destroy();
});
}
};
/**
* Return the server address.
*
* @return {Object}
* @api public
*/
Socket.prototype.address = function(){
if (!this.server) return;
var addr = this.server.address();
addr.string = 'tcp://' + addr.address + ':' + addr.port;
return addr;
};
/**
* Remove `sock`.
*
* @param {Socket} sock
* @api private
*/
Socket.prototype.removeSocket = function(sock){
var i = this.socks.indexOf(sock);
this.socks.splice(i, 1);
if (sock._axon_id) delete this.map[sock._axon_id];
};
/**
* Add `sock`.
*
* @param {Socket} sock
* @api private
*/
Socket.prototype.addSocket = function(sock){
var self = this
, pid = String(process.pid)
, parser = new Parser
, n = this.socks.push(sock);
sock.on('data', parser.write.bind(parser));
parser.onmessage = self.onmessage(sock);
};
/**
* Handles framed messages emitted from the parser, by
* default it will go ahead and emit the "message" events on
* the socket. However, if the "higher level" socket needs
* to hook into the messages before they are emitted, it
* should override this method and take care of everything
* it self, including emitted the "message" event.
*
* @param {net.Socket} sock
* @return {Function} closure(msg, mulitpart)
* @api private
*/
Socket.prototype.onmessage = function(sock){
var self = this;
return function(msg, multipart){
if (multipart) {
msg.unshift('message');
self.emit.apply(self, msg);
} else {
self.emit('message', msg);
}
};
};
/**
* Connect to `port` at `host` and invoke `fn()`.
*
* Defaults `host` to localhost.
*
* @param {Number|String} port
* @param {String} host
* @param {Function} fn
* @return {Socket}
* @api public
*/
Socket.prototype.connect = function(port, host, fn){
var self = this;
if ('server' == this.type) throw new Error('cannot connect() after bind()');
if ('function' == typeof host) fn = host, host = undefined;
if ('string' == typeof port) {
port = url.parse(port);
host = port.hostname;
port = parseInt(port.port, 10);
}
var sock = new net.Socket;
sock.setNoDelay();
this.type = 'client';
port = port;
host = host || '127.0.0.1';
sock.on('error', function(err){
if ('ECONNREFUSED' != err.code) {
self.emit('error', err);
}
});
sock.on('close', function(){
self.connected = false;
self.removeSocket(sock);
if (self.closing) return self.emit('close');
var max = self.get('max retry timeout');
var retry = self.retry || self.get('retry timeout');
setTimeout(function(){
debug('attempting reconnect');
self.emit('reconnect attempt');
sock.destroy();
self.connect(port, host);
self.retry = Math.min(max, retry * 1.5);
}, retry);
});
sock.on('connect', function(){
debug('connect');
self.connected = true;
self.addSocket(sock);
self.retry = self.get('retry timeout');
self.emit('connect');
fn && fn();
});
debug('connect attempt %s:%s', host, port);
sock.connect(port, host);
return this;
};
/**
* Handle connection.
*
* @param {Socket} sock
* @api private
*/
Socket.prototype.onconnect = function(sock){
var self = this;
var addr = sock.remoteAddress + ':' + sock.remotePort;
debug('connection %s', addr);
this.addSocket(sock);
this.emit('connect', sock);
sock.on('close', function(){
debug('disconnect %s', addr);
self.emit('disconnect', sock);
self.removeSocket(sock);
});
};
/**
* Bind to `port` at `host` and invoke `fn()`.
*
* Defaults `host` to INADDR_ANY.
*
* Emits:
*
* - `connection` when a client connects
* - `disconnect` when a client disconnects
* - `bind` when bound and listening
*
* @param {Number|String} port
* @param {Function} fn
* @return {Socket}
* @api public
*/
Socket.prototype.bind = function(port, host, fn){
var self = this;
if ('client' == this.type) throw new Error('cannot bind() after connect()');
if ('function' == typeof host) fn = host, host = undefined;
if ('string' == typeof port) {
port = url.parse(port);
host = port.hostname;
port = parseInt(port.port, 10);
}
this.type = 'server';
host = host || '0.0.0.0';
this.server = net.createServer(this.onconnect.bind(this));
debug('bind %s:%s', host, port);
this.server.on('listening', this.emit.bind('bind'));
this.server.listen(port, host, fn);
return this;
};