-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
447 lines (337 loc) · 12 KB
/
index.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
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
var amqp = require('amqp');
var uuid = require('node-uuid').v4;
var os = require('os');
var debug= require('debug')('amqp-rpc');
var queueNo = 0;
function rpc(opt) {
if(!opt) opt = {};
this.opt = opt;
this.__conn = opt.connection ? opt.connection : null;
this.__url = opt.url ? opt.url: 'amqp://guest:guest@localhost:5672';
this.__exchange = opt.exchangeInstance ? opt.exchangeInstance : null;
this.__exchange_name = opt.exchange ? opt.exchange : 'rpc_exchange';
this.__exchange_options = opt.exchange_options ? opt.exchange_options : {exclusive: false, autoDelete: true };
this.__impl_options = opt.ipml_options || {defaultExchangeName: this.__exchange_name};
this.__conn_options = opt.conn_options || {};
this.__results_queue = null;
this.__results_queue_name = null;
this.__results_cb = {};
this.__make_results_cb = [];
this.__cmds = {};
this.__connCbs = [];
this.__exchangeCbs = [];
}
/**
* generate unique name for new queue
* @returns {string}
*/
rpc.prototype.generateQueueName = function(type) {
return /*'njsListener:' +*/ os.hostname() + ':pid' + process.pid + ':' + type;
}
rpc.prototype._connect = function(cb) {
if(!cb) {
cb = function(){};
}
if(this.__conn) {
if(this.__connCbs.length > 0) {
this.__connCbs.push(cb);
return true;
}
return cb(this.__conn);
} else {
this.__conn = this.opt.connection ? this.opt.connection : null;
}
var $this = this;
this.__connCbs.push(cb);
var options = this.__conn_options;
if(!options.url && !options.host) options.url = this.__url;
debug("createConnection options=", options, ', ipml_options=', this.__impl_options || {});
this.__conn = amqp.createConnection(
options,
this.__impl_options
);
this.__conn.on('ready', function() {
debug("connected to " + $this.__conn.serverProperties.product);
var cbs = $this.__connCbs;
$this.__connCbs = [];
for(var i=0; i< cbs.length; i++) {
cbs[i]($this.__conn);
}
});
}
/**
* disconnect from MQ broker
*/
rpc.prototype.disconnect = function() {
debug("disconnect()");
if(!this.__conn) return;
this.__conn.end();
this.__conn = null;
}
rpc.prototype._makeExchange = function(cb) {
if(!cb) {
cb = function(){};
}
if(this.__exchange) {
if(this.__exchangeCbs.length > 0) {
this.__exchangeCbs.push(cb);
return true;
}
return cb(this.__exchange);
}
var $this = this;
this.__exchangeCbs.push(cb);
/*
* Added option autoDelete=false.
* Otherwise we had an error in library node-amqp version > 0.1.7.
* Text of such error: "PRECONDITION_FAILED - cannot redeclare exchange '<exchange name>' in vhost '/' with different type, durable, internal or autodelete value"
*/
this.__exchange = this.__conn.exchange(this.__exchange_name, { autoDelete: false }, function(exchange) {
debug('Exchange ' + exchange.name + ' is open');
var cbs = $this.__exchangeCbs;
$this.__exchangeCbs = [];
for(var i=0; i< cbs.length; i++) {
cbs[i]($this.__exchange);
}
});
}
rpc.prototype._makeResultsQueue = function(cb) {
if(!cb) {
cb = function(){};
}
if(this.__results_queue) {
if(this.__make_results_cb.length > 0) {
this.__make_results_cb.push(cb);
return true;
}
return cb(this.__results_queue);
}
var $this = this;
this.__results_queue_name = this.generateQueueName('callback');
this.__make_results_cb.push(cb);
$this._makeExchange(function() {
$this.__results_queue = $this.__conn.queue(
$this.__results_queue_name,
$this.__exchange_options,
function(queue) {
debug('Callback queue ' + queue.name + ' is open');
queue.subscribe(function() {
$this.__onResult.apply($this, arguments);
});
queue.bind($this.__exchange, $this.__results_queue_name);
debug('Bind queue ' + queue.name + ' to exchange ' + $this.__exchange.name);
var cbs = $this.__make_results_cb;
$this.__make_results_cb = [];
for(var i=0; i<cbs.length; i++){
cbs[i](queue);
}
}
);
});
}
rpc.prototype.__onResult = function(message, headers, deliveryInfo) {
debug("__onResult()");
if(! this.__results_cb[ deliveryInfo.correlationId ]) return;
var cb = this.__results_cb[ deliveryInfo.correlationId ];
var args = [];
if(Array.isArray(message) ) {
for(var i=0; i< message.length; i++) {
args.push(message[i]);
}
}
else args.push(message);
cb.cb.apply(cb.context, args);
if(cb.autoDeleteCallback !== false)
delete this.__results_cb[ deliveryInfo.correlationId ];
}
/**
* call a remote command
* @param {string} cmd command name
* @param {Buffer|Object|String}params parameters of command
* @param {function} cb callback
* @param {object} context context of callback
* @param {object} options advanced options of amqp
*/
rpc.prototype.call = function(cmd, params, cb, context, options) {
debug('call()', cmd);
var $this = this;
if(!options) options = {};
options.contentType = 'application/json';
var corr_id = options.correlationId || uuid();
this._connect(function() {
if(cb) {
$this._makeExchange(function(){
$this._makeResultsQueue(function() {
$this.__results_cb[ corr_id ] = {
cb: cb,
context: context,
autoDeleteCallback: !!options.autoDeleteCallback
};
options.mandatory = true;
options.replyTo = $this.__results_queue_name;
options.correlationId = corr_id;
//options.domain = "localhost";
$this.__exchange.publish(
cmd,
params,
options,
function(err) {
if(err) {
delete $this.__results_cb[ corr_id ];
cb(err);
}
}
);
});
});
}
else {
$this._makeExchange(function(){
$this.__exchange.publish(
cmd,
params,
options
);
});
}
});
return corr_id;
}
/**
* add new command handler
* @param {string} cmd command name or match string
* @param {function} cb handler
* @param {object} context context for handler
* @param {object} options advanced options
* @param {string} options.queueName name of queue. Default equal to "cmd" parameter
* @param {boolean} options.durable If true, the queue will be marked as durable.
* Durable queues remain active when a server restarts.
* Non-durable queues (transient queues) are purged if/when a server restarts.
* Note that durable queues do not necessarily hold persistent messages,
* although it does not make sense to send persistent messages to a transient queue.
* @param {boolean} options.exclusive Exclusive queues may only be accessed by the current connection,
* and are deleted when that connection closes.
* @param {boolean} options.autoDelete If true, the queue is deleted when all consumers have finished using it.
* The last consumer can be cancelled either explicitly or because its channel is closed.
* If there was no consumer ever on the queue, it won't be deleted. Applications
* can explicitly delete auto-delete queues using the Delete method as normal.
* @return {boolean}
*/
rpc.prototype.on = function(cmd, cb, context, options) {
debug('on(), routingKey=%s', cmd);
if(this.__cmds[ cmd ]) return false;
options || (options = {});
var $this = this;
this._connect(function() {
$this.__conn.queue(options.queueName || cmd, function(queue) {
$this.__cmds[ cmd ] = { queue: queue };
queue.subscribe(function(message, d, headers, deliveryInfo) {
var cmdInfo = {
cmd: deliveryInfo.routingKey,
exchange: deliveryInfo.exchange,
contentType: deliveryInfo.contentType,
size: deliveryInfo.size
};
if(deliveryInfo.correlationId && deliveryInfo.replyTo ) {
return cb.call(context, message, function(err, data) {
var options = {
correlationId: deliveryInfo.correlationId
}
$this.__exchange.publish(
deliveryInfo.replyTo,
Array.prototype.slice.call(arguments),
options
);
}, cmdInfo);
}
else
return cb.call(context, message, null, cmdInfo);
});
$this._makeExchange(function(){
queue.bind($this.__exchange, cmd);
});
});
});
return true;
}
/**
* remove command handler added with "on" method
* @param {string} cmd command or match string
* @return {boolean}
*/
rpc.prototype.off = function(cmd) {
debug('off', cmd);
if(!this.__cmds[ cmd ]) return false;
var $this = this;
var c = $this.__cmds[ cmd ];
function unsubscribe(cb) {
if(c.ctag)
c.queue.unsubscribe(c.ctag);
if(cb)
return cb();
}
function unbind(cb) {
if(c.queue) {
unsubscribe(function() {
c.queue.unbind($this.__exchange, cmd);
if(cb)
return cb();
});
}
}
function destroy(cb) {
if(c.queue){
unbind(function(){
c.queue.destroy()
if(cb)
return cb();
});
}
}
destroy(function(){
delete $this.__cmds[ cmd ];
});
return true;
}
/**
* call broadcast
* @param {string} cmd
* @param params
* @param options
*/
rpc.prototype.callBroadcast = function(cmd, params, options) {
var $this = this;
options || (options = {});
options.broadcast = true;
options.autoDeleteCallback = options.ttl ? false : true;
var corr_id = this.call.call(this, cmd, params, options.onResponse, options.context, options);
if(options.ttl) {
setTimeout(function() {
//release cb
if($this.__results_cb[ corr_id ]) {
delete $this.__results_cb[ corr_id ];
}
options.onComplete.call(options.context, cmd, options);
}, options.ttl);
}
}
/**
* subscribe to broadcast commands
* @param {string} cmd
* @param {function} cb
* @param {object} context
*/
rpc.prototype.onBroadcast = function (cmd, cb, context, options) {
options || (options = {});
options.queueName = this.generateQueueName('broadcast:q'+ (queueNo++) );
return this.on.call(this, cmd, cb, context, options);
}
/**
*
* @type {Function}
*/
rpc.prototype.offBroadcast = rpc.prototype.off;
module.exports.amqpRPC = rpc;
module.exports.factory = function(opt) {
return new rpc(opt);
}