@mojaloop/sdk-scheme-adapter 12.2.1 → 12.3.0
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/.env.example +1 -1
- package/CHANGELOG.md +22 -0
- package/audit-resolve.json +71 -1
- package/package.json +4 -1
- package/src/ControlAgent/index.js +2 -3
- package/src/ControlServer/index.js +2 -2
- package/src/InboundServer/index.js +7 -7
- package/src/InboundServer/middlewares.js +2 -2
- package/src/OutboundServer/handlers.js +3 -0
- package/src/OutboundServer/index.js +10 -11
- package/src/config.js +31 -14
- package/src/index.js +198 -10
- package/src/lib/cache.js +110 -52
- package/src/lib/metrics.js +148 -0
- package/src/lib/model/AccountsModel.js +4 -1
- package/src/lib/model/Async2SyncModel.js +4 -1
- package/src/lib/model/InboundTransfersModel.js +4 -1
- package/src/lib/model/OutboundBulkQuotesModel.js +4 -1
- package/src/lib/model/OutboundBulkTransfersModel.js +4 -1
- package/src/lib/model/OutboundRequestToPayModel.js +4 -1
- package/src/lib/model/OutboundRequestToPayTransferModel.js +4 -1
- package/src/lib/model/OutboundTransfersModel.js +61 -1
- package/src/lib/model/ProxyModel/index.js +4 -2
- package/src/lib/validate.js +2 -2
- package/test/__mocks__/redis.js +4 -0
- package/test/config/integration.env +5 -0
- package/test/unit/ControlServer/index.js +3 -3
- package/test/unit/InboundServer.test.js +1 -1
- package/test/unit/api/utils.js +4 -1
- package/test/unit/config.test.js +3 -3
- package/test/unit/data/defaultConfig.json +23 -7
- package/test/unit/index.test.js +95 -4
- package/test/unit/lib/model/OutboundTransfersModel.test.js +37 -1
- package/test/unit/lib/model/data/defaultConfig.json +24 -9
- package/src/lib/api/index.js +0 -12
- package/src/lib/randomphrase/index.js +0 -21
- package/src/lib/randomphrase/words.json +0 -3397
package/src/index.js
CHANGED
|
@@ -10,14 +10,18 @@
|
|
|
10
10
|
|
|
11
11
|
'use strict';
|
|
12
12
|
|
|
13
|
+
const assert = require('assert/strict');
|
|
13
14
|
const { hostname } = require('os');
|
|
14
15
|
const config = require('./config');
|
|
15
16
|
const EventEmitter = require('events');
|
|
17
|
+
const _ = require('lodash');
|
|
16
18
|
|
|
17
19
|
const InboundServer = require('./InboundServer');
|
|
18
20
|
const OutboundServer = require('./OutboundServer');
|
|
19
21
|
const OAuthTestServer = require('./OAuthTestServer');
|
|
20
22
|
const TestServer = require('./TestServer');
|
|
23
|
+
const { MetricsServer, MetricsClient } = require('./lib/metrics');
|
|
24
|
+
const ControlAgent = require('./ControlAgent');
|
|
21
25
|
|
|
22
26
|
// import things we want to expose e.g. for unit tests and users who dont want to use the entire
|
|
23
27
|
// scheme adapter as a service
|
|
@@ -25,10 +29,20 @@ const InboundServerMiddleware = require('./InboundServer/middlewares.js');
|
|
|
25
29
|
const OutboundServerMiddleware = require('./OutboundServer/middlewares.js');
|
|
26
30
|
const Router = require('./lib/router');
|
|
27
31
|
const Validate = require('./lib/validate');
|
|
28
|
-
const RandomPhrase = require('./lib/randomphrase');
|
|
29
32
|
const Cache = require('./lib/cache');
|
|
33
|
+
const check = require('./lib/check');
|
|
30
34
|
const { Logger } = require('@mojaloop/sdk-standard-components');
|
|
31
35
|
|
|
36
|
+
const LOG_ID = {
|
|
37
|
+
INBOUND: { app: 'mojaloop-connector-inbound-api' },
|
|
38
|
+
OUTBOUND: { app: 'mojaloop-connector-outbound-api' },
|
|
39
|
+
TEST: { app: 'mojaloop-connector-test-api' },
|
|
40
|
+
OAUTHTEST: { app: 'mojaloop-connector-oauth-test-server' },
|
|
41
|
+
CONTROL: { app: 'mojaloop-connector-control-client' },
|
|
42
|
+
METRICS: { app: 'mojaloop-connector-metrics' },
|
|
43
|
+
CACHE: { component: 'cache' },
|
|
44
|
+
};
|
|
45
|
+
|
|
32
46
|
/**
|
|
33
47
|
* Class that creates and manages http servers that expose the scheme adapter APIs.
|
|
34
48
|
*/
|
|
@@ -39,14 +53,22 @@ class Server extends EventEmitter {
|
|
|
39
53
|
this.logger = logger;
|
|
40
54
|
this.cache = new Cache({
|
|
41
55
|
...conf.cacheConfig,
|
|
42
|
-
logger: this.logger.push(
|
|
56
|
+
logger: this.logger.push(LOG_ID.CACHE),
|
|
43
57
|
enableTestFeatures: conf.enableTestFeatures,
|
|
44
58
|
});
|
|
45
59
|
|
|
60
|
+
this.metricsClient = new MetricsClient();
|
|
61
|
+
|
|
62
|
+
this.metricsServer = new MetricsServer({
|
|
63
|
+
port: this.conf.metrics.port,
|
|
64
|
+
logger: this.logger.push(LOG_ID.METRICS)
|
|
65
|
+
});
|
|
66
|
+
|
|
46
67
|
this.inboundServer = new InboundServer(
|
|
47
68
|
this.conf,
|
|
48
|
-
this.logger.push(
|
|
49
|
-
this.cache
|
|
69
|
+
this.logger.push(LOG_ID.INBOUND),
|
|
70
|
+
this.cache,
|
|
71
|
+
this.metricsClient
|
|
50
72
|
);
|
|
51
73
|
this.inboundServer.on('error', (...args) => {
|
|
52
74
|
this.logger.push({ args }).log('Unhandled error in Inbound Server');
|
|
@@ -55,8 +77,9 @@ class Server extends EventEmitter {
|
|
|
55
77
|
|
|
56
78
|
this.outboundServer = new OutboundServer(
|
|
57
79
|
this.conf,
|
|
58
|
-
this.logger.push(
|
|
59
|
-
this.cache
|
|
80
|
+
this.logger.push(LOG_ID.OUTBOUND),
|
|
81
|
+
this.cache,
|
|
82
|
+
this.metricsClient
|
|
60
83
|
);
|
|
61
84
|
this.outboundServer.on('error', (...args) => {
|
|
62
85
|
this.logger.push({ args }).log('Unhandled error in Outbound Server');
|
|
@@ -67,16 +90,140 @@ class Server extends EventEmitter {
|
|
|
67
90
|
clientKey: this.conf.oauthTestServer.clientKey,
|
|
68
91
|
clientSecret: this.conf.oauthTestServer.clientSecret,
|
|
69
92
|
port: this.conf.oauthTestServer.listenPort,
|
|
70
|
-
logger: this.logger.push(
|
|
93
|
+
logger: this.logger.push(LOG_ID.OAUTHTEST),
|
|
71
94
|
});
|
|
72
95
|
|
|
73
96
|
this.testServer = new TestServer({
|
|
74
|
-
port: this.conf.
|
|
75
|
-
logger: this.logger.push(
|
|
97
|
+
port: this.conf.test.port,
|
|
98
|
+
logger: this.logger.push(LOG_ID.TEST),
|
|
76
99
|
cache: this.cache,
|
|
77
100
|
});
|
|
78
101
|
}
|
|
79
102
|
|
|
103
|
+
async restart(newConf) {
|
|
104
|
+
// Figuring out what config is necessary in each server and component is a pretty big job
|
|
105
|
+
// that we'll have to save for later. For now, when the config changes, we'll restart
|
|
106
|
+
// more than we might have to.
|
|
107
|
+
// We'll do this by:
|
|
108
|
+
// 0. creating a new instance of the logger, if necessary
|
|
109
|
+
// 1. creating a new instance of the cache, if necessary
|
|
110
|
+
// 2. calling the async reconfigure method of each of the servers as necessary- this will
|
|
111
|
+
// return a synchronous function that we can call to swap over the server events and
|
|
112
|
+
// object properties to the new ones. It will:
|
|
113
|
+
// 1. remove the `request` listener for each of the HTTP servers
|
|
114
|
+
// 2. add the new appropriate `request` listener
|
|
115
|
+
// This results in a completely synchronous listener changeover to the new config and
|
|
116
|
+
// therefore hopefully avoids any concurrency issues arising from restarting different
|
|
117
|
+
// servers or components concurrently.
|
|
118
|
+
// TODO: in the sense of being able to reason about the code, it would make some sense to
|
|
119
|
+
// turn the config items or object passed to each server into an event emitter, or pass an
|
|
120
|
+
// additional event emitter to the server constructor for the server to listen to and act
|
|
121
|
+
// on changes. Before this, however, it's probably necessary to ensure each server gets
|
|
122
|
+
// _only_ the config it needs, not the entire config object.
|
|
123
|
+
// Further: it might be possible to use Object.observe for this functionality.
|
|
124
|
+
// TODO: what happens if this is run concurrently? I.e. if it is called twice in rapid
|
|
125
|
+
// succession. This question probably needs to be asked of the reconfigure message on every
|
|
126
|
+
// server.
|
|
127
|
+
// Note that it should be possible to reconfigure ports on a running server by reassigning
|
|
128
|
+
// servers, e.g.
|
|
129
|
+
// this.inboundServer._server = createHttpServer();
|
|
130
|
+
// this.inboundServer._server.listen(newPort);
|
|
131
|
+
// If there are conflicts, for example if the new configuration specifies the new inbound
|
|
132
|
+
// port to be the same value as the old outbound port, this will require either
|
|
133
|
+
// 1. some juggling of HTTP servers, e.g.
|
|
134
|
+
// const oldInboundServer = this.inboundServer._server;
|
|
135
|
+
// this.inboundServer._server = this.outboundServer._server;
|
|
136
|
+
// .. etc.
|
|
137
|
+
// 2. some juggling of sockets between servers, if possible
|
|
138
|
+
// 3. rearchitecting of the servers, perhaps splitting the .start() method on the servers
|
|
139
|
+
// to an .init() and .listen() methods, with the latter optionally taking an HTTP server
|
|
140
|
+
// as argument
|
|
141
|
+
// This _might_ introduce some confusion/complexity for existing websocket clients, but as
|
|
142
|
+
// the event handlers _should_ not be modified this shouldn't be a problem. A careful
|
|
143
|
+
// analysis of this will be necessary.
|
|
144
|
+
assert(newConf.inbound.port === this.conf.inbound.port
|
|
145
|
+
&& newConf.outbound.port === this.conf.outbound.port
|
|
146
|
+
&& newConf.test.port === this.conf.test.port
|
|
147
|
+
&& newConf.oauthTestServer.listenPort === this.conf.oauthTestServer.listenPort
|
|
148
|
+
&& newConf.control.mgmtAPIWsPort === this.conf.control.mgmtAPIWsPort,
|
|
149
|
+
'Cannot reconfigure ports on running server');
|
|
150
|
+
const doNothing = () => {};
|
|
151
|
+
const updateLogger = check.notDeepEqual(newConf.logIndent, this.conf.logIndent);
|
|
152
|
+
if (updateLogger) {
|
|
153
|
+
this.logger = new Logger.Logger({
|
|
154
|
+
context: {
|
|
155
|
+
// If we're running from a Mojaloop helm chart deployment, we'll have a SIM_NAME
|
|
156
|
+
simulator: process.env['SIM_NAME'],
|
|
157
|
+
hostname: hostname(),
|
|
158
|
+
},
|
|
159
|
+
stringify: Logger.buildStringify({ space: this.conf.logIndent }),
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
let oldCache;
|
|
163
|
+
const updateCache = (
|
|
164
|
+
updateLogger ||
|
|
165
|
+
check.notDeepEqual(this.conf.cacheConfig, newConf.cacheConfig) ||
|
|
166
|
+
check.notDeepEqual(this.conf.enableTestFeatures, newConf.enableTestFeatures)
|
|
167
|
+
);
|
|
168
|
+
if (updateCache) {
|
|
169
|
+
oldCache = this.cache;
|
|
170
|
+
this.cache = new Cache({
|
|
171
|
+
...newConf.cacheConfig,
|
|
172
|
+
logger: this.logger.push(LOG_ID.CACHE),
|
|
173
|
+
enableTestFeatures: newConf.enableTestFeatures,
|
|
174
|
+
});
|
|
175
|
+
await this.cache.connect();
|
|
176
|
+
}
|
|
177
|
+
const confChanged = !check.deepEqual(newConf, this.conf);
|
|
178
|
+
// TODO: find better naming than "restart", because that's not really what's happening.
|
|
179
|
+
const [restartInboundServer, restartOutboundServer, restartControlClient] = confChanged
|
|
180
|
+
? await Promise.all([
|
|
181
|
+
this.inboundServer.reconfigure(newConf, this.logger.push(LOG_ID.INBOUND), this.cache),
|
|
182
|
+
this.outboundServer.reconfigure(newConf, this.logger.push(LOG_ID.OUTBOUND), this.cache, this.metricsClient),
|
|
183
|
+
this.controlClient.reconfigure({
|
|
184
|
+
logger: this.logger.push(LOG_ID.CONTROL),
|
|
185
|
+
port: newConf.control.mgmtAPIWsPort,
|
|
186
|
+
appConfig: newConf
|
|
187
|
+
}),
|
|
188
|
+
])
|
|
189
|
+
: [doNothing, doNothing, doNothing];
|
|
190
|
+
const updateOAuthTestServer = (
|
|
191
|
+
updateLogger || check.notDeepEqual(newConf.oauthTestServer, this.conf.oauthTestServer)
|
|
192
|
+
);
|
|
193
|
+
const restartOAuthTestServer = updateOAuthTestServer
|
|
194
|
+
? await this.oauthTestServer.reconfigure({
|
|
195
|
+
clientKey: this.conf.oauthTestServer.clientKey,
|
|
196
|
+
clientSecret: this.conf.oauthTestServer.clientSecret,
|
|
197
|
+
port: this.conf.oauthTestServer.listenPort,
|
|
198
|
+
logger: this.logger.push(LOG_ID.OAUTHTEST),
|
|
199
|
+
})
|
|
200
|
+
: doNothing;
|
|
201
|
+
const updateTestServer = (
|
|
202
|
+
updateLogger || updateCache || check.notDeepEqual(newConf.test.port, this.conf.test.port)
|
|
203
|
+
);
|
|
204
|
+
const restartTestServer = updateTestServer
|
|
205
|
+
? await this.testServer.reconfigure({
|
|
206
|
+
port: newConf.test.port,
|
|
207
|
+
logger: this.logger.push(LOG_ID.TEST),
|
|
208
|
+
cache: this.cache,
|
|
209
|
+
})
|
|
210
|
+
: doNothing;
|
|
211
|
+
// You may not return an async restart function. Perform any required async activity in the
|
|
212
|
+
// reconfigure function and return a sync restart function. See the note at the top of this
|
|
213
|
+
// file.
|
|
214
|
+
[restartTestServer, restartOAuthTestServer, restartInboundServer, restartOutboundServer, restartControlClient]
|
|
215
|
+
.map(f => assert(Promise.resolve(f) !== f, 'Restart functions must be synchronous'));
|
|
216
|
+
restartTestServer();
|
|
217
|
+
restartOAuthTestServer();
|
|
218
|
+
restartInboundServer();
|
|
219
|
+
restartOutboundServer();
|
|
220
|
+
restartControlClient();
|
|
221
|
+
this.conf = newConf;
|
|
222
|
+
await Promise.all([
|
|
223
|
+
oldCache && oldCache.disconnect(),
|
|
224
|
+
]);
|
|
225
|
+
}
|
|
226
|
+
|
|
80
227
|
async start() {
|
|
81
228
|
await this.cache.connect();
|
|
82
229
|
|
|
@@ -84,9 +231,25 @@ class Server extends EventEmitter {
|
|
|
84
231
|
const startOauthTestServer = this.conf.oauthTestServer.enabled
|
|
85
232
|
? this.oauthTestServer.start()
|
|
86
233
|
: null;
|
|
234
|
+
|
|
235
|
+
// We only start the control client if we're running within Mojaloop Payment Manager.
|
|
236
|
+
// The control server is the Payment Manager Management API Service.
|
|
237
|
+
// We only start the client to connect to and listen to the Management API service for
|
|
238
|
+
// management protocol messages e.g configuration changes, certificate updates etc.
|
|
239
|
+
if (this.conf.pm4mlEnabled) {
|
|
240
|
+
this.controlClient = await ControlAgent.Client.Create({
|
|
241
|
+
address: this.conf.control.mgmtAPIWsUrl,
|
|
242
|
+
port: this.conf.control.mgmtAPIWsPort,
|
|
243
|
+
logger: this.logger.push(LOG_ID.CONTROL),
|
|
244
|
+
appConfig: this.conf,
|
|
245
|
+
});
|
|
246
|
+
this.controlClient.on(ControlAgent.EVENT.RECONFIGURE, this.restart.bind(this));
|
|
247
|
+
}
|
|
248
|
+
|
|
87
249
|
await Promise.all([
|
|
88
250
|
this.inboundServer.start(),
|
|
89
251
|
this.outboundServer.start(),
|
|
252
|
+
this.metricsServer.start(),
|
|
90
253
|
startTestServer,
|
|
91
254
|
startOauthTestServer,
|
|
92
255
|
]);
|
|
@@ -98,10 +261,23 @@ class Server extends EventEmitter {
|
|
|
98
261
|
this.outboundServer.stop(),
|
|
99
262
|
this.oauthTestServer.stop(),
|
|
100
263
|
this.testServer.stop(),
|
|
264
|
+
this.controlClient.stop(),
|
|
265
|
+
this.metricsServer.stop(),
|
|
101
266
|
]);
|
|
102
267
|
}
|
|
103
268
|
}
|
|
104
269
|
|
|
270
|
+
/*
|
|
271
|
+
* Call the Connector Manager in Management API to get the updated config
|
|
272
|
+
*/
|
|
273
|
+
async function _GetUpdatedConfigFromMgmtAPI(conf, logger, client) {
|
|
274
|
+
logger.log(`Getting updated config from Management API at ${conf.control.mgmtAPIWsUrl}:${conf.control.mgmtAPIWsPort}...`);
|
|
275
|
+
const clientSendResponse = await client.send(ControlAgent.build.CONFIGURATION.READ());
|
|
276
|
+
logger.log('client send returned:: ', clientSendResponse);
|
|
277
|
+
const responseRead = await client.receive();
|
|
278
|
+
logger.log('client receive returned:: ', responseRead);
|
|
279
|
+
return responseRead.data;
|
|
280
|
+
}
|
|
105
281
|
|
|
106
282
|
if(require.main === module) {
|
|
107
283
|
(async () => {
|
|
@@ -115,6 +291,18 @@ if(require.main === module) {
|
|
|
115
291
|
},
|
|
116
292
|
stringify: Logger.buildStringify({ space: config.logIndent }),
|
|
117
293
|
});
|
|
294
|
+
if(config.pm4mlEnabled) {
|
|
295
|
+
const controlClient = await ControlAgent.Client.Create({
|
|
296
|
+
address: config.control.mgmtAPIWsUrl,
|
|
297
|
+
port: config.control.mgmtAPIWsPort,
|
|
298
|
+
logger: logger,
|
|
299
|
+
appConfig: config,
|
|
300
|
+
});
|
|
301
|
+
const updatedConfigFromMgmtAPI = await _GetUpdatedConfigFromMgmtAPI(config, logger, controlClient);
|
|
302
|
+
logger.log(`updatedConfigFromMgmtAPI: ${JSON.stringify(updatedConfigFromMgmtAPI)}`);
|
|
303
|
+
_.merge(config, updatedConfigFromMgmtAPI);
|
|
304
|
+
controlClient.terminate();
|
|
305
|
+
}
|
|
118
306
|
const svr = new Server(config, logger);
|
|
119
307
|
svr.on('error', (err) => {
|
|
120
308
|
logger.push({ err }).log('Unhandled server error');
|
|
@@ -140,9 +328,9 @@ if(require.main === module) {
|
|
|
140
328
|
// scheme adapter as a service
|
|
141
329
|
module.exports = {
|
|
142
330
|
Cache,
|
|
331
|
+
ControlAgent,
|
|
143
332
|
InboundServerMiddleware,
|
|
144
333
|
OutboundServerMiddleware,
|
|
145
|
-
RandomPhrase,
|
|
146
334
|
Router,
|
|
147
335
|
Server,
|
|
148
336
|
Validate,
|
package/src/lib/cache.js
CHANGED
|
@@ -21,8 +21,8 @@ const CONN_ST = {
|
|
|
21
21
|
};
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
* A shared cache abstraction over a REDIS distributed key/value store
|
|
25
|
+
*/
|
|
26
26
|
class Cache {
|
|
27
27
|
constructor(config) {
|
|
28
28
|
this._config = config;
|
|
@@ -53,12 +53,12 @@ class Cache {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
56
|
+
* Connects to a redis server and waits for ready events
|
|
57
|
+
* Note: We create two connections. One for get, set and publish commands
|
|
58
|
+
* and another for subscribe commands. We do this as we are not supposed
|
|
59
|
+
* to issue any non-pub/sub related commands on a connection used for sub
|
|
60
|
+
* See: https://redis.io/topics/pubsub
|
|
61
|
+
*/
|
|
62
62
|
async connect() {
|
|
63
63
|
switch(this._connectionState) {
|
|
64
64
|
case CONN_ST.CONNECTED:
|
|
@@ -74,7 +74,6 @@ class Cache {
|
|
|
74
74
|
await this._inProgressDisconnection;
|
|
75
75
|
break;
|
|
76
76
|
}
|
|
77
|
-
|
|
78
77
|
this._connectionState = CONN_ST.CONNECTING;
|
|
79
78
|
this._inProgressConnection = Promise.all([this._getClient(), this._getClient()]);
|
|
80
79
|
[this._client, this._subscriptionClient] = await this._inProgressConnection;
|
|
@@ -82,15 +81,19 @@ class Cache {
|
|
|
82
81
|
// hook up our sub message handler
|
|
83
82
|
this._subscriptionClient.on('message', this._onMessage.bind(this));
|
|
84
83
|
|
|
84
|
+
if (this._config.enableTestFeatures) {
|
|
85
|
+
this.setTestMode(true);
|
|
86
|
+
}
|
|
87
|
+
|
|
85
88
|
this._inProgressConnection = null;
|
|
86
89
|
this._connectionState = CONN_ST.CONNECTED;
|
|
87
90
|
}
|
|
88
91
|
|
|
89
92
|
/**
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
* Configure Redis to emit keyevent events. This corresponds to the application test mode, and
|
|
94
|
+
* enables us to listen for changes on callback_* and request_* keys.
|
|
95
|
+
* Docs: https://redis.io/topics/notifications
|
|
96
|
+
*/
|
|
94
97
|
async setTestMode(enable) {
|
|
95
98
|
// See for modes: https://redis.io/topics/notifications#configuration
|
|
96
99
|
// This mode, 'Es$' is:
|
|
@@ -100,7 +103,7 @@ class Cache {
|
|
|
100
103
|
const mode = enable ? 'Es$' : '';
|
|
101
104
|
this._logger
|
|
102
105
|
.push({ 'notify-keyspace-events': mode })
|
|
103
|
-
.log('
|
|
106
|
+
.log('Configuring Redis to emit keyevent events');
|
|
104
107
|
this._client.config('SET', 'notify-keyspace-events', mode);
|
|
105
108
|
}
|
|
106
109
|
|
|
@@ -133,12 +136,12 @@ class Cache {
|
|
|
133
136
|
|
|
134
137
|
|
|
135
138
|
/**
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
* Subscribes to a channel
|
|
140
|
+
*
|
|
141
|
+
* @param channel {string} - The channel name to subscribe to
|
|
142
|
+
* @param callback {function} - Callback function to be executed when messages arrive on the specified channel
|
|
143
|
+
* @returns {Promise} - Promise that resolves with an integer callback Id to submit in unsubscribe request
|
|
144
|
+
*/
|
|
142
145
|
async subscribe(channel, callback) {
|
|
143
146
|
return new Promise((resolve, reject) => {
|
|
144
147
|
this._subscriptionClient.subscribe(channel, (err) => {
|
|
@@ -168,11 +171,11 @@ class Cache {
|
|
|
168
171
|
|
|
169
172
|
|
|
170
173
|
/**
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
174
|
+
* Unsubscribes a callback from a channel
|
|
175
|
+
*
|
|
176
|
+
* @param channel {string} - name of the channel to unsubscribe from
|
|
177
|
+
* @param callbackId {integer} - id of the callback to remove
|
|
178
|
+
*/
|
|
176
179
|
async unsubscribe(channel, callbackId) {
|
|
177
180
|
return new Promise((resolve, reject) => {
|
|
178
181
|
if(this._callbacks[channel] && this._callbacks[channel][callbackId]) {
|
|
@@ -196,8 +199,8 @@ class Cache {
|
|
|
196
199
|
|
|
197
200
|
|
|
198
201
|
/**
|
|
199
|
-
|
|
200
|
-
|
|
202
|
+
* Handler for published messages
|
|
203
|
+
*/
|
|
201
204
|
async _onMessage(channel, msg) {
|
|
202
205
|
if(this._callbacks[channel]) {
|
|
203
206
|
// we have some callbacks to make
|
|
@@ -219,16 +222,16 @@ class Cache {
|
|
|
219
222
|
|
|
220
223
|
|
|
221
224
|
/**
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
225
|
+
* Returns a new redis client
|
|
226
|
+
*
|
|
227
|
+
* @returns {object} - a connected REDIS client
|
|
228
|
+
* */
|
|
226
229
|
async _getClient() {
|
|
227
230
|
return new Promise((resolve, reject) => {
|
|
228
231
|
const client = redis.createClient(this._config);
|
|
229
232
|
|
|
230
233
|
client.on('error', (err) => {
|
|
231
|
-
this._logger.push({ err }).log('REDIS client
|
|
234
|
+
this._logger.push({ err }).log('Error from REDIS client getting subscriber');
|
|
232
235
|
return reject(err);
|
|
233
236
|
});
|
|
234
237
|
|
|
@@ -247,25 +250,25 @@ class Cache {
|
|
|
247
250
|
}
|
|
248
251
|
});
|
|
249
252
|
|
|
250
|
-
client.on('ready', () => {
|
|
251
|
-
this._logger.log(`REDIS client ready at: ${this._config.host}:${this._config.port}`);
|
|
252
|
-
return resolve(client);
|
|
253
|
-
});
|
|
254
|
-
|
|
255
253
|
client.on('connect', () => {
|
|
256
254
|
this._logger.log(`REDIS client connected at: ${this._config.host}:${this._config.port}`);
|
|
257
255
|
});
|
|
256
|
+
|
|
257
|
+
client.on('ready', () => {
|
|
258
|
+
this._logger.log(`Connected to REDIS at: ${this._config.host}:${this._config.port}`);
|
|
259
|
+
return resolve(client);
|
|
260
|
+
});
|
|
258
261
|
});
|
|
259
262
|
}
|
|
260
263
|
|
|
261
264
|
|
|
262
265
|
/**
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
266
|
+
* Publishes the specified message to the specified channel
|
|
267
|
+
*
|
|
268
|
+
* @param channelName {string} - channel name to publish to
|
|
269
|
+
* @param value - any type that will be converted to a JSON string (unless it is already a string) and published as the message
|
|
270
|
+
* @returns {Promise} - Promise that will resolve with redis replies or reject with an error
|
|
271
|
+
*/
|
|
269
272
|
async publish(channelName, value) {
|
|
270
273
|
return new Promise((resolve, reject) => {
|
|
271
274
|
if(typeof(value) !== 'string') {
|
|
@@ -288,11 +291,11 @@ class Cache {
|
|
|
288
291
|
|
|
289
292
|
|
|
290
293
|
/**
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
294
|
+
* Sets a value in the cache
|
|
295
|
+
*
|
|
296
|
+
* @param key {string} - cache key
|
|
297
|
+
* @param value {stirng} - cache value
|
|
298
|
+
*/
|
|
296
299
|
async set(key, value) {
|
|
297
300
|
return new Promise((resolve, reject) => {
|
|
298
301
|
//if we are given an object, turn it into a string
|
|
@@ -313,10 +316,65 @@ class Cache {
|
|
|
313
316
|
}
|
|
314
317
|
|
|
315
318
|
/**
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
319
|
+
* Add the specified value to the set stored at key
|
|
320
|
+
*
|
|
321
|
+
* @param key {string} - cache key
|
|
322
|
+
* @param value {string} - cache value
|
|
323
|
+
*/
|
|
324
|
+
async add(key, value) {
|
|
325
|
+
return new Promise((resolve, reject) => {
|
|
326
|
+
//if we are given an object, turn it into a string
|
|
327
|
+
if(typeof(value) !== 'string') {
|
|
328
|
+
value = JSON.stringify(value);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
this._client.sadd(key, value, (err, replies) => {
|
|
332
|
+
if(err) {
|
|
333
|
+
this._logger.push({ key, value, err }).log(`Error setting cache key: ${key}`);
|
|
334
|
+
return reject(err);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
this._logger.push({ key, value, replies }).log(`Add cache key: ${key}`);
|
|
338
|
+
return resolve(replies);
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Returns all the members of the set value stored at key
|
|
345
|
+
*
|
|
346
|
+
* @param key {string} - cache key
|
|
347
|
+
*/
|
|
348
|
+
async members(key) {
|
|
349
|
+
return new Promise((resolve, reject) => {
|
|
350
|
+
this._client.smembers(key, (err, value) => {
|
|
351
|
+
if(err) {
|
|
352
|
+
this._logger.push({ key, err }).log(`Error getting cache key: ${key}`);
|
|
353
|
+
return reject(err);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
this._logger.push({ key, value }).log(`Got cache key: ${key}`);
|
|
357
|
+
|
|
358
|
+
if(typeof(value) === 'string') {
|
|
359
|
+
try {
|
|
360
|
+
value = JSON.parse(value);
|
|
361
|
+
}
|
|
362
|
+
catch(err) {
|
|
363
|
+
this._logger.push({ err }).log('Error parsing JSON cache value');
|
|
364
|
+
return reject(err);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
return resolve(value);
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Gets a value from the cache
|
|
375
|
+
*
|
|
376
|
+
* @param key {string} - cache key
|
|
377
|
+
*/
|
|
320
378
|
async get(key) {
|
|
321
379
|
return new Promise((resolve, reject) => {
|
|
322
380
|
this._client.get(key, (err, value) => {
|