@sera4/essentia 1.1.8 → 1.1.11

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.
@@ -4,6 +4,30 @@ import jsonStringify from "fast-safe-stringify";
4
4
  const colorizer = winston.format.colorize();
5
5
  import "winston-logstash";
6
6
 
7
+ // IETF RFC5424:
8
+ // Severity of all levels is assumed to be numerically ascending from most important to least important.
9
+ const levels = {
10
+ error: 0,
11
+ warn: 1,
12
+ info: 2,
13
+ debug: 3,
14
+ trace: 4,
15
+ };
16
+
17
+ // These colors are not used, however if colors are not defined for custom levels
18
+ // then winston will throw an exception.
19
+ winston.addColors({
20
+ trace: 'white'
21
+ });
22
+
23
+ const defaultLevel = process.env.NODE_ENV === 'production' ? 'info' : 'debug';
24
+
25
+ // These colors are not used, however if colors are not defined for custom levels
26
+ // then winston will throw an exception.
27
+ winston.addColors({
28
+ trace: 'white'
29
+ });
30
+
7
31
  const devFormat = {
8
32
  transform(info) {
9
33
  const { message } = info;
@@ -16,11 +40,13 @@ const devFormat = {
16
40
  };
17
41
 
18
42
  const defaultTransport = new winston.transports.Console({
19
- format: devFormat
43
+ format: devFormat,
44
+ level: 'trace'
20
45
  });
21
46
 
22
47
  const logger = winston.createLogger({
23
- level: 'debug',
48
+ levels: levels,
49
+ level: defaultLevel,
24
50
  defaultMeta: { },
25
51
  transports: [defaultTransport]
26
52
  });
@@ -31,15 +57,13 @@ class S4Logger {
31
57
  return;
32
58
  }
33
59
 
34
- if (options.level && ["debug", "info", "error", "warn"].indexOf(options.level.toLowerCase())) {
35
- logger.level = options.level;
36
- }
60
+ this.setLevel(options.level);
37
61
 
38
62
  logger.defaultMeta.service = options.service;
39
63
  switch(options.format.toLowerCase()) {
40
64
  case "logstash":
41
- defaultTransport.format = winston.format.logstash();
42
- break;
65
+ defaultTransport.format = winston.format.logstash();
66
+ break;
43
67
  case "json":
44
68
  defaultTransport.format = winston.format.json();
45
69
  break;
@@ -50,7 +74,7 @@ class S4Logger {
50
74
  }
51
75
 
52
76
  setLevel(level) {
53
- if (level && ["debug", "info", "error", "warn"].indexOf(level.toLowerCase())) {
77
+ if (level && ["trace", "debug", "info", "error", "warn"].indexOf(level.toLowerCase())) {
54
78
  logger.level = level;
55
79
  }
56
80
  }
@@ -67,6 +91,10 @@ class S4Logger {
67
91
  });
68
92
  }
69
93
 
94
+ trace(...args) {
95
+ logger.trace(util.format(...args));
96
+ }
97
+
70
98
  debug(...args) {
71
99
  logger.debug(util.format(...args));
72
100
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sera4/essentia",
3
- "version": "1.1.8",
3
+ "version": "1.1.11",
4
4
  "description": "A library of utilities for Teleporte Web Services",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -28,7 +28,7 @@
28
28
  "sinon": "^5.1.1"
29
29
  },
30
30
  "dependencies": {
31
- "amqplib": "^0.7.1",
31
+ "amqplib": "^0.8.0",
32
32
  "async": "^2.6.3",
33
33
  "axios": "^0.21.1",
34
34
  "fast-safe-stringify": "^2.0.7",
package/package.tar.gz CHANGED
Binary file
package/queue/index.js CHANGED
@@ -29,6 +29,7 @@ class S4Queue {
29
29
  */
30
30
  async testConnection() {
31
31
  if (!this.isConnected()) {
32
+ this.connectionTestChannel = null;
32
33
  throw("queue service not connected")
33
34
  }
34
35
 
@@ -72,12 +73,16 @@ class S4Queue {
72
73
  amqp.connect(options.connectionUrl, socketOptions, (err, conn) => {
73
74
 
74
75
  if (err) {
75
- return reject(err);
76
+ logger.error("Error while connecting", err)
77
+ logger.error("Attempting again in", this.retry, "seconds");
78
+ return setTimeout(() => this.openConnection(options), this.retry * 1000);
76
79
  }
77
80
 
78
81
  this.connection = conn;
79
82
  if (!this.connection) {
80
83
  return reject(new Error("Failed to obtain connection"));
84
+ } else {
85
+ this.updatePubsAndSubsConnectionRef(conn);
81
86
  }
82
87
 
83
88
  this.connection.on("error", (err) => {
@@ -91,8 +96,8 @@ class S4Queue {
91
96
  logger.error("connection closed");
92
97
  this.connection = null;
93
98
  if (err) {
94
- logger.debug("connection closed due to error:", err);
95
- logger.debug("Reconnecting in", this.retry, "seconds");
99
+ logger.error("connection closed due to error:", err);
100
+ logger.error("Reconnecting in", this.retry, "seconds");
96
101
  setTimeout(() => this.openConnection(options), this.retry * 1000);
97
102
  } else {
98
103
  // If there was no error, it is us who closed
@@ -171,6 +176,22 @@ class S4Queue {
171
176
  this.pubs[name] = p;
172
177
  }
173
178
 
179
+ /**
180
+ * Registers a new fanout publisher on the given exchange.
181
+ * If exchange doesn't exist, one will be created.
182
+ * @param {String} exchange the name of the exchange on AMQP service.
183
+ */
184
+ async registerFanoutPublisher(exchange) {
185
+ const name = exchange;
186
+ if (Object.keys(this.pubs).includes(name)) {
187
+ throw new Error(`Publisher ${name} already registered`);
188
+ }
189
+
190
+ const p = new Publisher(exchange, 'fanout', true, name);
191
+ await p.init(this.connection);
192
+ this.pubs[name] = p;
193
+ }
194
+
174
195
  /**
175
196
  * Registers a new direct subscriber on a given exchange and queue.
176
197
  * If exchange and queue don't exists, they'll be created
@@ -273,6 +294,26 @@ class S4Queue {
273
294
  return await p.publish({key: topic, content});
274
295
  }
275
296
 
297
+ /**
298
+ * Binds an exchange to a queue
299
+ * @param {String} exchange the name of the exchange.
300
+ * @param {String} queue the name of the queue.
301
+ * @param {pattern} (optional) pattern for routing key
302
+ */
303
+ async bindQueueToExchange(exchange, queue, pattern) {
304
+ const p = this.pubs[exchange];
305
+
306
+ if (!p) {
307
+ throw(new Error(`No PUB for ${exchange} found`));
308
+ }
309
+
310
+ if (!queue) {
311
+ throw(new Error(`Binding a queue requires a queue name`));
312
+ }
313
+
314
+ return await p.bindQueue(queue, pattern)
315
+ }
316
+
276
317
  /**
277
318
  * Adds a listener for a specific key.
278
319
  * If a subscriber that was regitered was found
@@ -289,6 +330,29 @@ class S4Queue {
289
330
  }
290
331
  });
291
332
  }
333
+
334
+ /**
335
+ * Updates the connection reference to all the previously
336
+ * registered publishers and subscribers.
337
+ * After we successfully establish a connection and register pubs/subs,
338
+ * it's possible for the connection to break. This object will try
339
+ * to re-establish a new connection every 3 seconds (or whatever configuration is set)
340
+ * and if a new connection is established, we need to pass that connection to
341
+ * all our pubs/subs, otherwise they'll be operating with old/stale references
342
+ * @param {Object} connRef a new connection reference to the AMQP service
343
+ */
344
+ updatePubsAndSubsConnectionRef(connRef) {
345
+ Object.keys(this.pubs).forEach(k => {
346
+ logger.debug(`Updating publisher ${k} with a new connection object`);
347
+ const p = this.pubs[k];
348
+ p.init(connRef);
349
+ });
350
+ Object.keys(this.subs).forEach(k => {
351
+ logger.debug(`Updating subscriber ${k} with a new connection object`);
352
+ const s = this.subs[k];
353
+ s.init(connRef);
354
+ });
355
+ }
292
356
  }
293
357
 
294
358
  const queue = new S4Queue();
@@ -5,9 +5,7 @@ import uuidv4 from "uuid/v4.js";
5
5
  * A publisher for AMQP service
6
6
  */
7
7
  export class Publisher {
8
-
9
8
  /**
10
- *
11
9
  * @param {String} exchange AMQP exchange name.
12
10
  * @param {String} type direct|fanout| etc (supported types by RabbitMQ).
13
11
  * @param {boolean} durable true if the messages should persist service restarts.
@@ -81,4 +79,8 @@ export class Publisher {
81
79
 
82
80
  return parcel.tracking_id;
83
81
  }
82
+
83
+ async bindQueue(queue, pattern, args) {
84
+ await this.channel.bindQueue(queue, this.exchange, pattern, args)
85
+ }
84
86
  }
@@ -7,9 +7,8 @@ const { omitBy, isNil } = lodash;
7
7
  /* A class which safely wraps an axios connection in order to pass the current user through to
8
8
  * the next service. Useful when one of our microservices requires auth as either an admin (sera4tal)
9
9
  * or as the end user (example: DELETE /auth/sessions/:id
10
- *
11
- * similar to proxy however this isn't a proxy, it's a full out new call that we can manage
12
10
  *
11
+ * Similar to proxy however this isn't a proxy, it's a full out new call that we can manage
13
12
  * each method requires a res.locals from a pre-authd session
14
13
  */
15
14
  class SafeProxy {