forked from demchenkoe/node-amqp-rpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
604 lines (473 loc) · 17.1 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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
var amqp = require('amqp');
var uuid = require('node-uuid').v4;
var os = require('os');
var queueNo = 0;
var instanceId = 0;
function rpc(opt) {
this.instanceId = instanceId++;
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 uuid() + ':' + 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;
this.__conn = amqp.createConnection(
options,
this.__impl_options
);
this.__conn.on('error', function (err) {
throw err;
});
this.__conn.on('ready', function () {
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 () {
if (!this.__conn) return;
this.__conn.removeAllListeners('error');
var self = this;
this.__conn.on('error', function () {
console.log('--> error disconnecting amqp-rpc #' + self.instanceId);
});
this.__conn.disconnect();
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) {
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) {
queue.subscribe(function () {
$this.__onResult.apply($this, arguments);
});
queue.bind($this.__exchange, $this.__results_queue_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) {
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];
}
rpc.prototype.setMessageTimeout = function (corr_id, timeout) {
var $this = this;
setTimeout(function () {
//release cb
if ($this.__results_cb[corr_id]) {
delete $this.__results_cb[corr_id];
}
}, timeout);
};
/**
* call a remote command
* @param {string} cmd command name
* @param {Buffer|Object|String}params parameters of command
* @param {object} options advanced options of amqp
* @param {object} context context of callback
* @param {function} cb callback
*
*/
rpc.prototype.rpcCall = function (cmd, params, options, context, cb) {
var $this = this;
if (!options) options = {};
options.expiration = options.expiration || "20000";
options.contentType = 'application/json';
var corr_id = options.correlationId || uuid();
$this.setMessageTimeout(corr_id, options.expiration);
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;
}
rpc.prototype._getCurrentBindings = function (queueName, vhost, cb) {
var myRpc = new rpc({exchange: "rpc_exchange", conn_options: {url: this.opt.conn_options.url}});
var routing = "rabbitmon";
var message = {apiCall: "queues/" + vhost + "/" + queueName + "/bindings"};
myRpc.rpcCall(routing, message, {expiration: "20000"}, null, function (err, res) {
if (err) {
console.error(err);
throw err;
}
myRpc.disconnect();
cb(res);
});
};
rpc.prototype._deleteBindings = function (queue, bindingsToDelete) {
var self = this;
bindingsToDelete.forEach(function (b) {
queue.bind(b.exchange, b.routing, function () {
if (bindingsToDelete.length > 0) {
console.log("======= Amqp monitoring: deleting preexisting bindings =======");
}
bindingsToDelete.forEach(function (b) {
console.log("deleting binding: ", b);
queue.unbind(b.exchange, b.routing);
});
if (bindingsToDelete.length > 0) {
console.log("==============================================================");
}
});
});
};
/**
* 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.subscribeParallel = function (cmd, cb, options, context) {
if (this.__cmds[cmd]) return false;
options || (options = {});
var $this = this;
options.queueName = options.queueName || cmd;
this._connect(function () {
$this.__conn.queue(options.queueName, 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.printChannels(options.queueName);
$this._getCurrentBindings(options.queueName, "%2f", function (bindings) {
var bindingsToDelete = bindings.map(function (b) {
return {exchange: b.source, routing: b.routing_key};
}).filter(function (b) {
return b.exchange && b.exchange !== '';
}).filter(function (b) {
return !(b.exchange === $this.__exchange_name && b.routing === cmd);
});
$this._deleteBindings(queue, bindingsToDelete);
});
$this._makeExchange(function () {
queue.bind($this.__exchange, cmd);
});
});
});
return true;
}
/**
* add new command handler, it handles a message per time, at the end it sends the ack to rabbitMQ
* @param cmd
* @param cb
* @param context
* @param options
* @returns {boolean}
*/
rpc.prototype.subscribe = function (cmd, cb, options, context) {
if (this.__cmds[cmd]) return false;
options || (options = {});
var $this = this;
options.queueName = options.queueName || cmd;
this._connect(function () {
$this.__conn.queue(options.queueName, function (queue) {
$this.__cmds[cmd] = {queue: queue};
queue.subscribe({
ack: true
}, 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) {
queue.shift();
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.printChannels(options.queueName);
$this._getCurrentBindings(options.queueName, "%2f", function (bindings) {
var bindingsToDelete = bindings.map(function (b) {
return {exchange: b.source, routing: b.routing_key};
}).filter(function (b) {
return b.exchange && b.exchange !== '';
}).filter(function (b) {
return !(b.exchange === $this.__exchange_name && b.routing === cmd);
});
$this._deleteBindings(queue, bindingsToDelete);
});
$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) {
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();
}
// other processes could remain bounded to the queue, so we cannot delete it
//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.rpcCall.call(this, cmd, params, options, options.context, options.onResponse);
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);
}
}
rpc.prototype.printChannels = function (queueName) {
var thisRabbit = this;
thisRabbit._getChannels(queueName, function (channels) {
if (channels.length > 0) {
console.log("======= Amqp monitoring report =======");
console.log("Channels in [" + queueName + "] queue: ");
channels.forEach(function (v) {
console.log("\t" + v);
});
console.log("======================================");
}
});
};
rpc.prototype._getChannels = function (queueName, cb) {
var myRpc = new rpc({exchange: "rpc_exchange", conn_options: {url: this.opt.conn_options.url}});
var routing = "rabbitmon";
var message = {apiCall: "queues/" + "%2f" + "/" + queueName};
myRpc.rpcCall(routing, message, {expiration: "20000"}, null, function (err, res) {
if (err) {
console.error(err);
throw err;
}
myRpc.disconnect();
var ipList = res.consumer_details.map(function (consumer) {
return consumer.channel_details.connection_name;
});
cb(ipList);
});
};
module.exports.amqpRPC = rpc;
module.exports.factory = function (opt) {
return new rpc(opt);
}