amqp-connection-manager 3.2.0 → 3.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -166,7 +166,22 @@ class ChannelWrapper extends _events.EventEmitter {
166
166
 
167
167
  this._messages = []; // Place to store published, but not yet confirmed messages
168
168
 
169
- this._unconfirmedMessages = []; // True if the "worker" is busy sending messages. False if we need to
169
+ this._unconfirmedMessages = []; // Place to store reason code during publish or sendtoqueue messages.
170
+
171
+ this._irrecoverableCode = null; // Irrecoverable error.
172
+
173
+ this._irrecoverableError = [403, // AMQP Access Refused Error.
174
+ 404, // AMQP Not Found Error.
175
+ 406, // AMQP Precondition Failed Error.
176
+ 501, // AMQP Frame Error.
177
+ 502, // AMQP Frame Syntax Error.
178
+ 503, // AMQP Invalid Command Error.
179
+ 504, // AMQP Channel Not Open Error.
180
+ 505, // AMQP Unexpected Frame.
181
+ 530, // AMQP Not Allowed Error.
182
+ 540, // AMQP Not Implemented Error.
183
+ 541 // AMQP Internal Error.
184
+ ]; // True if the "worker" is busy sending messages. False if we need to
170
185
  // start the worker to get stuff done.
171
186
 
172
187
  this._working = false; // If we're in the process of creating a channel, this is a Promise which
@@ -203,6 +218,7 @@ class ChannelWrapper extends _events.EventEmitter {
203
218
  connection
204
219
  }) {
205
220
  this._connection = connection;
221
+ this._irrecoverableCode = null;
206
222
  return connection.createConfirmChannel().then(channel => {
207
223
  this._channel = channel;
208
224
  channel.on('close', () => this._onChannelClose(channel));
@@ -254,7 +270,8 @@ class ChannelWrapper extends _events.EventEmitter {
254
270
  // Called whenever we disconnect from the AMQP server.
255
271
 
256
272
 
257
- _onDisconnect() {
273
+ _onDisconnect(ex) {
274
+ this._irrecoverableCode = (ex.err instanceof Error ? ex.err.code : null) || null;
258
275
  this._channel = null;
259
276
  this._settingUp = null; // Kill off the current worker. We never get any kind of error for messages in flight - see
260
277
  // https://github.com/squaremo/amqp.node/issues/191.
@@ -308,6 +325,11 @@ class ChannelWrapper extends _events.EventEmitter {
308
325
 
309
326
  this._publishQueuedMessages(this._workerNumber);
310
327
  }
328
+ } // Define if a message can cause irrecoverable error
329
+
330
+
331
+ _canWaitReconnection() {
332
+ return !this._irrecoverableError.includes(this._irrecoverableCode);
311
333
  }
312
334
 
313
335
  _publishQueuedMessages(workerNumber) {
@@ -325,12 +347,13 @@ class ChannelWrapper extends _events.EventEmitter {
325
347
 
326
348
  Promise.resolve().then(() => {
327
349
  const encodedMessage = this._json ? new Buffer.from(JSON.stringify(message.content)) : message.content;
350
+ let result = true;
328
351
 
329
352
  const sendPromise = (() => {
330
353
  switch (message.type) {
331
354
  case 'publish':
332
355
  return new Promise(function (resolve, reject) {
333
- const result = channel.publish(message.exchange, message.routingKey, encodedMessage, message.options, err => {
356
+ result = channel.publish(message.exchange, message.routingKey, encodedMessage, message.options, err => {
334
357
  if (err) {
335
358
  reject(err);
336
359
  } else {
@@ -341,7 +364,7 @@ class ChannelWrapper extends _events.EventEmitter {
341
364
 
342
365
  case 'sendToQueue':
343
366
  return new Promise(function (resolve, reject) {
344
- const result = channel.sendToQueue(message.queue, encodedMessage, message.options, err => {
367
+ result = channel.sendToQueue(message.queue, encodedMessage, message.options, err => {
345
368
  if (err) {
346
369
  reject(err);
347
370
  } else {
@@ -355,26 +378,29 @@ class ChannelWrapper extends _events.EventEmitter {
355
378
  default:
356
379
  throw new Error(`Unhandled message type ${message.type}`);
357
380
  }
358
- })(); // Send some more!
359
-
381
+ })();
360
382
 
361
- this._publishQueuedMessages(workerNumber);
383
+ if (result) {
384
+ this._publishQueuedMessages(workerNumber);
385
+ } else {
386
+ this._channel.once('drain', () => this._publishQueuedMessages(workerNumber));
387
+ }
362
388
 
363
389
  return sendPromise;
364
390
  }).then(result => {
365
- this._unconfirmedMessages.shift();
366
-
391
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
367
392
  message.resolve(result);
368
393
  }, err => {
369
- if (!this._channel) {
394
+ if (!this._channel && this._canWaitReconnection()) {
370
395
  // Tried to write to a closed channel. Leave the message in the queue and we'll try again when we
371
396
  // reconnect.
372
- this._messages.unshift(this._unconfirmedMessages.shift());
397
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
398
+
399
+ this._messages.unshift(message);
373
400
  } else {
374
401
  // Something went wrong trying to send this message - could be JSON.stringify failed, could be the
375
402
  // broker rejected the message. Either way, reject it back
376
- this._unconfirmedMessages.shift();
377
-
403
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
378
404
  message.reject(err);
379
405
  }
380
406
  }).catch(
@@ -424,14 +450,35 @@ class ChannelWrapper extends _events.EventEmitter {
424
450
 
425
451
  bindQueue() {
426
452
  return this._channel && this._channel.bindQueue.apply(this._channel, arguments);
453
+ } // Send a `deleteQueue` to the underlying channel.
454
+
455
+
456
+ deleteQueue() {
457
+ return this._channel && this._channel.deleteQueue.apply(this._channel, arguments);
427
458
  } // Send a `assertExchange` to the underlying channel.
428
459
 
429
460
 
430
461
  assertExchange() {
431
462
  return this._channel && this._channel.assertExchange.apply(this._channel, arguments);
463
+ } // Send a `get` to the underlying channel.
464
+
465
+
466
+ get() {
467
+ return this._channel && this._channel.get.apply(this._channel, arguments);
432
468
  }
433
469
 
434
470
  }
435
471
 
436
472
  exports.default = ChannelWrapper;
473
+
474
+ function removeUnconfirmedMessage(arr, message) {
475
+ const toRemove = arr.indexOf(message);
476
+
477
+ if (toRemove === -1) {
478
+ throw new Error(`Message is not in _unconfirmedMessages!`);
479
+ }
480
+
481
+ const removed = arr.splice(toRemove, 1);
482
+ return removed[0];
483
+ }
437
484
  //# sourceMappingURL=ChannelWrapper.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ChannelWrapper.js"],"names":["ChannelWrapper","EventEmitter","addSetup","setup","done","pb","addCallback","_settingUp","Promise","resolve","then","_setups","push","_channel","call","undefined","removeSetup","teardown","filter","s","waitForConnect","once","publish","exchange","routingKey","content","options","reject","_messages","type","_startWorker","sendToQueue","queue","constructor","connectionManager","_onConnect","bind","_onDisconnect","_connectionManager","name","context","_json","json","_unconfirmedMessages","_working","_workerNumber","isConnected","connection","_currentConnection","on","_connection","createConfirmChannel","channel","_onChannelClose","all","map","setupFn","catch","err","emit","length","shift","queueLength","close","forEach","message","Error","removeListener","answer","_shouldPublish","_publishQueuedMessages","workerNumber","encodedMessage","Buffer","from","JSON","stringify","sendPromise","result","setImmediate","unshift","ack","apply","arguments","ackAll","nack","nackAll","purgeQueue","checkQueue","assertQueue","bindQueue","assertExchange"],"mappings":";;;;;;;AAAA;;AACA;;;;AAEA;;;;;;;;;;;;AAYe,MAAMA,cAAN,SAA6BC,oBAA7B,CAA0C;AACrD;;;;;;;;;;;;;;;;;;;;AAoBAC,EAAAA,QAAQ,CAACC,KAAD,EAAQC,IAAI,GAAC,IAAb,EAAmB;AACvB,WAAOC,wBAAGC,WAAH,CAAeF,IAAf,EACH,CAAC,KAAKG,UAAL,IAAmBC,OAAO,CAACC,OAAR,EAApB,EACCC,IADD,CACM,MAAM;AACR,WAAKC,OAAL,CAAaC,IAAb,CAAkBT,KAAlB;;AACA,UAAG,KAAKU,QAAR,EAAkB;AACd,eAAOR,wBAAGS,IAAH,CAAQX,KAAR,EAAe,IAAf,EAAqB,KAAKU,QAA1B,CAAP;AACH,OAFD,MAEO;AACH,eAAOE,SAAP;AACH;AACJ,KARD,CADG,CAAP;AAWH;AAED;;;;;;;;;;;;;AAWAC,EAAAA,WAAW,CAACb,KAAD,EAAQc,QAAQ,GAAC,IAAjB,EAAuBb,IAAI,GAAC,IAA5B,EAAkC;AACzC,WAAOC,wBAAGC,WAAH,CAAeF,IAAf,EAAqB,MAAM;AAC9B,WAAKO,OAAL,GAAe,KAAKA,OAAL,CAAaO,MAAb,CAAoBC,CAAC,IAAIA,CAAC,KAAKhB,KAA/B,CAAf;AAEA,aAAO,CAAC,KAAKI,UAAL,IAAmBC,OAAO,CAACC,OAAR,EAApB,EACNC,IADM,CACD,MAAM,KAAKG,QAAL,GACNR,wBAAGS,IAAH,CAA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,IAAiB,KAAKA,QAAL,CAAcyE,OAAd,CAAsBJ,KAAtB,CAA4B,KAAKrE,QAAjC,EAA2CsE,SAA3C,CAAxB;AACH,GA/YoD,CAiZrD;;;AACAI,EAAAA,UAAU,GAAG;AACT,WAAO,KAAK1E,QAAL,IAAiB,KAAKA,QAAL,CAAc0E,UAAd,CAAyBL,KAAzB,CAA+B,KAAKrE,QAApC,EAA8CsE,SAA9C,CAAxB;AACH,GApZoD,CAsZrD;;;AACAK,EAAAA,UAAU,GAAG;AACT,WAAO,KAAK3E,QAAL,IAAiB,KAAKA,QAAL,CAAc2E,UAAd,CAAyBN,KAAzB,CAA+B,KAAKrE,QAApC,EAA8CsE,SAA9C,CAAxB;AACH,GAzZoD,CA2ZrD;;;AACAM,EAAAA,WAAW,GAAG;AACV,WAAO,KAAK5E,QAAL,IAAiB,KAAKA,QAAL,CAAc4E,WAAd,CAA0BP,KAA1B,CAAgC,KAAKrE,QAArC,EAA+CsE,SAA/C,CAAxB;AACH,GA9ZoD,CAgarD;;;AACAO,EAAAA,SAAS,GAAG;AACR,WAAO,KAAK7E,QAAL,IAAiB,KAAKA,QAAL,CAAc6E,SAAd,CAAwBR,KAAxB,CAA8B,KAAKrE,QAAnC,EAA6CsE,SAA7C,CAAxB;AACH,GAnaoD,CAqarD;;;AACAQ,EAAAA,cAAc,GAAG;AACb,WAAO,KAAK9E,QAAL,IAAiB,KAAKA,QAAL,CAAc8E,cAAd,CAA6BT,KAA7B,CAAmC,KAAKrE,QAAxC,EAAkDsE,SAAlD,CAAxB;AACH;;AAxaoD","sourcesContent":["import { EventEmitter } from 'events';\nimport pb from 'promise-breaker';\n\n/**\n * Calls to `publish()` or `sendToQueue()` work just like in amqplib, but messages are queued internally and\n * are guaranteed to be delivered. If the underlying connection drops, ChannelWrapper will wait for a new\n * connection and continue.\n *\n * Events:\n * * `connect` - emitted every time this channel connects or reconnects.\n * * `error(err, {name})` - emitted if an error occurs setting up the channel.\n * * `drop({message, err})` - called when a JSON message was dropped because it could not be encoded.\n * * `close` - emitted when this channel closes via a call to `close()`\n *\n */\nexport default class ChannelWrapper extends EventEmitter {\n /**\n * Adds a new 'setup handler'.\n *\n * `setup(channel, [cb])` is a function to call when a new underlying channel is created - handy for asserting\n * exchanges and queues exists, and whatnot. The `channel` object here is a ConfigChannel from amqplib.\n * The `setup` function should return a Promise (or optionally take a callback) - no messages will be sent until\n * this Promise resolves.\n *\n * If there is a connection, `setup()` will be run immediately, and the addSetup Promise/callback won't resolve\n * until `setup` is complete. Note that in this case, if the setup throws an error, no 'error' event will\n * be emitted, since you can just handle the error here (although the `setup` will still be added for future\n * reconnects, even if it throws an error.)\n *\n * Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error'\n * event.\n *\n * @param {function} setup - setup function.\n * @param {function} [done] - callback.\n * @returns {void | Promise} - Resolves when complete.\n */\n addSetup(setup, done=null) {\n return pb.addCallback(done,\n (this._settingUp || Promise.resolve())\n .then(() => {\n this._setups.push(setup);\n if(this._channel) {\n return pb.call(setup, this, this._channel);\n } else {\n return undefined;\n }\n })\n );\n }\n\n /**\n * Remove a setup function added with `addSetup`. If there is currently a\n * connection, `teardown(channel, [cb])` will be run immediately, and the\n * returned Promise will not resolve until it completes.\n *\n * @param {function} setup - the setup function to remove.\n * @param {function} [teardown] - `function(channel, [cb])` to run to tear\n * down the channel.\n * @param {function} [done] - Optional callback.\n * @returns {void | Promise} - Resolves when complete.\n */\n removeSetup(setup, teardown=null, done=null) {\n return pb.addCallback(done, () => {\n this._setups = this._setups.filter(s => s !== setup);\n\n return (this._settingUp || Promise.resolve())\n .then(() => this._channel\n ? pb.call(teardown, this, this._channel)\n : undefined\n );\n });\n }\n\n /**\n * Returns a Promise which resolves when this channel next connects.\n * (Mainly here for unit testing...)\n *\n * @param {function} [done] - Optional callback.\n * @returns {void | Promise} - Resolves when connected.\n */\n waitForConnect(done=null) {\n return pb.addCallback(done,\n (this._channel && !this._settingUp)\n ? Promise.resolve()\n : new Promise(resolve => this.once('connect', resolve))\n );\n }\n\n /*\n * Publish a message to the channel.\n *\n * This works just like amqplib's `publish()`, except if the channel is not\n * connected, this will wait until the channel is connected. Returns a\n * Promise which will only resolve when the message has been succesfully sent.\n * The returned promise will be rejected if `close()` is called on this\n * channel before it can be sent, if `options.json` is set and the message\n * can't be encoded, or if the broker rejects the message for some reason.\n *\n */\n publish(exchange, routingKey, content, options, done=null) {\n return pb.addCallback(done, new Promise((resolve, reject) => {\n this._messages.push({\n type: 'publish',\n exchange,\n routingKey,\n content,\n options,\n resolve,\n reject\n });\n this._startWorker();\n }));\n }\n\n /*\n * Send a message to a queue.\n *\n * This works just like amqplib's `sendToQueue`, except if the channel is not connected, this will wait until the\n * channel is connected. Returns a Promise which will only resolve when the message has been succesfully sent.\n * The returned promise will be rejected only if `close()` is called on this channel before it can be sent.\n *\n * `message` here should be a JSON-able object.\n */\n sendToQueue(queue, content, options, done=null) {\n return pb.addCallback(done, new Promise((resolve, reject) => {\n this._messages.push({\n type: 'sendToQueue',\n queue,\n content,\n options,\n resolve,\n reject\n });\n return this._startWorker();\n }));\n }\n\n /**\n * Create a new ChannelWrapper.\n *\n * @param {AmqpConnectionManager} connectionManager - connection manager which\n * created this channel.\n * @param {Object} [options] -\n * @param {string} [options.name] - A name for this channel. Handy for debugging.\n * @param {function} [options.setup] - A default setup function to call. See\n * `addSetup` for details.\n * @param {boolean} [options.json] - if true, then ChannelWrapper assumes all\n * messages passed to `publish()` and `sendToQueue()` are plain JSON objects.\n * These will be encoded automatically before being sent.\n *\n */\n constructor(connectionManager, options = {}) {\n super();\n this._onConnect = this._onConnect.bind(this);\n this._onDisconnect = this._onDisconnect.bind(this);\n this._connectionManager = connectionManager;\n this.name = options.name;\n\n this.context = {};\n\n this._json = ('json' in options) ? options.json : false;\n\n // Place to store queued messages.\n this._messages = [];\n\n // Place to store published, but not yet confirmed messages\n this._unconfirmedMessages = [];\n\n // True if the \"worker\" is busy sending messages. False if we need to\n // start the worker to get stuff done.\n this._working = false;\n\n // If we're in the process of creating a channel, this is a Promise which\n // will resolve when the channel is set up. Otherwise, this is `null`.\n this._settingUp = null;\n\n // The currently connected channel. Note that not all setup functions\n // have been run on this channel until `@_settingUp` is either null or\n // resolved.\n this._channel = null;\n\n // We kill off workers when we disconnect. Whenever we start a new\n // worker, we bump up the `_workerNumber` - this makes it so if stale\n // workers ever do wake up, they'll know to stop working.\n this._workerNumber = 0;\n\n // Array of setup functions to call.\n this._setups = [];\n if(options.setup) {\n this._setups.push(options.setup);\n }\n\n if(connectionManager.isConnected()) {\n this._onConnect({\n connection: this._connectionManager._currentConnection\n });\n }\n connectionManager.on('connect', this._onConnect);\n connectionManager.on('disconnect', this._onDisconnect);\n }\n\n // Called whenever we connect to the broker.\n _onConnect({ connection }) {\n this._connection = connection;\n\n return connection.createConfirmChannel()\n .then(channel => {\n this._channel = channel;\n channel.on('close', () => this._onChannelClose(channel));\n\n this._settingUp = Promise.all(\n this._setups.map(setupFn =>\n // TODO: Use a timeout here to guard against setupFns that never resolve?\n pb.call(setupFn, this, channel)\n .catch(err => {\n if(this._channel) {\n this.emit('error', err, { name: this.name });\n } else {\n // Don't emit an error if setups failed because the channel was closing.\n }\n })\n )\n\n )\n .then(() => {\n this._settingUp = null;\n return this._channel;\n });\n\n return this._settingUp;\n })\n .then(() => {\n if(!this._channel) {\n // Can happen if channel closes while we're setting up.\n return;\n }\n if (this._unconfirmedMessages.length > 0) {\n // requeu any messages that were left unconfirmed when connection was lost\n while (this._unconfirmedMessages.length) {\n this._messages.push(this._unconfirmedMessages.shift());\n }\n }\n\n // Since we just connected, publish any queued messages\n this._startWorker();\n this.emit('connect');\n })\n .catch(err => {\n this.emit('error', err, { name: this.name });\n this._settingUp = null;\n this._channel = null;\n });\n }\n\n // Called whenever the channel closes.\n _onChannelClose(channel) {\n if(this._channel === channel) {\n this._channel = null;\n }\n }\n // Wait for another reconnect to create a new channel.\n\n // Called whenever we disconnect from the AMQP server.\n _onDisconnect() {\n this._channel = null;\n this._settingUp = null;\n\n // Kill off the current worker. We never get any kind of error for messages in flight - see\n // https://github.com/squaremo/amqp.node/issues/191.\n this._working = false;\n }\n\n // Returns the number of unsent messages queued on this channel.\n queueLength() {\n return this._messages.length;\n }\n\n // Destroy this channel.\n //\n // Any unsent messages will have their associated Promises rejected.\n //\n close() {\n return Promise.resolve()\n .then(() => {\n this._working = false;\n if(this._messages.length !== 0) {\n // Reject any unsent messages.\n this._messages.forEach(message => message.reject(new Error('Channel closed')));\n }\n if(this._unconfirmedMessages.length !== 0) {\n // Reject any unconfirmed messages.\n this._unconfirmedMessages.forEach(message => message.reject(new Error('Channel closed')));\n }\n\n this._connectionManager.removeListener('connect', this._onConnect);\n this._connectionManager.removeListener('disconnect', this._onDisconnect);\n const answer = (this._channel && this._channel.close()) || undefined;\n this._channel = null;\n\n this.emit('close');\n\n return answer;\n });\n }\n\n _shouldPublish() {\n return (this._messages.length > 0) && !this._settingUp && this._channel;\n }\n\n // Start publishing queued messages, if there isn't already a worker doing this.\n _startWorker() {\n if(!this._working && this._shouldPublish()) {\n this._working = true;\n this._workerNumber++;\n this._publishQueuedMessages(this._workerNumber);\n }\n }\n\n _publishQueuedMessages(workerNumber) {\n if(!this._shouldPublish() || !this._working || (workerNumber !== this._workerNumber)) {\n // Can't publish anything right now...\n this._working = false;\n return Promise.resolve();\n }\n\n const channel = this._channel;\n const message = this._messages.shift();\n this._unconfirmedMessages.push(message);\n\n Promise.resolve()\n .then(() => {\n const encodedMessage = this._json ? new Buffer.from(JSON.stringify(message.content)) : message.content;\n\n const sendPromise = (() => {\n switch (message.type) {\n case 'publish':\n return new Promise(function(resolve, reject) {\n const result = channel.publish(message.exchange, message.routingKey, encodedMessage,\n message.options,\n err => {\n if(err) {\n reject(err);\n } else {\n setImmediate(() => resolve(result));\n }\n });\n });\n case 'sendToQueue':\n return new Promise(function(resolve, reject) {\n const result = channel.sendToQueue(message.queue, encodedMessage, message.options, err => {\n if(err) {\n reject(err);\n } else {\n setImmediate(() => resolve(result));\n }\n });\n });\n\n /* istanbul ignore next */\n default:\n throw new Error(`Unhandled message type ${message.type}`);\n }\n })();\n\n // Send some more!\n this._publishQueuedMessages(workerNumber);\n\n return sendPromise;\n })\n .then(\n result => {\n this._unconfirmedMessages.shift();\n message.resolve(result);\n },\n\n err => {\n if(!this._channel) {\n // Tried to write to a closed channel. Leave the message in the queue and we'll try again when we\n // reconnect.\n this._messages.unshift(this._unconfirmedMessages.shift());\n } else {\n // Something went wrong trying to send this message - could be JSON.stringify failed, could be the\n // broker rejected the message. Either way, reject it back\n this._unconfirmedMessages.shift();\n message.reject(err);\n }\n }\n )\n .catch( /* istanbul ignore next */ err => {\n this.emit('error', err);\n this._working = false;\n });\n\n return null;\n }\n\n // Send an `ack` to the underlying channel.\n ack() {\n return this._channel && this._channel.ack.apply(this._channel, arguments);\n }\n\n // Send an `ackAll` to the underlying channel.\n ackAll() {\n return this._channel && this._channel.ackAll.apply(this._channel, arguments);\n }\n\n // Send a `nack` to the underlying channel.\n nack() {\n return this._channel && this._channel.nack.apply(this._channel, arguments);\n }\n\n // Send a `nackAll` to the underlying channel.\n nackAll() {\n return this._channel && this._channel.nackAll.apply(this._channel, arguments);\n }\n\n // Send a `purgeQueue` to the underlying channel.\n purgeQueue() {\n return this._channel && this._channel.purgeQueue.apply(this._channel, arguments);\n }\n\n // Send a `checkQueue` to the underlying channel.\n checkQueue() {\n return this._channel && this._channel.checkQueue.apply(this._channel, arguments);\n }\n\n // Send a `assertQueue` to the underlying channel.\n assertQueue() {\n return this._channel && this._channel.assertQueue.apply(this._channel, arguments);\n }\n\n // Send a `bindQueue` to the underlying channel.\n bindQueue() {\n return this._channel && this._channel.bindQueue.apply(this._channel, arguments);\n }\n\n // Send a `assertExchange` to the underlying channel.\n assertExchange() {\n return this._channel && this._channel.assertExchange.apply(this._channel, arguments);\n }\n}\n"],"file":"ChannelWrapper.js"}
1
+ {"version":3,"sources":["../src/ChannelWrapper.js"],"names":["ChannelWrapper","EventEmitter","addSetup","setup","done","pb","addCallback","_settingUp","Promise","resolve","then","_setups","push","_channel","call","undefined","removeSetup","teardown","filter","s","waitForConnect","once","publish","exchange","routingKey","content","options","reject","_messages","type","_startWorker","sendToQueue","queue","constructor","connectionManager","_onConnect","bind","_onDisconnect","_connectionManager","name","context","_json","json","_unconfirmedMessages","_irrecoverableCode","_irrecoverableError","_working","_workerNumber","isConnected","connection","_currentConnection","on","_connection","createConfirmChannel","channel","_onChannelClose","all","map","setupFn","catch","err","emit","length","shift","ex","Error","code","queueLength","close","forEach","message","removeListener","answer","_shouldPublish","_publishQueuedMessages","_canWaitReconnection","includes","workerNumber","encodedMessage","Buffer","from","JSON","stringify","result","sendPromise","setImmediate","removeUnconfirmedMessage","unshift","ack","apply","arguments","ackAll","nack","nackAll","purgeQueue","checkQueue","assertQueue","bindQueue","deleteQueue","assertExchange","get","arr","toRemove","indexOf","removed","splice"],"mappings":";;;;;;;AAAA;;AACA;;;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,MAAMA,cAAN,SAA6BC,oBAA7B,CAA0C;AACrD;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACIC,EAAAA,QAAQ,CAACC,KAAD,EAAQC,IAAI,GAAG,IAAf,EAAqB;AACzB,WAAOC,wBAAGC,WAAH,CACHF,IADG,EAEH,CAAC,KAAKG,UAAL,IAAmBC,OAAO,CAACC,OAAR,EAApB,EAAuCC,IAAvC,CAA4C,MAAM;AAC9C,WAAKC,OAAL,CAAaC,IAAb,CAAkBT,KAAlB;;AACA,UAAI,KAAKU,QAAT,EAAmB;AACf,eAAOR,wBAAGS,IAAH,CAAQX,KAAR,EAAe,IAAf,EAAqB,KAAKU,QAA1B,CAAP;AACH,OAFD,MAEO;AACH,eAAOE,SAAP;AACH;AACJ,KAPD,CAFG,CAAP;AAWH;AAED;AACJ;AACA;AACA;A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A,cAAc,GAAG;AACb,WAAO,KAAKtF,QAAL,IAAiB,KAAKA,QAAL,CAAcsF,cAAd,CAA6BV,KAA7B,CAAmC,KAAK5E,QAAxC,EAAkD6E,SAAlD,CAAxB;AACH,GAzdoD,CA2drD;;;AACAU,EAAAA,GAAG,GAAG;AACF,WAAO,KAAKvF,QAAL,IAAiB,KAAKA,QAAL,CAAcuF,GAAd,CAAkBX,KAAlB,CAAwB,KAAK5E,QAA7B,EAAuC6E,SAAvC,CAAxB;AACH;;AA9doD;;;;AAiezD,SAASJ,wBAAT,CAAkCe,GAAlC,EAAuC/B,OAAvC,EAAgD;AAC5C,QAAMgC,QAAQ,GAAGD,GAAG,CAACE,OAAJ,CAAYjC,OAAZ,CAAjB;;AACA,MAAIgC,QAAQ,KAAK,CAAC,CAAlB,EAAqB;AACjB,UAAM,IAAIrC,KAAJ,CAAW,yCAAX,CAAN;AACH;;AACD,QAAMuC,OAAO,GAAGH,GAAG,CAACI,MAAJ,CAAWH,QAAX,EAAqB,CAArB,CAAhB;AACA,SAAOE,OAAO,CAAC,CAAD,CAAd;AACH","sourcesContent":["import { EventEmitter } from 'events';\nimport pb from 'promise-breaker';\n\n/**\n * Calls to `publish()` or `sendToQueue()` work just like in amqplib, but messages are queued internally and\n * are guaranteed to be delivered. If the underlying connection drops, ChannelWrapper will wait for a new\n * connection and continue.\n *\n * Events:\n * * `connect` - emitted every time this channel connects or reconnects.\n * * `error(err, {name})` - emitted if an error occurs setting up the channel.\n * * `drop({message, err})` - called when a JSON message was dropped because it could not be encoded.\n * * `close` - emitted when this channel closes via a call to `close()`\n *\n */\nexport default class ChannelWrapper extends EventEmitter {\n /**\n * Adds a new 'setup handler'.\n *\n * `setup(channel, [cb])` is a function to call when a new underlying channel is created - handy for asserting\n * exchanges and queues exists, and whatnot. The `channel` object here is a ConfigChannel from amqplib.\n * The `setup` function should return a Promise (or optionally take a callback) - no messages will be sent until\n * this Promise resolves.\n *\n * If there is a connection, `setup()` will be run immediately, and the addSetup Promise/callback won't resolve\n * until `setup` is complete. Note that in this case, if the setup throws an error, no 'error' event will\n * be emitted, since you can just handle the error here (although the `setup` will still be added for future\n * reconnects, even if it throws an error.)\n *\n * Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error'\n * event.\n *\n * @param {function} setup - setup function.\n * @param {function} [done] - callback.\n * @returns {void | Promise} - Resolves when complete.\n */\n addSetup(setup, done = null) {\n return pb.addCallback(\n done,\n (this._settingUp || Promise.resolve()).then(() => {\n this._setups.push(setup);\n if (this._channel) {\n return pb.call(setup, this, this._channel);\n } else {\n return undefined;\n }\n })\n );\n }\n\n /**\n * Remove a setup function added with `addSetup`. If there is currently a\n * connection, `teardown(channel, [cb])` will be run immediately, and the\n * returned Promise will not resolve until it completes.\n *\n * @param {function} setup - the setup function to remove.\n * @param {function} [teardown] - `function(channel, [cb])` to run to tear\n * down the channel.\n * @param {function} [done] - Optional callback.\n * @returns {void | Promise} - Resolves when complete.\n */\n removeSetup(setup, teardown = null, done = null) {\n return pb.addCallback(done, () => {\n this._setups = this._setups.filter((s) => s !== setup);\n\n return (this._settingUp || Promise.resolve()).then(() =>\n this._channel ? pb.call(teardown, this, this._channel) : undefined\n );\n });\n }\n\n /**\n * Returns a Promise which resolves when this channel next connects.\n * (Mainly here for unit testing...)\n *\n * @param {function} [done] - Optional callback.\n * @returns {void | Promise} - Resolves when connected.\n */\n waitForConnect(done = null) {\n return pb.addCallback(\n done,\n this._channel && !this._settingUp\n ? Promise.resolve()\n : new Promise((resolve) => this.once('connect', resolve))\n );\n }\n\n /*\n * Publish a message to the channel.\n *\n * This works just like amqplib's `publish()`, except if the channel is not\n * connected, this will wait until the channel is connected. Returns a\n * Promise which will only resolve when the message has been succesfully sent.\n * The returned promise will be rejected if `close()` is called on this\n * channel before it can be sent, if `options.json` is set and the message\n * can't be encoded, or if the broker rejects the message for some reason.\n *\n */\n publish(exchange, routingKey, content, options, done = null) {\n return pb.addCallback(\n done,\n new Promise((resolve, reject) => {\n this._messages.push({\n type: 'publish',\n exchange,\n routingKey,\n content,\n options,\n resolve,\n reject,\n });\n this._startWorker();\n })\n );\n }\n\n /*\n * Send a message to a queue.\n *\n * This works just like amqplib's `sendToQueue`, except if the channel is not connected, this will wait until the\n * channel is connected. Returns a Promise which will only resolve when the message has been succesfully sent.\n * The returned promise will be rejected only if `close()` is called on this channel before it can be sent.\n *\n * `message` here should be a JSON-able object.\n */\n sendToQueue(queue, content, options, done = null) {\n return pb.addCallback(\n done,\n new Promise((resolve, reject) => {\n this._messages.push({\n type: 'sendToQueue',\n queue,\n content,\n options,\n resolve,\n reject,\n });\n return this._startWorker();\n })\n );\n }\n\n /**\n * Create a new ChannelWrapper.\n *\n * @param {AmqpConnectionManager} connectionManager - connection manager which\n * created this channel.\n * @param {Object} [options] -\n * @param {string} [options.name] - A name for this channel. Handy for debugging.\n * @param {function} [options.setup] - A default setup function to call. See\n * `addSetup` for details.\n * @param {boolean} [options.json] - if true, then ChannelWrapper assumes all\n * messages passed to `publish()` and `sendToQueue()` are plain JSON objects.\n * These will be encoded automatically before being sent.\n *\n */\n constructor(connectionManager, options = {}) {\n super();\n this._onConnect = this._onConnect.bind(this);\n this._onDisconnect = this._onDisconnect.bind(this);\n this._connectionManager = connectionManager;\n this.name = options.name;\n\n this.context = {};\n\n this._json = 'json' in options ? options.json : false;\n\n // Place to store queued messages.\n this._messages = [];\n\n // Place to store published, but not yet confirmed messages\n this._unconfirmedMessages = [];\n\n // Place to store reason code during publish or sendtoqueue messages.\n this._irrecoverableCode = null;\n // Irrecoverable error.\n this._irrecoverableError = [\n 403, // AMQP Access Refused Error.\n 404, // AMQP Not Found Error.\n 406, // AMQP Precondition Failed Error.\n 501, // AMQP Frame Error.\n 502, // AMQP Frame Syntax Error.\n 503, // AMQP Invalid Command Error.\n 504, // AMQP Channel Not Open Error.\n 505, // AMQP Unexpected Frame.\n 530, // AMQP Not Allowed Error.\n 540, // AMQP Not Implemented Error.\n 541, // AMQP Internal Error.\n ];\n\n // True if the \"worker\" is busy sending messages. False if we need to\n // start the worker to get stuff done.\n this._working = false;\n\n // If we're in the process of creating a channel, this is a Promise which\n // will resolve when the channel is set up. Otherwise, this is `null`.\n this._settingUp = null;\n\n // The currently connected channel. Note that not all setup functions\n // have been run on this channel until `@_settingUp` is either null or\n // resolved.\n this._channel = null;\n\n // We kill off workers when we disconnect. Whenever we start a new\n // worker, we bump up the `_workerNumber` - this makes it so if stale\n // workers ever do wake up, they'll know to stop working.\n this._workerNumber = 0;\n\n // Array of setup functions to call.\n this._setups = [];\n if (options.setup) {\n this._setups.push(options.setup);\n }\n\n if (connectionManager.isConnected()) {\n this._onConnect({\n connection: this._connectionManager._currentConnection,\n });\n }\n connectionManager.on('connect', this._onConnect);\n connectionManager.on('disconnect', this._onDisconnect);\n }\n\n // Called whenever we connect to the broker.\n _onConnect({ connection }) {\n this._connection = connection;\n this._irrecoverableCode = null;\n\n return connection\n .createConfirmChannel()\n .then((channel) => {\n this._channel = channel;\n channel.on('close', () => this._onChannelClose(channel));\n\n this._settingUp = Promise.all(\n this._setups.map((setupFn) =>\n // TODO: Use a timeout here to guard against setupFns that never resolve?\n pb.call(setupFn, this, channel).catch((err) => {\n if (this._channel) {\n this.emit('error', err, { name: this.name });\n } else {\n // Don't emit an error if setups failed because the channel was closing.\n }\n })\n )\n ).then(() => {\n this._settingUp = null;\n return this._channel;\n });\n\n return this._settingUp;\n })\n .then(() => {\n if (!this._channel) {\n // Can happen if channel closes while we're setting up.\n return;\n }\n if (this._unconfirmedMessages.length > 0) {\n // requeu any messages that were left unconfirmed when connection was lost\n while (this._unconfirmedMessages.length) {\n this._messages.push(this._unconfirmedMessages.shift());\n }\n }\n\n // Since we just connected, publish any queued messages\n this._startWorker();\n this.emit('connect');\n })\n .catch((err) => {\n this.emit('error', err, { name: this.name });\n this._settingUp = null;\n this._channel = null;\n });\n }\n\n // Called whenever the channel closes.\n _onChannelClose(channel) {\n if (this._channel === channel) {\n this._channel = null;\n }\n }\n // Wait for another reconnect to create a new channel.\n\n // Called whenever we disconnect from the AMQP server.\n _onDisconnect(ex) {\n this._irrecoverableCode = (ex.err instanceof Error ? ex.err.code : null) || null;\n this._channel = null;\n this._settingUp = null;\n\n // Kill off the current worker. We never get any kind of error for messages in flight - see\n // https://github.com/squaremo/amqp.node/issues/191.\n this._working = false;\n }\n\n // Returns the number of unsent messages queued on this channel.\n queueLength() {\n return this._messages.length;\n }\n\n // Destroy this channel.\n //\n // Any unsent messages will have their associated Promises rejected.\n //\n close() {\n return Promise.resolve().then(() => {\n this._working = false;\n if (this._messages.length !== 0) {\n // Reject any unsent messages.\n this._messages.forEach((message) => message.reject(new Error('Channel closed')));\n }\n if (this._unconfirmedMessages.length !== 0) {\n // Reject any unconfirmed messages.\n this._unconfirmedMessages.forEach((message) =>\n message.reject(new Error('Channel closed'))\n );\n }\n\n this._connectionManager.removeListener('connect', this._onConnect);\n this._connectionManager.removeListener('disconnect', this._onDisconnect);\n const answer = (this._channel && this._channel.close()) || undefined;\n this._channel = null;\n\n this.emit('close');\n\n return answer;\n });\n }\n\n _shouldPublish() {\n return this._messages.length > 0 && !this._settingUp && this._channel;\n }\n\n // Start publishing queued messages, if there isn't already a worker doing this.\n _startWorker() {\n if (!this._working && this._shouldPublish()) {\n this._working = true;\n this._workerNumber++;\n this._publishQueuedMessages(this._workerNumber);\n }\n }\n\n // Define if a message can cause irrecoverable error\n _canWaitReconnection() {\n return !this._irrecoverableError.includes(this._irrecoverableCode);\n }\n\n _publishQueuedMessages(workerNumber) {\n if (!this._shouldPublish() || !this._working || workerNumber !== this._workerNumber) {\n // Can't publish anything right now...\n this._working = false;\n return Promise.resolve();\n }\n\n const channel = this._channel;\n const message = this._messages.shift();\n this._unconfirmedMessages.push(message);\n\n Promise.resolve()\n .then(() => {\n const encodedMessage = this._json\n ? new Buffer.from(JSON.stringify(message.content))\n : message.content;\n\n let result = true;\n const sendPromise = (() => {\n switch (message.type) {\n case 'publish':\n return new Promise(function (resolve, reject) {\n result = channel.publish(\n message.exchange,\n message.routingKey,\n encodedMessage,\n message.options,\n (err) => {\n if (err) {\n reject(err);\n } else {\n setImmediate(() => resolve(result));\n }\n }\n );\n });\n case 'sendToQueue':\n return new Promise(function (resolve, reject) {\n result = channel.sendToQueue(\n message.queue,\n encodedMessage,\n message.options,\n (err) => {\n if (err) {\n reject(err);\n } else {\n setImmediate(() => resolve(result));\n }\n }\n );\n });\n /* istanbul ignore next */\n default:\n throw new Error(`Unhandled message type ${message.type}`);\n }\n })();\n\n if (result) {\n this._publishQueuedMessages(workerNumber);\n } else {\n this._channel.once('drain', () => this._publishQueuedMessages(workerNumber));\n }\n return sendPromise;\n })\n .then(\n (result) => {\n removeUnconfirmedMessage(this._unconfirmedMessages, message);\n message.resolve(result);\n },\n\n (err) => {\n if (!this._channel && this._canWaitReconnection()) {\n // Tried to write to a closed channel. Leave the message in the queue and we'll try again when we\n // reconnect.\n removeUnconfirmedMessage(this._unconfirmedMessages, message);\n this._messages.unshift(message);\n } else {\n // Something went wrong trying to send this message - could be JSON.stringify failed, could be the\n // broker rejected the message. Either way, reject it back\n removeUnconfirmedMessage(this._unconfirmedMessages, message);\n message.reject(err);\n }\n }\n )\n .catch(\n /* istanbul ignore next */ (err) => {\n this.emit('error', err);\n this._working = false;\n }\n );\n\n return null;\n }\n\n // Send an `ack` to the underlying channel.\n ack() {\n return this._channel && this._channel.ack.apply(this._channel, arguments);\n }\n\n // Send an `ackAll` to the underlying channel.\n ackAll() {\n return this._channel && this._channel.ackAll.apply(this._channel, arguments);\n }\n\n // Send a `nack` to the underlying channel.\n nack() {\n return this._channel && this._channel.nack.apply(this._channel, arguments);\n }\n\n // Send a `nackAll` to the underlying channel.\n nackAll() {\n return this._channel && this._channel.nackAll.apply(this._channel, arguments);\n }\n\n // Send a `purgeQueue` to the underlying channel.\n purgeQueue() {\n return this._channel && this._channel.purgeQueue.apply(this._channel, arguments);\n }\n\n // Send a `checkQueue` to the underlying channel.\n checkQueue() {\n return this._channel && this._channel.checkQueue.apply(this._channel, arguments);\n }\n\n // Send a `assertQueue` to the underlying channel.\n assertQueue() {\n return this._channel && this._channel.assertQueue.apply(this._channel, arguments);\n }\n\n // Send a `bindQueue` to the underlying channel.\n bindQueue() {\n return this._channel && this._channel.bindQueue.apply(this._channel, arguments);\n }\n\n // Send a `deleteQueue` to the underlying channel.\n deleteQueue() {\n return this._channel && this._channel.deleteQueue.apply(this._channel, arguments);\n }\n\n // Send a `assertExchange` to the underlying channel.\n assertExchange() {\n return this._channel && this._channel.assertExchange.apply(this._channel, arguments);\n }\n\n // Send a `get` to the underlying channel.\n get() {\n return this._channel && this._channel.get.apply(this._channel, arguments);\n }\n}\n\nfunction removeUnconfirmedMessage(arr, message) {\n const toRemove = arr.indexOf(message);\n if (toRemove === -1) {\n throw new Error(`Message is not in _unconfirmedMessages!`);\n }\n const removed = arr.splice(toRemove, 1);\n return removed[0];\n}\n"],"file":"ChannelWrapper.js"}
package/lib/helpers.js CHANGED
@@ -6,8 +6,18 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.wait = wait;
7
7
 
8
8
  function wait(timeInMs) {
9
- return new Promise(function (resolve) {
10
- return setTimeout(resolve, timeInMs);
11
- });
9
+ let timeoutHandle;
10
+
11
+ const promise = () => {
12
+ return new Promise(function (resolve) {
13
+ timeoutHandle = setTimeout(resolve, timeInMs);
14
+ return timeoutHandle;
15
+ });
16
+ };
17
+
18
+ return {
19
+ promise,
20
+ cancel: () => clearTimeout(timeoutHandle)
21
+ };
12
22
  }
13
23
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers.js"],"names":["wait","timeInMs","Promise","resolve","setTimeout"],"mappings":";;;;;;;AAAO,SAASA,IAAT,CAAcC,QAAd,EAAwB;AAC3B,SAAO,IAAIC,OAAJ,CAAY,UAASC,OAAT,EAAkB;AACjC,WAAOC,UAAU,CAACD,OAAD,EAAUF,QAAV,CAAjB;AACH,GAFM,CAAP;AAGH","sourcesContent":["export function wait(timeInMs) {\n return new Promise(function(resolve) {\n return setTimeout(resolve, timeInMs);\n });\n}"],"file":"helpers.js"}
1
+ {"version":3,"sources":["../src/helpers.js"],"names":["wait","timeInMs","timeoutHandle","promise","Promise","resolve","setTimeout","cancel","clearTimeout"],"mappings":";;;;;;;AAAO,SAASA,IAAT,CAAcC,QAAd,EAAwB;AAC3B,MAAIC,aAAJ;;AAEA,QAAMC,OAAO,GAAG,MAAM;AAClB,WAAO,IAAIC,OAAJ,CAAY,UAAUC,OAAV,EAAmB;AAClCH,MAAAA,aAAa,GAAGI,UAAU,CAACD,OAAD,EAAUJ,QAAV,CAA1B;AACA,aAAOC,aAAP;AACH,KAHM,CAAP;AAIH,GALD;;AAOA,SAAO;AAAEC,IAAAA,OAAF;AAAWI,IAAAA,MAAM,EAAE,MAAMC,YAAY,CAACN,aAAD;AAArC,GAAP;AACH","sourcesContent":["export function wait(timeInMs) {\n let timeoutHandle;\n\n const promise = () => {\n return new Promise(function (resolve) {\n timeoutHandle = setTimeout(resolve, timeInMs);\n return timeoutHandle;\n });\n };\n\n return { promise, cancel: () => clearTimeout(timeoutHandle) };\n}\n"],"file":"helpers.js"}
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["connect","urls","options","AmqpConnectionManager","amqp"],"mappings":";;;;;;;;AAAA;;;;AAEO,SAASA,OAAT,CAAiBC,IAAjB,EAAuBC,OAAvB,EAAgC;AACnC,SAAO,IAAIC,8BAAJ,CAA0BF,IAA1B,EAAgCC,OAAhC,CAAP;AACH;;AAED,MAAME,IAAI,GAAG;AACTJ,EAAAA;AADS,CAAb;eAIeI,I","sourcesContent":["import AmqpConnectionManager from './AmqpConnectionManager';\n\nexport function connect(urls, options) {\n return new AmqpConnectionManager(urls, options);\n}\n\nconst amqp = {\n connect\n};\n\nexport default amqp;"],"file":"index.js"}
1
+ {"version":3,"sources":["../src/index.js"],"names":["connect","urls","options","AmqpConnectionManager","amqp"],"mappings":";;;;;;;;AAAA;;;;AAEO,SAASA,OAAT,CAAiBC,IAAjB,EAAuBC,OAAvB,EAAgC;AACnC,SAAO,IAAIC,8BAAJ,CAA0BF,IAA1B,EAAgCC,OAAhC,CAAP;AACH;;AAED,MAAME,IAAI,GAAG;AACTJ,EAAAA;AADS,CAAb;eAIeI,I","sourcesContent":["import AmqpConnectionManager from './AmqpConnectionManager';\n\nexport function connect(urls, options) {\n return new AmqpConnectionManager(urls, options);\n}\n\nconst amqp = {\n connect,\n};\n\nexport default amqp;\n"],"file":"index.js"}
package/package.json CHANGED
@@ -1,77 +1,80 @@
1
1
  {
2
- "name": "amqp-connection-manager",
3
- "version": "3.2.0",
4
- "description": "Auto-reconnect and round robin support for amqplib.",
5
- "main": "lib/index.js",
6
- "dependencies": {
7
- "promise-breaker": "^5.0.0"
8
- },
9
- "peerDependencies": {
10
- "amqplib": "*"
11
- },
12
- "devDependencies": {
13
- "@babel/cli": "^7.2.3",
14
- "@babel/core": "^7.3.3",
15
- "@babel/preset-env": "^7.3.1",
16
- "@babel/register": "^7.0.0",
17
- "@jwalton/semantic-release-config": "^1.0.0",
18
- "@semantic-release/changelog": "^3.0.1",
19
- "@semantic-release/git": "^7.0.1",
20
- "amqplib": "^0.5.1",
21
- "babel-plugin-istanbul": "^5.1.1",
22
- "chai": "^4.1.2",
23
- "chai-as-promised": "^7.1.1",
24
- "chai-string": "^1.1.2",
25
- "coveralls": "^3.0.0",
26
- "cross-env": "^6.0.0",
27
- "eslint": "^6.5.1",
28
- "eslint-config-benbria": "^4.0.2",
29
- "eslint-plugin-import": "^2.18.0",
30
- "eslint-plugin-promise": "^4.2.1",
31
- "greenkeeper-lockfile": "^1.14.0",
32
- "husky": "^4.0.2",
33
- "istanbul": "^0.4.0",
34
- "mocha": "^6.1.4",
35
- "nyc": "^14.0.0",
36
- "promise-tools": "^2.0.0",
37
- "proxyquire": "^2.0.1",
38
- "semantic-release": "^15.13.18",
39
- "sinon": "^8.1.0"
40
- },
41
- "engines": {
42
- "node": ">=6.0.0",
43
- "npm": ">5.0.0"
44
- },
45
- "scripts": {
46
- "prepare": "npm run build",
47
- "prepublishOnly": "npm test",
48
- "build": "babel -s -d lib src",
49
- "clean": "rm -rf lib coverage",
50
- "test": "npm run test:lint && npm run test:unittest",
51
- "test:unittest": "cross-env NODE_ENV=test nyc mocha",
52
- "test:lint": "eslint src test",
53
- "precommit:unittest": "cross-env BABEL_DISABLE_CACHE=1 cross-env NODE_ENV=test nyc mocha --reporter progress",
54
- "semantic-release": "semantic-release"
55
- },
56
- "husky": {
57
- "hooks": {
58
- "pre-commit": "npm run test:lint && npm run precommit:unittest"
59
- }
60
- },
61
- "repository": {
62
- "type": "git",
63
- "url": "https://github.com/benbria/node-amqp-connection-manager"
64
- },
65
- "keywords": [
66
- "amqp",
67
- "rabbitmq",
68
- "cluster",
69
- "amqplib"
70
- ],
71
- "author": "Jason Walton <dev@lucid.thedreaming.org> (https://github.com/jwalton)",
72
- "license": "MIT",
73
- "bugs": {
74
- "url": "https://github.com/benbria/node-amqp-connection-manager/issues"
75
- },
76
- "homepage": "https://github.com/benbria/node-amqp-connection-manager"
2
+ "name": "amqp-connection-manager",
3
+ "version": "3.2.4",
4
+ "description": "Auto-reconnect and round robin support for amqplib.",
5
+ "main": "lib/index.js",
6
+ "dependencies": {
7
+ "promise-breaker": "^5.0.0"
8
+ },
9
+ "peerDependencies": {
10
+ "amqplib": "*"
11
+ },
12
+ "devDependencies": {
13
+ "@babel/cli": "^7.11.6",
14
+ "@babel/core": "^7.11.6",
15
+ "@babel/preset-env": "^7.11.5",
16
+ "@babel/register": "^7.11.5",
17
+ "@jwalton/semantic-release-config": "^1.0.0",
18
+ "@semantic-release/changelog": "^5.0.1",
19
+ "@semantic-release/git": "^9.0.0",
20
+ "amqplib": "^0.8.0",
21
+ "babel-plugin-istanbul": "^6.0.0",
22
+ "chai": "^4.1.2",
23
+ "chai-as-promised": "^7.1.1",
24
+ "chai-string": "^1.1.2",
25
+ "coveralls": "^3.1.0",
26
+ "cross-env": "^7.0.2",
27
+ "eslint": "^7.8.1",
28
+ "eslint-config-benbria": "^4.0.3",
29
+ "eslint-plugin-import": "^2.22.0",
30
+ "eslint-plugin-promise": "^5.0.0",
31
+ "greenkeeper-lockfile": "^1.14.0",
32
+ "husky": "^7.0.1",
33
+ "istanbul": "^0.4.0",
34
+ "lint-staged": "^11.1.2",
35
+ "mocha": "^9.0.1",
36
+ "nyc": "^15.1.0",
37
+ "prettier": "^2.3.2",
38
+ "pretty-quick": "^3.1.1",
39
+ "promise-tools": "^2.1.0",
40
+ "proxyquire": "^2.1.3",
41
+ "semantic-release": "^17.1.1",
42
+ "sinon": "^11.0.0"
43
+ },
44
+ "engines": {
45
+ "node": ">=6.0.0",
46
+ "npm": ">5.0.0"
47
+ },
48
+ "scripts": {
49
+ "prepare": "husky install && npm run build",
50
+ "prepublishOnly": "npm test",
51
+ "build": "babel -s -d lib src",
52
+ "clean": "rm -rf lib coverage",
53
+ "test": "npm run test:lint && npm run test:unittest",
54
+ "test:unittest": "cross-env NODE_ENV=test nyc mocha",
55
+ "test:lint": "eslint src test",
56
+ "precommit:unittest": "cross-env BABEL_DISABLE_CACHE=1 cross-env NODE_ENV=test nyc mocha --reporter progress",
57
+ "semantic-release": "semantic-release"
58
+ },
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "https://github.com/jwalton/node-amqp-connection-manager"
62
+ },
63
+ "lint-staged": {
64
+ "**/*.js": [
65
+ "eslint"
66
+ ]
67
+ },
68
+ "keywords": [
69
+ "amqp",
70
+ "rabbitmq",
71
+ "cluster",
72
+ "amqplib"
73
+ ],
74
+ "author": "Jason Walton <dev@lucid.thedreaming.org> (https://github.com/jwalton)",
75
+ "license": "MIT",
76
+ "bugs": {
77
+ "url": "https://github.com/jwalton/node-amqp-connection-manager/issues"
78
+ },
79
+ "homepage": "https://github.com/jwalton/node-amqp-connection-manager"
77
80
  }