amqp-connection-manager 3.1.0 → 3.2.2

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.
package/CHANGELOG.md CHANGED
@@ -1,16 +1,45 @@
1
- # [3.1.0](https://github.com/benbria/node-amqp-connection-manager/compare/v3.0.0...v3.1.0) (2019-12-06)
1
+ ## [3.2.2](https://github.com/jwalton/node-amqp-connection-manager/compare/v3.2.1...v3.2.2) (2021-02-09)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * When messages are acked/nacked, make sure we remove the correct message from the sent messages queue. ([c662026](https://github.com/jwalton/node-amqp-connection-manager/commit/c662026bc287e684a0f43ce2de7a44b80a88e8ff)), closes [#142](https://github.com/jwalton/node-amqp-connection-manager/issues/142)
7
+
8
+ ## [3.2.1](https://github.com/jwalton/node-amqp-connection-manager/compare/v3.2.0...v3.2.1) (2020-09-12)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * Push never resolves if error occured (courtesy @SSANSH). ([48a78f8](https://github.com/jwalton/node-amqp-connection-manager/commit/48a78f8de5d39002035b37f27fc3e0ce5015490c))
14
+ * **package:** resolve hanging retry connection timeout by introducing cancelable timeout ([e37dd1a](https://github.com/jwalton/node-amqp-connection-manager/commit/e37dd1a4e423012910d31ae8bcebf781cac6f3b5))
15
+
16
+ # [3.2.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v3.1.1...v3.2.0) (2020-01-20)
17
+
18
+
19
+ ### Features
20
+
21
+ * add bindQueue and assertExchange on ChannelWrapper ([879e522](https://github.com/jwalton/node-amqp-connection-manager/commit/879e522))
22
+
23
+ ## [3.1.1](https://github.com/jwalton/node-amqp-connection-manager/compare/v3.1.0...v3.1.1) (2020-01-06)
24
+
25
+
26
+ ### Bug Fixes
27
+
28
+ * typo ([6055b02](https://github.com/jwalton/node-amqp-connection-manager/commit/6055b02))
29
+
30
+ # [3.1.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v3.0.0...v3.1.0) (2019-12-06)
2
31
 
3
32
 
4
33
  ### Features
5
34
 
6
- * Allow using URL object to connect, same format as amqplib accepts. ([f046680](https://github.com/benbria/node-amqp-connection-manager/commit/f046680))
35
+ * Allow using URL object to connect, same format as amqplib accepts. ([f046680](https://github.com/jwalton/node-amqp-connection-manager/commit/f046680))
7
36
 
8
- # [3.0.0](https://github.com/benbria/node-amqp-connection-manager/compare/v2.3.3...v3.0.0) (2019-07-04)
37
+ # [3.0.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.3.3...v3.0.0) (2019-07-04)
9
38
 
10
39
 
11
40
  ### Continuous Integration
12
41
 
13
- * Stop running tests for node 6 and node 8. ([164b882](https://github.com/benbria/node-amqp-connection-manager/commit/164b882))
42
+ * Stop running tests for node 6 and node 8. ([164b882](https://github.com/jwalton/node-amqp-connection-manager/commit/164b882))
14
43
 
15
44
 
16
45
  ### BREAKING CHANGES
@@ -18,69 +47,69 @@
18
47
  * Officially drop support for node 6 and node 8 (although they will probably still
19
48
  work).
20
49
 
21
- ## [2.3.3](https://github.com/benbria/node-amqp-connection-manager/compare/v2.3.2...v2.3.3) (2019-06-25)
50
+ ## [2.3.3](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.3.2...v2.3.3) (2019-06-25)
22
51
 
23
52
 
24
53
  ### Bug Fixes
25
54
 
26
- * **package:** update promise-breaker to version 5.0.0 ([ed91042](https://github.com/benbria/node-amqp-connection-manager/commit/ed91042))
55
+ * **package:** update promise-breaker to version 5.0.0 ([ed91042](https://github.com/jwalton/node-amqp-connection-manager/commit/ed91042))
27
56
 
28
- ## [2.3.2](https://github.com/benbria/node-amqp-connection-manager/compare/v2.3.1...v2.3.2) (2019-05-21)
57
+ ## [2.3.2](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.3.1...v2.3.2) (2019-05-21)
29
58
 
30
59
 
31
60
  ### Bug Fixes
32
61
 
33
- * Null delta to get semantic-release to pick up [#65](https://github.com/benbria/node-amqp-connection-manager/issues/65). Fix [#84](https://github.com/benbria/node-amqp-connection-manager/issues/84). ([9737135](https://github.com/benbria/node-amqp-connection-manager/commit/9737135))
62
+ * Null delta to get semantic-release to pick up [#65](https://github.com/jwalton/node-amqp-connection-manager/issues/65). Fix [#84](https://github.com/jwalton/node-amqp-connection-manager/issues/84). ([9737135](https://github.com/jwalton/node-amqp-connection-manager/commit/9737135))
34
63
 
35
- ## [2.3.1](https://github.com/benbria/node-amqp-connection-manager/compare/v2.3.0...v2.3.1) (2019-04-01)
64
+ ## [2.3.1](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.3.0...v2.3.1) (2019-04-01)
36
65
 
37
66
 
38
67
  ### Bug Fixes
39
68
 
40
- * prevent too many connection attempts on error ([2760ce5](https://github.com/benbria/node-amqp-connection-manager/commit/2760ce5)), closes [#77](https://github.com/benbria/node-amqp-connection-manager/issues/77)
69
+ * prevent too many connection attempts on error ([2760ce5](https://github.com/jwalton/node-amqp-connection-manager/commit/2760ce5)), closes [#77](https://github.com/jwalton/node-amqp-connection-manager/issues/77)
41
70
 
42
- # [2.3.0](https://github.com/benbria/node-amqp-connection-manager/compare/v2.2.0...v2.3.0) (2018-11-20)
71
+ # [2.3.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.2.0...v2.3.0) (2018-11-20)
43
72
 
44
73
 
45
74
  ### Features
46
75
 
47
- * Add ChannelWrapper.ackAll() and ChannelWrapper.nackAll(). ([0246695](https://github.com/benbria/node-amqp-connection-manager/commit/0246695)), closes [#60](https://github.com/benbria/node-amqp-connection-manager/issues/60)
76
+ * Add ChannelWrapper.ackAll() and ChannelWrapper.nackAll(). ([0246695](https://github.com/jwalton/node-amqp-connection-manager/commit/0246695)), closes [#60](https://github.com/jwalton/node-amqp-connection-manager/issues/60)
48
77
 
49
- # [2.2.0](https://github.com/benbria/node-amqp-connection-manager/compare/v2.1.2...v2.2.0) (2018-09-25)
78
+ # [2.2.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.1.2...v2.2.0) (2018-09-25)
50
79
 
51
80
 
52
81
  ### Features
53
82
 
54
- * Set 'this' to be the channel wrapper in the setup function. ([551200f](https://github.com/benbria/node-amqp-connection-manager/commit/551200f))
83
+ * Set 'this' to be the channel wrapper in the setup function. ([551200f](https://github.com/jwalton/node-amqp-connection-manager/commit/551200f))
55
84
 
56
- ## [2.1.2](https://github.com/benbria/node-amqp-connection-manager/compare/v2.1.1...v2.1.2) (2018-09-13)
85
+ ## [2.1.2](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.1.1...v2.1.2) (2018-09-13)
57
86
 
58
87
 
59
88
  ### Bug Fixes
60
89
 
61
- * Export a default object from root module. ([78893c9](https://github.com/benbria/node-amqp-connection-manager/commit/78893c9)), closes [#51](https://github.com/benbria/node-amqp-connection-manager/issues/51)
90
+ * Export a default object from root module. ([78893c9](https://github.com/jwalton/node-amqp-connection-manager/commit/78893c9)), closes [#51](https://github.com/jwalton/node-amqp-connection-manager/issues/51)
62
91
 
63
- ## [2.1.1](https://github.com/benbria/node-amqp-connection-manager/compare/v2.1.0...v2.1.1) (2018-09-05)
92
+ ## [2.1.1](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.1.0...v2.1.1) (2018-09-05)
64
93
 
65
94
 
66
95
  ### Bug Fixes
67
96
 
68
- * Remove reconnection listener when closing the connection manager. ([eeb6e2b](https://github.com/benbria/node-amqp-connection-manager/commit/eeb6e2b))
97
+ * Remove reconnection listener when closing the connection manager. ([eeb6e2b](https://github.com/jwalton/node-amqp-connection-manager/commit/eeb6e2b))
69
98
 
70
- # [2.1.0](https://github.com/benbria/node-amqp-connection-manager/compare/v2.0.0...v2.1.0) (2018-08-09)
99
+ # [2.1.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v2.0.0...v2.1.0) (2018-08-09)
71
100
 
72
101
 
73
102
  ### Features
74
103
 
75
- * Support for per URL connection options ([ec2d484](https://github.com/benbria/node-amqp-connection-manager/commit/ec2d484)), closes [#29](https://github.com/benbria/node-amqp-connection-manager/issues/29) [#34](https://github.com/benbria/node-amqp-connection-manager/issues/34) [#44](https://github.com/benbria/node-amqp-connection-manager/issues/44)
104
+ * Support for per URL connection options ([ec2d484](https://github.com/jwalton/node-amqp-connection-manager/commit/ec2d484)), closes [#29](https://github.com/jwalton/node-amqp-connection-manager/issues/29) [#34](https://github.com/jwalton/node-amqp-connection-manager/issues/34) [#44](https://github.com/jwalton/node-amqp-connection-manager/issues/44)
76
105
 
77
106
  <a name="2.0.0"></a>
78
- # [2.0.0](https://github.com/benbria/node-amqp-connection-manager/compare/v1.4.2...v2.0.0) (2018-05-05)
107
+ # [2.0.0](https://github.com/jwalton/node-amqp-connection-manager/compare/v1.4.2...v2.0.0) (2018-05-05)
79
108
 
80
109
 
81
110
  ### Code Refactoring
82
111
 
83
- * Rewrite all source in javascript. ([377d01d](https://github.com/benbria/node-amqp-connection-manager/commit/377d01d))
112
+ * Rewrite all source in javascript. ([377d01d](https://github.com/jwalton/node-amqp-connection-manager/commit/377d01d))
84
113
 
85
114
 
86
115
  ### BREAKING CHANGES
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
- [![Build Status](https://travis-ci.org/benbria/node-amqp-connection-manager.svg?branch=master)](https://travis-ci.org/benbria/node-amqp-connection-manager)
2
- [![Coverage Status](https://coveralls.io/repos/benbria/node-amqp-connection-manager/badge.svg?branch=master&service=github)](https://coveralls.io/github/benbria/node-amqp-connection-manager?branch=master)
3
- [![Greenkeeper badge](https://badges.greenkeeper.io/benbria/node-amqp-connection-manager.svg)](https://greenkeeper.io/)
1
+ [![NPM version](https://badge.fury.io/js/amqp-connection-manager.svg)](https://npmjs.org/package/amqp-connection-manager)
2
+ ![Build Status](https://github.com/jwalton/amqp-connection-manager/workflows/GitHub%20CI/badge.svg)
3
+ [![Coverage Status](https://coveralls.io/repos/jwalton/node-amqp-connection-manager/badge.svg?branch=master&service=github)](https://coveralls.io/github/jwalton/node-amqp-connection-manager?branch=master)
4
4
  [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
5
5
 
6
- [![Dependency Status](https://david-dm.org/benbria/node-amqp-connection-manager.svg)](https://david-dm.org/benbria/node-amqp-connection-manager)
7
- [![devDependency Status](https://david-dm.org/benbria/node-amqp-connection-manager/dev-status.svg)](https://david-dm.org/benbria/node-amqp-connection-manager#info=devDependencies)
8
- [![peerDependency Status](https://david-dm.org/benbria/node-amqp-connection-manager/peer-status.svg)](https://david-dm.org/benbria/node-amqp-connection-manager#info=peerDependencies)
6
+ [![Dependency Status](https://david-dm.org/jwalton/node-amqp-connection-manager.svg)](https://david-dm.org/jwalton/node-amqp-connection-manager)
7
+ [![devDependency Status](https://david-dm.org/jwalton/node-amqp-connection-manager/dev-status.svg)](https://david-dm.org/jwalton/node-amqp-connection-manager#info=devDependencies)
8
+ [![peerDependency Status](https://david-dm.org/jwalton/node-amqp-connection-manager/peer-status.svg)](https://david-dm.org/jwalton/node-amqp-connection-manager#info=peerDependencies)
9
9
 
10
10
  Connection management for amqplib.
11
11
 
@@ -96,17 +96,26 @@ class AmqpConnectionManager extends _events.EventEmitter {
96
96
  }
97
97
 
98
98
  this._closed = true;
99
- return Promise.all(this._channels.map(channel => channel.close())).catch(function () {// Ignore errors closing channels.
100
- }).then(() => {
101
- this._channels = [];
102
99
 
103
- if (this._currentConnection) {
104
- this._currentConnection.removeAllListeners('close');
100
+ if (this._cancelRetriesHandler) {
101
+ this._cancelRetriesHandler();
105
102
 
106
- this._currentConnection.close();
107
- }
103
+ this._cancelRetriesHandler = null;
104
+ }
108
105
 
109
- this._currentConnection = null;
106
+ return Promise.resolve(this._connectPromise).then(() => {
107
+ return Promise.all(this._channels.map(channel => channel.close())).catch(function () {// Ignore errors closing channels.
108
+ }).then(() => {
109
+ this._channels = [];
110
+
111
+ if (this._currentConnection) {
112
+ this._currentConnection.removeAllListeners('close');
113
+
114
+ this._currentConnection.close();
115
+ }
116
+
117
+ this._currentConnection = null;
118
+ });
110
119
  });
111
120
  }
112
121
 
@@ -115,12 +124,15 @@ class AmqpConnectionManager extends _events.EventEmitter {
115
124
  }
116
125
 
117
126
  _connect() {
118
- if (this._closed || this._connecting || this.isConnected()) {
127
+ if (this._connectPromise) {
128
+ return this._connectPromise;
129
+ }
130
+
131
+ if (this._closed || this.isConnected()) {
119
132
  return Promise.resolve();
120
133
  }
121
134
 
122
- this._connecting = true;
123
- return Promise.resolve().then(() => {
135
+ this._connectPromise = Promise.resolve().then(() => {
124
136
  if (!this._urls || this._currentUrl >= this._urls.length) {
125
137
  this._currentUrl = 0;
126
138
  return _promiseBreaker.default.callFn(this._findServers, 0, null);
@@ -184,10 +196,12 @@ class AmqpConnectionManager extends _events.EventEmitter {
184
196
  this.emit('disconnect', {
185
197
  err
186
198
  });
187
- (0, _helpers.wait)(this.reconnectTimeInSeconds * 1000).then(() => this._connect()) // `_connect()` should never throw.
199
+ const handle = (0, _helpers.wait)(this.reconnectTimeInSeconds * 1000);
200
+ this._cancelRetriesHandler = handle.cancel;
201
+ handle.promise().then(() => this._connect()) // `_connect()` should never throw.
188
202
  .catch(neverThrows);
189
203
  });
190
- this._connecting = false;
204
+ this._connectPromise = null;
191
205
  this.emit('connect', {
192
206
  connection,
193
207
  url: urlString
@@ -199,13 +213,14 @@ class AmqpConnectionManager extends _events.EventEmitter {
199
213
  err
200
214
  }); // Connection failed...
201
215
 
202
- this._currentConnection = null; // TODO: Probably want to try right away here, especially if there are multiple brokers to try...
216
+ this._currentConnection = null;
217
+ this._connectPromise = null; // TODO: Probably want to try right away here, especially if there are multiple brokers to try...
203
218
 
204
- return (0, _helpers.wait)(this.reconnectTimeInSeconds * 1000).then(() => {
205
- this._connecting = false;
206
- return this._connect();
207
- });
219
+ const handle = (0, _helpers.wait)(this.reconnectTimeInSeconds * 1000);
220
+ this._cancelRetriesHandler = handle.cancel;
221
+ return handle.promise().then(() => this._connect());
208
222
  });
223
+ return this._connectPromise;
209
224
  }
210
225
 
211
226
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/AmqpConnectionManager.js"],"names":["HEARTBEAT_IN_SECONDS","neverThrows","err","setImmediate","Error","message","stack","AmqpConnectionManager","EventEmitter","constructor","urls","options","findServers","_channels","_currentUrl","connectionOptions","heartbeatIntervalInSeconds","reconnectTimeInSeconds","setMaxListeners","_findServers","Promise","resolve","_connect","createChannel","channel","ChannelWrapper","push","once","filter","c","close","_closed","all","map","catch","then","_currentConnection","removeAllListeners","isConnected","_connecting","_urls","length","pb","callFn","Array","isArray","url","urlString","amqpUrl","Object","assign","heartbeat","urlUtils","parse","search","format","amqp","connect","connection","on","reason","emit"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AAEA;;AACA;;AACA;;;;AAEA;AACA,MAAMA,oBAAoB,GAAG,CAA7B;AAEA;;AACA,SAASC,WAAT,GAAuB;AACnB,SAAOC,GAAG,IACNC,YAAY,CAAC,MAAM;AACf,UAAM,IAAIC,KAAJ,CAAW,kDAAiDF,GAAG,CAACG,OAAQ,IAA9D,GACZH,GAAG,CAACI,KADF,CAAN;AAEH,GAHW,CADhB;AAKH,C,CAED;AACA;AACA;AACA;AACA;;;AACe,MAAMC,qBAAN,SAAoCC,oBAApC,CAAiD;AAC5D;;;;;;;;;;;;;;;;;;;;;;;AAuBAC,EAAAA,WAAW,CAACC,IAAD,EAAOC,OAAO,GAAG,EAAjB,EAAqB;AAC5B;;AACA,QAAG,CAACD,IAAD,IAAS,CAACC,OAAO,CAACC,WAArB,EAAkC;AAC9B,YAAM,IAAIR,KAAJ,CAAU,4CAAV,CAAN;AACH;;AACD,SAAKS,SAAL,GAAiB,EAAjB;AAEA,SAAKC,WAAL,GAAmB,CAAnB;AACA,SAAKC,iBAAL,GAAyBJ,OAAO,CAACI,iBAAjC;AAEA,SAAKC,0BAAL,GAAkCL,OAAO,CAACK,0BAAR,IAAsChB,oBAAxE;AACA,SAAKiB,sBAAL,GAA8BN,OAAO,CAACM,sBAAR,IAAkC,KAAKD,0BAArE,C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CAAU,SAAV,EAAqB;AAAEH,UAAAA,UAAF;AAAcZ,UAAAA,GAAG,EAAEC;AAAnB,SAArB;AAEA,eAAO,IAAP;AACH,OA/BM,CAAP;AAgCH,KA3EM,EA4ENb,KA5EM,CA4EAhC,GAAG,IAAI;AACV,WAAK2D,IAAL,CAAU,YAAV,EAAwB;AAAE3D,QAAAA;AAAF,OAAxB,EADU,CAGV;;AACA,WAAKkC,kBAAL,GAA0B,IAA1B,CAJU,CAMV;;AACA,aAAO,mBAAK,KAAKnB,sBAAL,GAA8B,IAAnC,EACNkB,IADM,CACD,MAAM;AACR,aAAKI,WAAL,GAAmB,KAAnB;AACA,eAAO,KAAKjB,QAAL,EAAP;AACH,OAJM,CAAP;AAKH,KAxFM,CAAP;AAyFH;;AA7K2D","sourcesContent":["import { EventEmitter } from 'events';\nimport amqp from 'amqplib';\nimport urlUtils from 'url';\n\nimport ChannelWrapper from './ChannelWrapper';\nimport { wait } from './helpers';\nimport pb from 'promise-breaker';\n\n// Default heartbeat time.\nconst HEARTBEAT_IN_SECONDS = 5;\n\n/* istanbul ignore next */\nfunction neverThrows() {\n return err =>\n setImmediate(() => {\n throw new Error(`AmqpConnectionManager - should never get here: ${err.message}\\n` +\n err.stack);\n });\n}\n\n//\n// Events:\n// * `connect({connection, url})` - Emitted whenever we connect to a broker.\n// * `disconnect({err})` - Emitted whenever we disconnect from a broker.\n//\nexport default class AmqpConnectionManager extends EventEmitter {\n /**\n * Create a new AmqplibConnectionManager.\n *\n * @param {(string|Object)[]} urls - An array of brokers to connect to.\n * Takes url strings or objects {url: string, connectionOptions?: object}\n * If present, a broker's [connectionOptions] will be used instead\n * of [options.connectionOptions] when passed to the amqplib connect method.\n * AmqplibConnectionManager will round-robin between them whenever it\n * needs to create a new connection.\n * @param {Object} [options={}] -\n * @param {number} [options.heartbeatIntervalInSeconds=5] - The interval,\n * in seconds, to send heartbeats.\n * @param {number} [options.reconnectTimeInSeconds] - The time to wait\n * before trying to reconnect. If not specified, defaults to\n * `heartbeatIntervalInSeconds`.\n * @param {Object} [options.connectionOptions] - Passed to the amqplib\n * connect method.\n * @param {function} [options.findServers] - A `fn(callback)` or a `fn()`\n * which returns a Promise. This should resolve to one or more servers\n * to connect to, either a single URL or an array of URLs. This is handy\n * when you're using a service discovery mechanism such as Consul or etcd.\n * Note that if this is supplied, then `urls` is ignored.\n */\n constructor(urls, options = {}) {\n super();\n if(!urls && !options.findServers) {\n throw new Error(\"Must supply either `urls` or `findServers`\");\n }\n this._channels = [];\n\n this._currentUrl = 0;\n this.connectionOptions = options.connectionOptions;\n\n this.heartbeatIntervalInSeconds = options.heartbeatIntervalInSeconds || HEARTBEAT_IN_SECONDS;\n this.reconnectTimeInSeconds = options.reconnectTimeInSeconds || this.heartbeatIntervalInSeconds;\n\n // There will be one listener per channel, and there could be a lot of channels, so disable warnings from node.\n this.setMaxListeners(0);\n\n this._findServers = options.findServers || (() => Promise.resolve(urls));\n\n this._connect();\n }\n\n // `options` here are any options that can be passed to ChannelWrapper.\n createChannel(options = {}) {\n const channel = new ChannelWrapper(this, options);\n this._channels.push(channel);\n channel.once('close', () => {\n this._channels = this._channels.filter(c => c !== channel);\n });\n return channel;\n }\n\n close() {\n if(this._closed) { return Promise.resolve(); }\n this._closed = true;\n\n return Promise.all(this._channels.map(channel => channel.close()))\n .catch(function() {\n // Ignore errors closing channels.\n })\n .then(() => {\n this._channels = [];\n if(this._currentConnection) {\n this._currentConnection.removeAllListeners('close');\n this._currentConnection.close();\n }\n this._currentConnection = null;\n });\n }\n\n isConnected() {\n return !!this._currentConnection;\n }\n\n _connect() {\n if(this._closed || this._connecting || this.isConnected()) {\n return Promise.resolve();\n }\n\n this._connecting = true;\n\n return Promise.resolve()\n .then(() => {\n if(!this._urls || (this._currentUrl >= this._urls.length)) {\n this._currentUrl = 0;\n return pb.callFn(this._findServers, 0, null);\n } else {\n return this._urls;\n }\n })\n .then(urls => {\n if(urls && !Array.isArray(urls)) { urls = [urls]; }\n this._urls = urls;\n\n if(!urls || (urls.length === 0)) {\n throw new Error('amqp-connection-manager: No servers found');\n }\n\n // Round robin between brokers\n const url = urls[this._currentUrl];\n this._currentUrl++;\n\n // url can be a string or object {url: string, connectionOptions?: object}\n const urlString = url.url || url;\n const connectionOptions = url.connectionOptions || this.connectionOptions;\n\n let amqpUrl = null;\n\n if(typeof urlString === \"object\") {\n amqpUrl = Object.assign({}, url);\n if(!amqpUrl.heartbeat) {\n amqpUrl.heartbeat = this.heartbeatIntervalInSeconds;\n }\n }else {\n amqpUrl = urlUtils.parse(urlString);\n if(amqpUrl.search) {\n amqpUrl.search += `&heartbeat=${this.heartbeatIntervalInSeconds}`;\n } else {\n amqpUrl.search = `?heartbeat=${this.heartbeatIntervalInSeconds}`;\n }\n amqpUrl = urlUtils.format(amqpUrl);\n }\n\n\n return amqp.connect(amqpUrl, connectionOptions)\n .then(connection => {\n this._currentConnection = connection;\n\n //emit 'blocked' when RabbitMQ server decides to block the connection (resources running low)\n connection.on('blocked', reason => this.emit('blocked', { reason }));\n\n connection.on('unblocked', () => this.emit('unblocked'));\n\n connection.on('error', (/* err */) => {\n // if this event was emitted, then the connection was already closed,\n // so no need to call #close here\n // also, 'close' is emitted after 'error',\n // so no need for work already done in 'close' handler\n });\n\n // Reconnect if the connection closes\n connection.on('close', err => {\n this._currentConnection = null;\n this.emit('disconnect', { err });\n\n wait(this.reconnectTimeInSeconds * 1000)\n .then(() => this._connect())\n // `_connect()` should never throw.\n .catch(neverThrows);\n });\n\n this._connecting = false;\n this.emit('connect', { connection, url: urlString });\n\n return null;\n });\n })\n .catch(err => {\n this.emit('disconnect', { err });\n\n // Connection failed...\n this._currentConnection = null;\n\n // TODO: Probably want to try right away here, especially if there are multiple brokers to try...\n return wait(this.reconnectTimeInSeconds * 1000)\n .then(() => {\n this._connecting = false;\n return this._connect();\n });\n });\n }\n}\n"],"file":"AmqpConnectionManager.js"}
1
+ {"version":3,"sources":["../src/AmqpConnectionManager.js"],"names":["HEARTBEAT_IN_SECONDS","neverThrows","err","setImmediate","Error","message","stack","AmqpConnectionManager","EventEmitter","constructor","urls","options","findServers","_channels","_currentUrl","connectionOptions","heartbeatIntervalInSeconds","reconnectTimeInSeconds","setMaxListeners","_findServers","Promise","resolve","_connect","createChannel","channel","ChannelWrapper","push","once","filter","c","close","_closed","_cancelRetriesHandler","_connectPromise","then","all","map","catch","_currentConnection","removeAllListeners","isConnected","_urls","length","pb","callFn","Array","isArray","url","urlString","amqpUrl","Object","assign","heartbeat","urlUtils","parse","search","format","amqp","connect","connection","on","reason","emit","handle","cancel","promise"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AAEA;;AACA;;AACA;;;;AAEA;AACA,MAAMA,oBAAoB,GAAG,CAA7B;AAEA;;AACA,SAASC,WAAT,GAAuB;AACnB,SAAOC,GAAG,IACNC,YAAY,CAAC,MAAM;AACf,UAAM,IAAIC,KAAJ,CAAW,kDAAiDF,GAAG,CAACG,OAAQ,IAA9D,GACZH,GAAG,CAACI,KADF,CAAN;AAEH,GAHW,CADhB;AAKH,C,CAED;AACA;AACA;AACA;AACA;;;AACe,MAAMC,qBAAN,SAAoCC,oBAApC,CAAiD;AAC5D;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACIC,EAAAA,WAAW,CAACC,IAAD,EAAOC,OAAO,GAAG,EAAjB,EAAqB;AAC5B;;AACA,QAAG,CAACD,IAAD,IAAS,CAACC,OAAO,CAACC,WAArB,EAAkC;AAC9B,YAAM,IAAIR,KAAJ,CAAU,4CAAV,CAAN;AACH;;AACD,SAAKS,SAAL,GAAiB,EAAjB;AAEA,SAAKC,WAAL,GAAmB,CAAnB;AACA,SAAKC,iBAAL,GAAyBJ,OAAO,CAACI,iBAAjC;AAEA,SAAKC,0BAAL,GAAkCL,OAAO,CAACK,0BAAR,IAAsChB,oBAAxE;AACA,SAAKiB,sBAAL,GAA8BN,OAAO,C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;AACA,eAAKwB,IAAL,CAAU,YAAV,EAAwB;AAAE5D,YAAAA;AAAF,WAAxB;AAEA,gBAAM6D,MAAM,GAAG,mBAAK,KAAK9C,sBAAL,GAA8B,IAAnC,CAAf;AACA,eAAKe,qBAAL,GAA6B+B,MAAM,CAACC,MAApC;AAEAD,UAAAA,MAAM,CACHE,OADH,GAEG/B,IAFH,CAEQ,MAAM,KAAKZ,QAAL,EAFd,EAGE;AAHF,WAIGe,KAJH,CAISpC,WAJT;AAKH,SAZD;AAcA,aAAKgC,eAAL,GAAuB,IAAvB;AACA,aAAK6B,IAAL,CAAU,SAAV,EAAqB;AAAEH,UAAAA,UAAF;AAAcZ,UAAAA,GAAG,EAAEC;AAAnB,SAArB;AAEA,eAAO,IAAP;AACH,OAnCM,CAAP;AAoCH,KA/EsB,EAgFtBX,KAhFsB,CAgFhBnC,GAAG,IAAI;AACV,WAAK4D,IAAL,CAAU,YAAV,EAAwB;AAAE5D,QAAAA;AAAF,OAAxB,EADU,CAGV;;AACA,WAAKoC,kBAAL,GAA0B,IAA1B;AACA,WAAKL,eAAL,GAAuB,IAAvB,CALU,CAOV;;AACA,YAAM8B,MAAM,GAAG,mBAAK,KAAK9C,sBAAL,GAA8B,IAAnC,CAAf;AACA,WAAKe,qBAAL,GAA6B+B,MAAM,CAACC,MAApC;AAEA,aAAOD,MAAM,CAACE,OAAP,GAAiB/B,IAAjB,CAAsB,MAAM,KAAKZ,QAAL,EAA5B,CAAP;AACH,KA5FsB,CAAvB;AA8FA,WAAO,KAAKW,eAAZ;AACH;;AA5L2D","sourcesContent":["import { EventEmitter } from 'events';\nimport amqp from 'amqplib';\nimport urlUtils from 'url';\n\nimport ChannelWrapper from './ChannelWrapper';\nimport { wait } from './helpers';\nimport pb from 'promise-breaker';\n\n// Default heartbeat time.\nconst HEARTBEAT_IN_SECONDS = 5;\n\n/* istanbul ignore next */\nfunction neverThrows() {\n return err =>\n setImmediate(() => {\n throw new Error(`AmqpConnectionManager - should never get here: ${err.message}\\n` +\n err.stack);\n });\n}\n\n//\n// Events:\n// * `connect({connection, url})` - Emitted whenever we connect to a broker.\n// * `disconnect({err})` - Emitted whenever we disconnect from a broker.\n//\nexport default class AmqpConnectionManager extends EventEmitter {\n /**\n * Create a new AmqplibConnectionManager.\n *\n * @param {(string|Object)[]} urls - An array of brokers to connect to.\n * Takes url strings or objects {url: string, connectionOptions?: object}\n * If present, a broker's [connectionOptions] will be used instead\n * of [options.connectionOptions] when passed to the amqplib connect method.\n * AmqplibConnectionManager will round-robin between them whenever it\n * needs to create a new connection.\n * @param {Object} [options={}] -\n * @param {number} [options.heartbeatIntervalInSeconds=5] - The interval,\n * in seconds, to send heartbeats.\n * @param {number} [options.reconnectTimeInSeconds] - The time to wait\n * before trying to reconnect. If not specified, defaults to\n * `heartbeatIntervalInSeconds`.\n * @param {Object} [options.connectionOptions] - Passed to the amqplib\n * connect method.\n * @param {function} [options.findServers] - A `fn(callback)` or a `fn()`\n * which returns a Promise. This should resolve to one or more servers\n * to connect to, either a single URL or an array of URLs. This is handy\n * when you're using a service discovery mechanism such as Consul or etcd.\n * Note that if this is supplied, then `urls` is ignored.\n */\n constructor(urls, options = {}) {\n super();\n if(!urls && !options.findServers) {\n throw new Error(\"Must supply either `urls` or `findServers`\");\n }\n this._channels = [];\n\n this._currentUrl = 0;\n this.connectionOptions = options.connectionOptions;\n\n this.heartbeatIntervalInSeconds = options.heartbeatIntervalInSeconds || HEARTBEAT_IN_SECONDS;\n this.reconnectTimeInSeconds = options.reconnectTimeInSeconds || this.heartbeatIntervalInSeconds;\n\n // There will be one listener per channel, and there could be a lot of channels, so disable warnings from node.\n this.setMaxListeners(0);\n\n this._findServers = options.findServers || (() => Promise.resolve(urls));\n\n this._connect();\n }\n\n // `options` here are any options that can be passed to ChannelWrapper.\n createChannel(options = {}) {\n const channel = new ChannelWrapper(this, options);\n this._channels.push(channel);\n channel.once('close', () => {\n this._channels = this._channels.filter(c => c !== channel);\n });\n return channel;\n }\n\n close() {\n if(this._closed) { return Promise.resolve(); }\n this._closed = true;\n\n if(this._cancelRetriesHandler) { \n this._cancelRetriesHandler();\n this._cancelRetriesHandler = null;\n }\n\n return Promise.resolve(this._connectPromise).then(() => {\n return Promise.all(this._channels.map(channel => channel.close()))\n .catch(function() {\n // Ignore errors closing channels.\n })\n .then(() => {\n this._channels = [];\n if(this._currentConnection) {\n this._currentConnection.removeAllListeners('close');\n this._currentConnection.close();\n }\n this._currentConnection = null;\n });\n });\n }\n\n isConnected() {\n return !!this._currentConnection;\n }\n\n _connect() {\n if (this._connectPromise) {\n return this._connectPromise;\n }\n\n if(this._closed || this.isConnected()) {\n return Promise.resolve();\n }\n\n this._connectPromise = Promise.resolve()\n .then(() => {\n if(!this._urls || (this._currentUrl >= this._urls.length)) {\n this._currentUrl = 0;\n return pb.callFn(this._findServers, 0, null);\n } else {\n return this._urls;\n }\n })\n .then(urls => {\n if(urls && !Array.isArray(urls)) { urls = [urls]; }\n this._urls = urls;\n\n if(!urls || (urls.length === 0)) {\n throw new Error('amqp-connection-manager: No servers found');\n }\n\n // Round robin between brokers\n const url = urls[this._currentUrl];\n this._currentUrl++;\n\n // url can be a string or object {url: string, connectionOptions?: object}\n const urlString = url.url || url;\n const connectionOptions = url.connectionOptions || this.connectionOptions;\n\n let amqpUrl = null;\n\n if(typeof urlString === \"object\") {\n amqpUrl = Object.assign({}, url);\n if(!amqpUrl.heartbeat) {\n amqpUrl.heartbeat = this.heartbeatIntervalInSeconds;\n }\n }else {\n amqpUrl = urlUtils.parse(urlString);\n if(amqpUrl.search) {\n amqpUrl.search += `&heartbeat=${this.heartbeatIntervalInSeconds}`;\n } else {\n amqpUrl.search = `?heartbeat=${this.heartbeatIntervalInSeconds}`;\n }\n amqpUrl = urlUtils.format(amqpUrl);\n }\n\n\n return amqp.connect(amqpUrl, connectionOptions)\n .then(connection => {\n this._currentConnection = connection;\n\n //emit 'blocked' when RabbitMQ server decides to block the connection (resources running low)\n connection.on('blocked', reason => this.emit('blocked', { reason }));\n\n connection.on('unblocked', () => this.emit('unblocked'));\n\n connection.on('error', (/* err */) => {\n // if this event was emitted, then the connection was already closed,\n // so no need to call #close here\n // also, 'close' is emitted after 'error',\n // so no need for work already done in 'close' handler\n });\n\n // Reconnect if the connection closes\n connection.on('close', err => {\n this._currentConnection = null;\n this.emit('disconnect', { err });\n\n const handle = wait(this.reconnectTimeInSeconds * 1000);\n this._cancelRetriesHandler = handle.cancel;\n\n handle\n .promise()\n .then(() => this._connect())\n // `_connect()` should never throw.\n .catch(neverThrows);\n });\n\n this._connectPromise = null;\n this.emit('connect', { connection, url: urlString });\n\n return null;\n });\n })\n .catch(err => {\n this.emit('disconnect', { err });\n\n // Connection failed...\n this._currentConnection = null;\n this._connectPromise = null;\n\n // TODO: Probably want to try right away here, especially if there are multiple brokers to try...\n const handle = wait(this.reconnectTimeInSeconds * 1000);\n this._cancelRetriesHandler = handle.cancel;\n\n return handle.promise().then(() => this._connect());\n });\n\n return this._connectPromise;\n }\n}\n"],"file":"AmqpConnectionManager.js"}
@@ -62,7 +62,7 @@ class ChannelWrapper extends _events.EventEmitter {
62
62
  *
63
63
  * @param {function} setup - the setup function to remove.
64
64
  * @param {function} [teardown] - `function(channel, [cb])` to run to tear
65
- * down the chanel.
65
+ * down the channel.
66
66
  * @param {function} [done] - Optional callback.
67
67
  * @returns {void | Promise} - Resolves when complete.
68
68
  */
@@ -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) {
@@ -362,19 +384,19 @@ class ChannelWrapper extends _events.EventEmitter {
362
384
 
363
385
  return sendPromise;
364
386
  }).then(result => {
365
- this._unconfirmedMessages.shift();
366
-
387
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
367
388
  message.resolve(result);
368
389
  }, err => {
369
- if (!this._channel) {
390
+ if (!this._channel && this._canWaitReconnection()) {
370
391
  // Tried to write to a closed channel. Leave the message in the queue and we'll try again when we
371
392
  // reconnect.
372
- this._messages.unshift(this._unconfirmedMessages.shift());
393
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
394
+
395
+ this._messages.unshift(message);
373
396
  } else {
374
397
  // Something went wrong trying to send this message - could be JSON.stringify failed, could be the
375
398
  // broker rejected the message. Either way, reject it back
376
- this._unconfirmedMessages.shift();
377
-
399
+ removeUnconfirmedMessage(this._unconfirmedMessages, message);
378
400
  message.reject(err);
379
401
  }
380
402
  }).catch(
@@ -419,9 +441,40 @@ class ChannelWrapper extends _events.EventEmitter {
419
441
 
420
442
  assertQueue() {
421
443
  return this._channel && this._channel.assertQueue.apply(this._channel, arguments);
444
+ } // Send a `bindQueue` to the underlying channel.
445
+
446
+
447
+ bindQueue() {
448
+ return this._channel && this._channel.bindQueue.apply(this._channel, arguments);
449
+ } // Send a `deleteQueue` to the underlying channel.
450
+
451
+
452
+ deleteQueue() {
453
+ return this._channel && this._channel.deleteQueue.apply(this._channel, arguments);
454
+ } // Send a `assertExchange` to the underlying channel.
455
+
456
+
457
+ assertExchange() {
458
+ return this._channel && this._channel.assertExchange.apply(this._channel, arguments);
459
+ } // Send a `get` to the underlying channel.
460
+
461
+
462
+ get() {
463
+ return this._channel && this._channel.get.apply(this._channel, arguments);
422
464
  }
423
465
 
424
466
  }
425
467
 
426
468
  exports.default = ChannelWrapper;
469
+
470
+ function removeUnconfirmedMessage(arr, message) {
471
+ const toRemove = arr.indexOf(message);
472
+
473
+ if (toRemove === -1) {
474
+ throw new Error(`Message is not in _unconfirmedMessages!`);
475
+ }
476
+
477
+ const removed = arr.splice(toRemove, 1);
478
+ return removed[0];
479
+ }
427
480
  //# 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"],"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,GAC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N,WAAO,KAAKzE,QAAL,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;;AA9ZoD","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 chanel.\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"],"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","sendPromise","result","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,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;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACIC,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,CAAQG,QAAR,EAAkB,IAAlB,EAAwB,KAAKJ,QAA7B,CADM,GAENE,SAHC,CAAP;AAKH,KARM,C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C,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(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 // 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.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(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()\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 // 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 ? 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 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( /* 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 `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}"],"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;AAC7B,MAAIC,aAAJ;;AAEA,QAAMC,OAAO,GAAG,MAAM;AACpB,WAAO,IAAIC,OAAJ,CAAY,UAAUC,OAAV,EAAmB;AACpCH,MAAAA,aAAa,GAAGI,UAAU,CAACD,OAAD,EAAUJ,QAAV,CAA1B;AACA,aAAOC,aAAP;AACD,KAHM,CAAP;AAID,GALD;;AAOA,SAAO;AAAEC,IAAAA,OAAF;AAAWI,IAAAA,MAAM,EAAE,MAAMC,YAAY,CAACN,aAAD;AAArC,GAAP;AACD","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"}