@sellout/service 0.0.1

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.
Files changed (67) hide show
  1. package/.dist/BaseService.d.ts +22 -0
  2. package/.dist/BaseService.js +77 -0
  3. package/.dist/BaseService.js.map +1 -0
  4. package/.dist/ConsoleLogManager.d.ts +9 -0
  5. package/.dist/ConsoleLogManager.js +18 -0
  6. package/.dist/ConsoleLogManager.js.map +1 -0
  7. package/.dist/MongoConnectionManager.d.ts +9 -0
  8. package/.dist/MongoConnectionManager.js +52 -0
  9. package/.dist/MongoConnectionManager.js.map +1 -0
  10. package/.dist/NatsConnectionManager.d.ts +115 -0
  11. package/.dist/NatsConnectionManager.js +215 -0
  12. package/.dist/NatsConnectionManager.js.map +1 -0
  13. package/.dist/PbAsyncMessageHandler.d.ts +15 -0
  14. package/.dist/PbAsyncMessageHandler.js +26 -0
  15. package/.dist/PbAsyncMessageHandler.js.map +1 -0
  16. package/.dist/PbBroadcastProxy.d.ts +25 -0
  17. package/.dist/PbBroadcastProxy.js +41 -0
  18. package/.dist/PbBroadcastProxy.js.map +1 -0
  19. package/.dist/PbMessageHandler.d.ts +26 -0
  20. package/.dist/PbMessageHandler.js +46 -0
  21. package/.dist/PbMessageHandler.js.map +1 -0
  22. package/.dist/PbServiceProxy.d.ts +38 -0
  23. package/.dist/PbServiceProxy.js +64 -0
  24. package/.dist/PbServiceProxy.js.map +1 -0
  25. package/.dist/Segment.d.ts +12 -0
  26. package/.dist/Segment.js +34 -0
  27. package/.dist/Segment.js.map +1 -0
  28. package/.dist/Tracer.d.ts +22 -0
  29. package/.dist/Tracer.js +49 -0
  30. package/.dist/Tracer.js.map +1 -0
  31. package/.dist/TracerExpress.d.ts +1 -0
  32. package/.dist/TracerExpress.js +42 -0
  33. package/.dist/TracerExpress.js.map +1 -0
  34. package/.dist/build/tsconfig.json +32 -0
  35. package/.dist/build/tslint.json +17 -0
  36. package/.dist/env.d.ts +5 -0
  37. package/.dist/env.js +8 -0
  38. package/.dist/env.js.map +1 -0
  39. package/.dist/interfaces.d.ts +31 -0
  40. package/.dist/interfaces.js +3 -0
  41. package/.dist/interfaces.js.map +1 -0
  42. package/.dist/joiToErrors.d.ts +3 -0
  43. package/.dist/joiToErrors.js +43 -0
  44. package/.dist/joiToErrors.js.map +1 -0
  45. package/.dist/schemas.d.ts +0 -0
  46. package/.dist/schemas.js +1 -0
  47. package/.dist/schemas.js.map +1 -0
  48. package/package.json +34 -0
  49. package/src/BaseService.ts +98 -0
  50. package/src/ConsoleLogManager.ts +23 -0
  51. package/src/MongoConnectionManager.ts +49 -0
  52. package/src/NatsConnectionManager.ts +268 -0
  53. package/src/PbAsyncMessageHandler.ts +28 -0
  54. package/src/PbBroadcastProxy.ts +41 -0
  55. package/src/PbMessageHandler.ts +49 -0
  56. package/src/PbServiceProxy.ts +66 -0
  57. package/src/Segment.ts +35 -0
  58. package/src/Tracer.ts +55 -0
  59. package/src/TracerExpress.ts +36 -0
  60. package/src/build/tsconfig.json +32 -0
  61. package/src/build/tslint.json +17 -0
  62. package/src/env.ts +5 -0
  63. package/src/interfaces.ts +47 -0
  64. package/src/joiToErrors.ts +48 -0
  65. package/src/schemas.ts +0 -0
  66. package/tsconfig.json +28 -0
  67. package/tslint.json +21 -0
@@ -0,0 +1,22 @@
1
+ import { IConnectionManager, ILogManager, IServiceOpts } from "./interfaces";
2
+ import Segment from "./Segment";
3
+ /**
4
+ * Provides the abstract class for all service implementations.
5
+ */
6
+ declare class BaseService {
7
+ opts: IServiceOpts;
8
+ serviceName: string;
9
+ connectionMgr: IConnectionManager;
10
+ logger: ILogManager;
11
+ storage: any;
12
+ segment: Segment;
13
+ collectDefaultMetrics: any;
14
+ constructor(opts: IServiceOpts);
15
+ isReady(): boolean;
16
+ /**
17
+ * Register message listeners here.
18
+ */
19
+ register(): void;
20
+ run(): void;
21
+ }
22
+ export default BaseService;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Prometheus = require("prom-client");
4
+ const express = require("express");
5
+ const env_1 = require("./env");
6
+ const Sentry = require("@sentry/node");
7
+ const Segment_1 = require("./Segment");
8
+ /**
9
+ * Provides the abstract class for all service implementations.
10
+ */
11
+ class BaseService {
12
+ constructor(opts) {
13
+ this.opts = opts;
14
+ this.connectionMgr = this.opts.connectionMgr;
15
+ this.logger = this.opts.logManager;
16
+ this.serviceName = this.opts.serviceName;
17
+ this.storage = this.opts.storageManager;
18
+ this.segment = new Segment_1.default(env_1.SEGMENT_IO_WRITE_KEY, this.logger);
19
+ /**
20
+ * Initialize Sentry
21
+ */
22
+ if (env_1.SENTRY_DSN) {
23
+ this.logger.info("Sentry - Initializing with environment ${NODE_ENV}...");
24
+ Sentry.init({
25
+ dsn: env_1.SENTRY_DSN,
26
+ environment: env_1.NODE_ENV,
27
+ });
28
+ }
29
+ else {
30
+ this.logger.warn("Sentry - No DSN supplied, skipping initialization...");
31
+ }
32
+ // Enable/Disable Prometheus
33
+ if (!env_1.DISABLE_PROMETHEUS) {
34
+ // set up Prometheus client metrics gathering
35
+ const collectDefaultMetrics = Prometheus.collectDefaultMetrics;
36
+ // collectDefaultMetrics({ timeout: 5000 });
37
+ collectDefaultMetrics();
38
+ // initialize Express app
39
+ const app = express();
40
+ const metricsPort = 5499; // todo: parameterize this
41
+ // Metrics endpoint
42
+ app.get('/metrics', (req, res) => {
43
+ res.set('Content-Type', Prometheus.register.contentType);
44
+ res.end(Prometheus.register.metrics());
45
+ });
46
+ app.get('/readiness', (req, res) => {
47
+ if (this.isReady()) {
48
+ res.status(200).send('OK');
49
+ }
50
+ else {
51
+ res.status(500).send('Not ready');
52
+ }
53
+ });
54
+ // as long as the event loop is running this should run
55
+ app.get('/liveness', (req, res) => {
56
+ res.status(200).send('OK');
57
+ });
58
+ // listen for metrics requests
59
+ app.listen(metricsPort, () => this.logger.info(`Service '${this.serviceName}' listening for metrics requests on port ${metricsPort}.`));
60
+ }
61
+ }
62
+ // override to have derived classes declare non-readiness to k8s
63
+ isReady() {
64
+ return true;
65
+ }
66
+ /**
67
+ * Register message listeners here.
68
+ */
69
+ register() {
70
+ throw new Error("Not Implemented: register method in Service class.");
71
+ }
72
+ run() {
73
+ throw new Error("Not Implemented: run method in Service class.");
74
+ }
75
+ }
76
+ exports.default = BaseService;
77
+ //# sourceMappingURL=BaseService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseService.js","sourceRoot":"","sources":["../src/BaseService.ts"],"names":[],"mappings":";;AACA,0CAA0C;AAC1C,mCAAmC;AACnC,+BAKe;AACf,uCAAuC;AACvC,uCAAgC;AAEhC;;GAEG;AACH,MAAM,WAAW;IASf,YAAY,IAAkB;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC;QAC7C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;QACzC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC;QACxC,IAAI,CAAC,OAAO,GAAG,IAAI,iBAAO,CAAC,0BAAoB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAE9D;;WAEG;QACH,IAAI,gBAAU,EAAE;YACd,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;YAC1E,MAAM,CAAC,IAAI,CAAC;gBACV,GAAG,EAAE,gBAAU;gBACf,WAAW,EAAE,cAAQ;aACtB,CAAC,CAAC;SACJ;aAAM;YACL,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sDAAsD,CAAC,CAAC;SAC1E;QAED,4BAA4B;QAC5B,IAAG,CAAC,wBAAkB,EAAE;YACtB,6CAA6C;YAC7C,MAAM,qBAAqB,GAAG,UAAU,CAA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;OAEG;IACI,QAAQ;QACb,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAEM,GAAG;QACR,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;CACF;AAED,kBAAe,WAAW,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { ILogManager, ILogManagerOpts } from "./interfaces";
2
+ declare class ConsoleLogManager implements ILogManager {
3
+ opts: ILogManagerOpts;
4
+ constructor(opts: ILogManagerOpts);
5
+ info(msg: string, ...params: string[]): void;
6
+ warn(msg: string, ...params: string[]): void;
7
+ error(msg: string, ...params: string[]): void;
8
+ }
9
+ export default ConsoleLogManager;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class ConsoleLogManager {
4
+ constructor(opts) {
5
+ this.opts = opts;
6
+ }
7
+ info(msg, ...params) {
8
+ console.info(msg, ...params);
9
+ }
10
+ warn(msg, ...params) {
11
+ console.warn(msg, ...params);
12
+ }
13
+ error(msg, ...params) {
14
+ console.error(msg, ...params);
15
+ }
16
+ }
17
+ exports.default = ConsoleLogManager;
18
+ //# sourceMappingURL=ConsoleLogManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConsoleLogManager.js","sourceRoot":"","sources":["../src/ConsoleLogManager.ts"],"names":[],"mappings":";;AAEA,MAAM,iBAAiB;IAGrB,YAAY,IAAqB;QAC/B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEM,IAAI,CAAC,GAAW,EAAE,GAAG,MAAgB;QAC1C,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;IAC/B,CAAC;IAEM,IAAI,CAAC,GAAW,EAAE,GAAG,MAAgB;QAC1C,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;IAC/B,CAAC;IAEM,KAAK,CAAC,GAAW,EAAE,GAAG,MAAgB;QAC3C,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;IAChC,CAAC;CACF;AAED,kBAAe,iBAAiB,CAAC"}
@@ -0,0 +1,9 @@
1
+ export default class MongoConnectionManager {
2
+ connected: boolean;
3
+ mongoConnectionString: string;
4
+ isReplicaSet: boolean;
5
+ private mongoose;
6
+ private mongoConnectionStringInternal;
7
+ constructor(mongoose: any, mongoConnectionString: string, username?: string, password?: string);
8
+ connect(): Promise<void>;
9
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const wait_1 = require("@sellout/utils/.dist/wait");
13
+ class MongoConnectionManager {
14
+ constructor(mongoose, mongoConnectionString, username = '', password = '') {
15
+ const parsed = new URL(mongoConnectionString);
16
+ parsed.username = username;
17
+ parsed.password = password;
18
+ parsed.pathname = '/admin';
19
+ this.connected = false;
20
+ this.mongoConnectionStringInternal = parsed.toString();
21
+ this.isReplicaSet = parsed.protocol === 'mongodb+srv:';
22
+ // redact username/password from publicly available connection string
23
+ parsed.username = '__user__';
24
+ parsed.password = '__pass__';
25
+ this.mongoConnectionString = parsed.toString();
26
+ this.mongoose = mongoose;
27
+ }
28
+ connect() {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ while (!this.connected) {
31
+ console.log('Attempting to connect to Mongo...');
32
+ this.mongoose.connect(this.mongoConnectionStringInternal, {
33
+ ssl: false,
34
+ useUnifiedTopology: true,
35
+ useNewUrlParser: true,
36
+ })
37
+ .then(() => {
38
+ this.connected = true;
39
+ console.log(`Connected to MongoDB: ${this.mongoConnectionString}`);
40
+ })
41
+ .catch((e) => {
42
+ console.error(`There was an error connecting to MongoDB: ${this.mongoConnectionString}`);
43
+ console.error(e);
44
+ });
45
+ // wait five seconds before trying again
46
+ yield wait_1.default(5000);
47
+ }
48
+ });
49
+ }
50
+ }
51
+ exports.default = MongoConnectionManager;
52
+ //# sourceMappingURL=MongoConnectionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MongoConnectionManager.js","sourceRoot":"","sources":["../src/MongoConnectionManager.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,oDAA6C;AAE7C,MAAqB,sBAAsB;IAOzC,YAAY,QAAa,EAAE,qBAA6B,EAAE,WAAmB,EAAE,EAAE,WAAmB,EAAE;QACpG,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,qBAAqB,CAAC,CAAC;QAE9C,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAE3B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,6BAA6B,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;QACvD,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,QAAQ,KAAK,cAAc,CAAC;QAEvD,qEAAqE;QACrE,MAAM,CAAC,QAAQ,GAAG,UAAU,CAAC;QAC7B,MAAM,CAAC,QAAQ,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,qBAAqB,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAEY,OAAO;;YAClB,OAAM,CAAC,IAAI,CAAC,SAAS,EAAE;gBACrB,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;gBACjD,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE;oBACxD,GAAG,EAAE,KAAK;oBACV,kBAAkB,EAAE,IAAI;oBACxB,eAAe,EAAE,IAAI;iBACtB,CAAC;qBACC,IAAI,CAAC,GAAG,EAAE;oBACT,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;oBACtB,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC;gBACrE,CAAC,CAAC;qBACD,KAAK,CAAC,CAAC,CAAM,EAAE,EAAE;oBAChB,OAAO,CAAC,KAAK,CAAC,6CAA6C,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC;oBACzF,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBACnB,CAAC,CAAC,CAAC;gBAEL,wCAAwC;gBACxC,MAAM,cAAI,CAAC,IAAI,CAAC,CAAC;aAClB;QACH,CAAC;KAAA;CACF;AA9CD,yCA8CC"}
@@ -0,0 +1,115 @@
1
+ /// <reference types="node" />
2
+ import { IConnectionManager, ILogManager, ISubscriptionRoutes } from './interfaces';
3
+ /**
4
+ * Exposes connection operations for NATS.
5
+ */
6
+ declare class NatsConnectionManager implements IConnectionManager {
7
+ /**
8
+ * Exception representing an error that occurred during invocation of
9
+ * a message handler.
10
+ *
11
+ */
12
+ static MESSAGE_HANDLER_ERROR: {
13
+ new (errors: any, messageSubject: string): {
14
+ errors: any;
15
+ name: string;
16
+ message: string;
17
+ stack?: string | undefined;
18
+ };
19
+ captureStackTrace(targetObject: object, constructorOpt?: Function | undefined): void;
20
+ prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
21
+ stackTraceLimit: number;
22
+ };
23
+ /**
24
+ * Exception caused by request timeout.
25
+ */
26
+ static TIMEOUT_ERROR: {
27
+ new (errors: any): {
28
+ errors: any;
29
+ name: string;
30
+ message: string;
31
+ stack?: string | undefined;
32
+ };
33
+ captureStackTrace(targetObject: object, constructorOpt?: Function | undefined): void;
34
+ prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
35
+ stackTraceLimit: number;
36
+ };
37
+ natsServers: string[];
38
+ private verbose;
39
+ private defaultRequestTimeout;
40
+ private conn;
41
+ private logPrefix;
42
+ private logger;
43
+ /**
44
+ * Manages connections to NATS servers.
45
+ * @constructor
46
+ *
47
+ * @param {boolean} verbose - Log all events if true
48
+ */
49
+ constructor(natsServers: string[], logger: ILogManager, verbose?: boolean, defaultRequestTimeout?: number);
50
+ /**
51
+ * Connect to one of the specified servers.
52
+ *
53
+ * @param {string[]} servers - Array of server URLs for NATS (server is randomly chosen)
54
+ */
55
+ connect(waitForConnect?: boolean): void;
56
+ /**
57
+ * Close active connections.
58
+ */
59
+ close(): void;
60
+ /**
61
+ * Expose event system of Nats client.
62
+ *
63
+ * @param event
64
+ * @callback cb
65
+ */
66
+ on(event: string, cb: (...args: any[]) => void): void;
67
+ /**
68
+ * Subscribes a service listener to its methods within a NATS queue.
69
+ *
70
+ * IMPORTANT: Ensure service message handlers are defined via arrow functions
71
+ * to ensure instance variables of the class are accessible within
72
+ * the scope of the handlers.
73
+ *
74
+ * @param service - Service Id of listener
75
+ * @param @optional {string} - Optional name of queue to subscribe
76
+ * @param {SubscriptionRoutes} routes - Mapping of method Ids to handlers
77
+ */
78
+ subscribe(serviceId: string, queue: string, routes: ISubscriptionRoutes): void;
79
+ subscribeBroadcast(serviceId: string, routes: ISubscriptionRoutes): void;
80
+ subscribeTopic(topicQualifier: string, queue: string | undefined, routes: ISubscriptionRoutes): void;
81
+ /**
82
+ * Publish request for service.
83
+ *
84
+ * @param {string} serviceId - Service Id of receipient
85
+ * @param {string} method - Id of method to call
86
+ * @param {Buffer} req - Request buffer
87
+ * @callback cb - Reply callback
88
+ * @param { number} [timeout] - Register a default timeout for requests
89
+ */
90
+ send: (serviceId: string, method: string, req: Buffer, cb: (error: any, reply: any) => void, timeout?: number | undefined) => void;
91
+ /**
92
+ * Publish a broadcast message
93
+ */
94
+ sendBroadcast: (messageId: string, req: Buffer, cb: (error: any, reply: any) => void) => void;
95
+ /**
96
+ * Publish asynchronous request for service.
97
+ *
98
+ * @param {string} serviceId - Service Id of receipient
99
+ * @param {string} method - Id of method to call
100
+ * @param {Buffer} req - Request buffer
101
+ * @callback cb - Reply callback
102
+ */
103
+ sendAsync: (serviceId: string, method: string, req: Buffer, cb: (error: any, reply: any) => void) => void;
104
+ /**
105
+ * Register for logged connection events
106
+ */
107
+ private enableLogging;
108
+ /**
109
+ * Log a message
110
+ *
111
+ * @param msg
112
+ */
113
+ private logMessage;
114
+ }
115
+ export default NatsConnectionManager;
@@ -0,0 +1,215 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const NATS = require("nats");
4
+ const BROADCAST_PREFIX = 'BROADCAST'; /* Prefix for broadcast messages */
5
+ /**
6
+ * Exposes connection operations for NATS.
7
+ */
8
+ class NatsConnectionManager {
9
+ /**
10
+ * Manages connections to NATS servers.
11
+ * @constructor
12
+ *
13
+ * @param {boolean} verbose - Log all events if true
14
+ */
15
+ constructor(natsServers, logger, verbose = false, defaultRequestTimeout = 60000) {
16
+ this.logPrefix = 'NatsConnectionManager';
17
+ /**
18
+ * Publish request for service.
19
+ *
20
+ * @param {string} serviceId - Service Id of receipient
21
+ * @param {string} method - Id of method to call
22
+ * @param {Buffer} req - Request buffer
23
+ * @callback cb - Reply callback
24
+ * @param { number} [timeout] - Register a default timeout for requests
25
+ */
26
+ // tslint:disable-next-line:max-line-length
27
+ this.send = (serviceId, method, req, cb, timeout) => {
28
+ const subject = [serviceId, method].join('.');
29
+ const msgId = this.conn.requestOne(subject, req, {}, timeout == null ? this.defaultRequestTimeout : timeout, (reply) => {
30
+ this.logMessage(`Sending message: ${subject} (${msgId})`);
31
+ if (reply.code && reply.code === NATS.REQ_TIMEOUT) {
32
+ this.logMessage(`Reply for (${msgId}): ${JSON.stringify(reply)}`, true);
33
+ const error = new NatsConnectionManager.TIMEOUT_ERROR({
34
+ message: `Timeout sending request: ${subject} (${msgId})`,
35
+ });
36
+ cb(error, null);
37
+ return;
38
+ }
39
+ this.logMessage(`Received reply: ${subject} (${msgId})`);
40
+ cb(null, reply);
41
+ });
42
+ };
43
+ /**
44
+ * Publish a broadcast message
45
+ */
46
+ this.sendBroadcast = (messageId, req, cb) => {
47
+ return this.sendAsync(BROADCAST_PREFIX, messageId, req, cb);
48
+ };
49
+ /**
50
+ * Publish asynchronous request for service.
51
+ *
52
+ * @param {string} serviceId - Service Id of receipient
53
+ * @param {string} method - Id of method to call
54
+ * @param {Buffer} req - Request buffer
55
+ * @callback cb - Reply callback
56
+ */
57
+ this.sendAsync = (serviceId, method, req, cb) => {
58
+ const subject = [serviceId, method].join('.');
59
+ this.conn.publish(subject, req, (reply) => {
60
+ this.logMessage(`Queued message: ${subject}`);
61
+ // NATS always returns "undefined" for publish, since reply is N/A.
62
+ // Protobuf Services require _some_ kind of Type (cannot be undefined or void).
63
+ // thus, return an empty `<Buffer >` here, which can be marshalled to the `google.protobuf.Empty` type.
64
+ const empty = Buffer.from([]);
65
+ cb(null, empty);
66
+ });
67
+ };
68
+ this.logger = logger;
69
+ this.natsServers = natsServers;
70
+ this.verbose = verbose;
71
+ if (process.env.NATS_TIMEOUT) {
72
+ this.defaultRequestTimeout = parseInt(process.env.NATS_TIMEOUT, 10);
73
+ }
74
+ else {
75
+ this.defaultRequestTimeout = defaultRequestTimeout;
76
+ }
77
+ }
78
+ /**
79
+ * Connect to one of the specified servers.
80
+ *
81
+ * @param {string[]} servers - Array of server URLs for NATS (server is randomly chosen)
82
+ */
83
+ connect(waitForConnect = true) {
84
+ const opts = {};
85
+ opts.servers = this.natsServers;
86
+ opts.preserveBuffers = true;
87
+ opts.verbose = this.verbose;
88
+ opts.waitOnFirstConnect = waitForConnect;
89
+ opts.maxReconnectAttempts = -1; /* Infinite reconnect attempts */
90
+ this.conn = NATS.connect(opts);
91
+ this.enableLogging();
92
+ }
93
+ /**
94
+ * Close active connections.
95
+ */
96
+ close() {
97
+ this.conn.close();
98
+ }
99
+ /**
100
+ * Expose event system of Nats client.
101
+ *
102
+ * @param event
103
+ * @callback cb
104
+ */
105
+ on(event, cb) {
106
+ this.conn.on(event, cb);
107
+ }
108
+ /**
109
+ * Subscribes a service listener to its methods within a NATS queue.
110
+ *
111
+ * IMPORTANT: Ensure service message handlers are defined via arrow functions
112
+ * to ensure instance variables of the class are accessible within
113
+ * the scope of the handlers.
114
+ *
115
+ * @param service - Service Id of listener
116
+ * @param @optional {string} - Optional name of queue to subscribe
117
+ * @param {SubscriptionRoutes} routes - Mapping of method Ids to handlers
118
+ */
119
+ subscribe(serviceId, queue, routes) {
120
+ this.logMessage(`Subscribing handlers for service='${serviceId}', queue='${queue}'`);
121
+ const topic = [serviceId, '>'].join('.');
122
+ return this.subscribeTopic(topic, queue, routes); /* Match all topics containing Service Id */
123
+ }
124
+ subscribeBroadcast(serviceId, routes) {
125
+ const routeNames = Object.keys(routes);
126
+ this.logMessage(`Subscribing handlers for broadcast: [${routeNames.join(', ')}]`);
127
+ routeNames.forEach((r) => {
128
+ const topic = [BROADCAST_PREFIX, r].join('.');
129
+ const queue = `${serviceId}-${r}`;
130
+ this.subscribeTopic(topic, queue, { [r]: routes[r] });
131
+ });
132
+ }
133
+ subscribeTopic(topicQualifier, queue, routes) {
134
+ const opts = {};
135
+ opts.queue = queue;
136
+ this.conn.subscribe(topicQualifier, opts, (req, reply, subject) => {
137
+ const method = subject.substring(subject.indexOf('.') + 1);
138
+ const handler = routes[method];
139
+ this.logMessage(`Receive message: full subject=${subject}, method=${method}, replyTo=${reply} `);
140
+ handler.process(req).then((resp) => {
141
+ if (reply) {
142
+ this.logMessage(`Publishing reply: ${reply}`);
143
+ this.conn.publish(reply, resp);
144
+ }
145
+ else {
146
+ this.logMessage('No reply required');
147
+ }
148
+ }, (reason) => {
149
+ this.logMessage(`Handler failed. Reason= ${reason}`, false);
150
+ throw new NatsConnectionManager.MESSAGE_HANDLER_ERROR(reason, subject);
151
+ });
152
+ });
153
+ }
154
+ /**
155
+ * Register for logged connection events
156
+ */
157
+ enableLogging() {
158
+ /**
159
+ * GENERIC ERROR LOGGING
160
+ */
161
+ this.conn.on('error', (err) => {
162
+ this.logMessage(err, false);
163
+ });
164
+ if (!this.verbose) {
165
+ return;
166
+ }
167
+ /**
168
+ * VERBOSE EVENT LOGGING
169
+ */
170
+ this.conn.on('connect', (conn) => {
171
+ this.logMessage(`Connection established to ${conn.currentServer.url.host}`);
172
+ });
173
+ this.conn.on('disconnect', () => {
174
+ this.logMessage('Disconnected', false);
175
+ });
176
+ this.conn.on('reconnect', () => {
177
+ this.logMessage('Reconnected', false);
178
+ });
179
+ this.conn.on('close', () => {
180
+ this.logMessage('Connection closed');
181
+ });
182
+ }
183
+ /**
184
+ * Log a message
185
+ *
186
+ * @param msg
187
+ */
188
+ logMessage(msg, info = true) {
189
+ if (!info || this.verbose) {
190
+ this.logger.info(`(${this.logPrefix}) ${msg}`);
191
+ }
192
+ }
193
+ }
194
+ /**
195
+ * Exception representing an error that occurred during invocation of
196
+ * a message handler.
197
+ *
198
+ */
199
+ NatsConnectionManager.MESSAGE_HANDLER_ERROR = class extends Error {
200
+ constructor(errors, messageSubject) {
201
+ super(`Error from message handler for '${messageSubject}'. Reason = ${JSON.stringify(errors)}`);
202
+ this.errors = errors;
203
+ }
204
+ };
205
+ /**
206
+ * Exception caused by request timeout.
207
+ */
208
+ NatsConnectionManager.TIMEOUT_ERROR = class extends Error {
209
+ constructor(errors) {
210
+ super('NATS Timeout');
211
+ this.errors = errors;
212
+ }
213
+ };
214
+ exports.default = NatsConnectionManager;
215
+ //# sourceMappingURL=NatsConnectionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NatsConnectionManager.js","sourceRoot":"","sources":["../src/NatsConnectionManager.ts"],"names":[],"mappings":"AA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AAI,CAAC,IAAI,IAAI,CAAC,SAAS,KAAK,GAAG,EAAE,CAAC,CAAC;SAChD;IACH,CAAC;;AA7PD;;;;GAIG;AACW,2CAAqB,GAAG,KAAM,SAAQ,KAAK;IAGvD,YAAY,MAAM,EAAE,cAAsB;QACxC,KAAK,CAAC,mCAAmC,cAAc,eAAe,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAChG,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF,CAAC;AAEF;;GAEG;AACW,mCAAa,GAAG,KAAM,SAAQ,KAAK;IAG/C,YAAY,MAAM;QAChB,KAAK,CAAC,cAAc,CAAC,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF,CAAC;AAwOJ,kBAAe,qBAAqB,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { PbMessageHandler } from './PbMessageHandler';
2
+ /**
3
+ * Provides a wrapper around asynchronous Protobuf messages that don't return a response.
4
+ * Incoming buffers are decoded, the handler method is called using staticly-compiled
5
+ * Protobuf definitions.
6
+ */
7
+ export declare class PbAsyncMessageHandler extends PbMessageHandler {
8
+ /**
9
+ * @constructor
10
+ * @param method - Message handler method to be invoked
11
+ * @param requestCls - Request class provided by Protobuf
12
+ */
13
+ constructor(method: any, requestCls: any);
14
+ }
15
+ export default PbAsyncMessageHandler;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const pb = require("@sellout/models/.dist/sellout-proto");
4
+ const PbMessageHandler_1 = require("./PbMessageHandler");
5
+ /* Message handler wrapper method for unidirectional calls */
6
+ function invokeWithEmptyResponse(method) {
7
+ return (req) => method(req).then(() => Promise.resolve(pb.google.protobuf.Empty.create()));
8
+ }
9
+ /**
10
+ * Provides a wrapper around asynchronous Protobuf messages that don't return a response.
11
+ * Incoming buffers are decoded, the handler method is called using staticly-compiled
12
+ * Protobuf definitions.
13
+ */
14
+ class PbAsyncMessageHandler extends PbMessageHandler_1.PbMessageHandler {
15
+ /**
16
+ * @constructor
17
+ * @param method - Message handler method to be invoked
18
+ * @param requestCls - Request class provided by Protobuf
19
+ */
20
+ constructor(method, requestCls) {
21
+ super(invokeWithEmptyResponse(method), requestCls, pb.google.protobuf.Empty);
22
+ }
23
+ }
24
+ exports.PbAsyncMessageHandler = PbAsyncMessageHandler;
25
+ exports.default = PbAsyncMessageHandler;
26
+ //# sourceMappingURL=PbAsyncMessageHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PbAsyncMessageHandler.js","sourceRoot":"","sources":["../src/PbAsyncMessageHandler.ts"],"names":[],"mappings":";;AAAA,0DAA0D;AAC1D,yDAAsD;AAGtD,6DAA6D;AAC7D,SAAS,uBAAuB,CAAC,MAAM;IACrC,OAAO,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AACrG,CAAC;AAED;;;;GAIG;AACH,MAAa,qBAAsB,SAAQ,mCAAgB;IAEzD;;;;OAIG;IACH,YAAY,MAAM,EAAE,UAAU;QAC5B,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/E,CAAC;CAEF;AAXD,sDAWC;AAED,kBAAe,qBAAqB,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { Broadcast } from "@sellout/models/.dist/sellout-proto";
2
+ import { IConnectionManager } from './interfaces';
3
+ import { PbServiceProxy } from './PbServiceProxy';
4
+ export default class PbBroadcastProxy extends PbServiceProxy<Broadcast.Publisher> {
5
+ constructor(conn: IConnectionManager);
6
+ activate(svc?: any): Broadcast.Publisher;
7
+ /**
8
+ * Provides handler logic for RPC sender. Note: use of arrow function
9
+ * required to maintain instance context.
10
+ *
11
+ * @param method
12
+ * @param requestData
13
+ * @param callback
14
+ */
15
+ protected sendRpcImpl: (method: any, requestData: any, callback: any) => never;
16
+ /**
17
+ * Provides handler logic for RPC sender. Note: use of arrow function
18
+ * required to maintain instance context.
19
+ *
20
+ * @param method
21
+ * @param requestData
22
+ * @param callback
23
+ */
24
+ protected sendRpcImplAsync: (method: any, requestData: any, callback: any) => void;
25
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const sellout_proto_1 = require("@sellout/models/.dist/sellout-proto");
4
+ const PbServiceProxy_1 = require("./PbServiceProxy");
5
+ class PbBroadcastProxy extends PbServiceProxy_1.PbServiceProxy {
6
+ constructor(conn) {
7
+ super(conn, 'BROADCAST');
8
+ /**
9
+ * Provides handler logic for RPC sender. Note: use of arrow function
10
+ * required to maintain instance context.
11
+ *
12
+ * @param method
13
+ * @param requestData
14
+ * @param callback
15
+ */
16
+ this.sendRpcImpl = (method, requestData, callback) => {
17
+ throw ('PbBroadcastProxy does not support synchronous calls');
18
+ };
19
+ /**
20
+ * Provides handler logic for RPC sender. Note: use of arrow function
21
+ * required to maintain instance context.
22
+ *
23
+ * @param method
24
+ * @param requestData
25
+ * @param callback
26
+ */
27
+ this.sendRpcImplAsync = (method, requestData, callback) => {
28
+ try {
29
+ this.conn.sendBroadcast(method.name, requestData, callback);
30
+ }
31
+ catch (e) {
32
+ callback(e, null);
33
+ }
34
+ };
35
+ }
36
+ activate(svc = sellout_proto_1.Broadcast.Publisher) {
37
+ return super.activate(svc, true);
38
+ }
39
+ }
40
+ exports.default = PbBroadcastProxy;
41
+ //# sourceMappingURL=PbBroadcastProxy.js.map