-
Notifications
You must be signed in to change notification settings - Fork 26
/
index.js
385 lines (349 loc) · 15.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/**************************************************************************
* (C) Copyright ModusBox Inc. 2019 - All rights reserved. *
* *
* This file is made available under the terms of the license agreement *
* specified in the corresponding source code repository. *
* *
* ORIGINAL AUTHOR: *
* James Bush - james.bush@modusbox.com *
**************************************************************************/
'use strict';
const { hostname } = require('os');
const EventEmitter = require('events');
const _ = require('lodash');
const { Logger } = require('@mojaloop/sdk-standard-components');
const config = require('./config');
const InboundServer = require('./InboundServer');
const OutboundServer = require('./OutboundServer');
const OAuthTestServer = require('./OAuthTestServer');
const { BackendEventHandler } = require('./BackendEventHandler');
const { FSPIOPEventHandler } = require('./FSPIOPEventHandler');
const TestServer = require('./TestServer');
const { MetricsServer, MetricsClient } = require('./lib/metrics');
const ControlAgent = require('./ControlAgent');
// import things we want to expose e.g. for unit tests and users who dont want to use the entire
// scheme adapter as a service
const InboundServerMiddleware = require('./InboundServer/middlewares.js');
const OutboundServerMiddleware = require('./OutboundServer/middlewares.js');
const Router = require('./lib/router');
const Validate = require('./lib/validate');
const Cache = require('./lib/cache');
const { SDKStateEnum } = require('./lib/model/common');
const { createAuthClient } = require('./lib/utils');
const LOG_ID = {
INBOUND: { app: 'mojaloop-connector-inbound-api' },
OUTBOUND: { app: 'mojaloop-connector-outbound-api' },
BACKEND_EVENT_HANDLER: { app: 'backend-event-handler' },
FSPIOP_EVENT_HANDLER: { app: 'fspiop-event-handler' },
TEST: { app: 'mojaloop-connector-test-api' },
OAUTHTEST: { app: 'mojaloop-connector-oauth-test-server' },
CONTROL: { app: 'mojaloop-connector-control-client' },
METRICS: { app: 'mojaloop-connector-metrics' },
CACHE: { component: 'cache' },
};
/**
* Class that creates and manages http servers that expose the scheme adapter APIs.
*/
class Server extends EventEmitter {
constructor(conf, logger) {
super({ captureExceptions: true });
this.conf = conf;
this.logger = logger;
this.cache = new Cache({
cacheUrl: conf.cacheUrl,
logger: this.logger.push(LOG_ID.CACHE),
enableTestFeatures: conf.enableTestFeatures,
});
this.metricsClient = new MetricsClient();
this.metricsServer = new MetricsServer({
port: this.conf.metrics.port,
logger: this.logger.push(LOG_ID.METRICS)
});
this.wso2 = createAuthClient(conf, logger);
this.wso2.auth.on('error', (msg) => {
this.emit('error', 'WSO2 auth error in InboundApi', msg);
});
this.inboundServer = new InboundServer(
this.conf,
this.logger.push(LOG_ID.INBOUND),
this.cache,
this.wso2,
);
this.inboundServer.on('error', (...args) => {
this.logger.push({ args }).log('Unhandled error in Inbound Server');
this.emit('error', 'Unhandled error in Inbound Server');
});
this.outboundServer = new OutboundServer(
this.conf,
this.logger.push(LOG_ID.OUTBOUND),
this.cache,
this.metricsClient,
this.wso2,
);
this.outboundServer.on('error', (...args) => {
this.logger.push({ args }).log('Unhandled error in Outbound Server');
this.emit('error', 'Unhandled error in Outbound Server');
});
if (this.conf.oauthTestServer.enabled) {
this.oauthTestServer = new OAuthTestServer({
clientKey: this.conf.oauthTestServer.clientKey,
clientSecret: this.conf.oauthTestServer.clientSecret,
port: this.conf.oauthTestServer.listenPort,
logger: this.logger.push(LOG_ID.OAUTHTEST),
});
}
if (this.conf.enableTestFeatures) {
this.testServer = new TestServer({
port: this.conf.test.port,
logger: this.logger.push(LOG_ID.TEST),
cache: this.cache,
});
}
if (this.conf.backendEventHandler.enabled) {
this.backendEventHandler = new BackendEventHandler({
config: this.conf,
logger: this.logger.push(LOG_ID.BACKEND_EVENT_HANDLER),
});
}
if (this.conf.fspiopEventHandler.enabled) {
this.fspiopEventHandler = new FSPIOPEventHandler({
config: this.conf,
logger: this.logger.push(LOG_ID.FSPIOP_EVENT_HANDLER),
cache: this.cache,
wso2: this.wso2,
});
}
}
async start() {
await this.cache.connect();
await this.wso2.auth.start();
// We only start the control client if we're running within Mojaloop Payment Manager.
// The control server is the Payment Manager Management API Service.
// We only start the client to connect to and listen to the Management API service for
// management protocol messages e.g configuration changes, certicate updates etc.
if (this.conf.pm4mlEnabled) {
const RESTART_INTERVAL_MS = 10000;
this.controlClient = await ControlAgent.Client.Create({
address: this.conf.control.mgmtAPIWsUrl,
port: this.conf.control.mgmtAPIWsPort,
logger: this.logger.push(LOG_ID.CONTROL),
appConfig: this.conf,
});
this.controlClient.on(ControlAgent.EVENT.RECONFIGURE, this.restart.bind(this));
this.controlClient.on('close', () => setTimeout(() => this.restart(_.merge({}, this.conf, { control: { stopped: Date.now() } })), RESTART_INTERVAL_MS));
}
await Promise.all([
this.inboundServer.start(),
this.outboundServer.start(),
this.metricsServer.start(),
this.testServer?.start(),
this.oauthTestServer?.start(),
this.backendEventHandler?.start(),
this.fspiopEventHandler?.start(),
]);
}
async restart(newConf) {
const updateLogger = !_.isEqual(newConf.logIndent, this.conf.logIndent);
if (updateLogger) {
this.logger = new Logger.Logger({
context: {
// If we're running from a Mojaloop helm chart deployment, we'll have a SIM_NAME
simulator: process.env['SIM_NAME'],
hostname: hostname(),
},
stringify: Logger.buildStringify({ space: this.conf.logIndent }),
});
}
let oldCache;
const updateCache = !_.isEqual(this.conf.cacheUrl, newConf.cacheUrl)
|| !_.isEqual(this.conf.enableTestFeatures, newConf.enableTestFeatures);
if (updateCache) {
oldCache = this.cache;
await this.cache.disconnect();
this.cache = new Cache({
cacheUrl: newConf.cacheUrl,
logger: this.logger.push(LOG_ID.CACHE),
enableTestFeatures: newConf.enableTestFeatures,
});
await this.cache.connect();
}
const updateWSO2 = !_.isEqual(this.conf.wso2, newConf.wso2)
|| !_.isEqual(this.conf.outbound.tls, newConf.outbound.tls);
if (updateWSO2) {
this.wso2.auth.stop();
this.wso2 = createAuthClient(newConf, this.logger);
this.wso2.auth.on('error', (msg) => {
this.emit('error', 'WSO2 auth error in InboundApi', msg);
});
await this.wso2.auth.start();
}
const updateInboundServer = !_.isEqual(this.conf.inbound, newConf.inbound)
|| !_.isEqual(this.conf.outbound, newConf.outbound);
if (updateInboundServer) {
await this.inboundServer.stop();
this.inboundServer = new InboundServer(
newConf,
this.logger.push(LOG_ID.INBOUND),
this.cache,
this.wso2,
);
this.inboundServer.on('error', (...args) => {
this.logger.push({ args }).log('Unhandled error in Inbound Server');
this.emit('error', 'Unhandled error in Inbound Server');
});
await this.inboundServer.start();
}
const updateOutboundServer = !_.isEqual(this.conf.outbound, newConf.outbound);
if (updateOutboundServer) {
await this.outboundServer.stop();
this.outboundServer = new OutboundServer(
newConf,
this.logger.push(LOG_ID.OUTBOUND),
this.cache,
this.metricsClient,
this.wso2,
);
this.outboundServer.on('error', (...args) => {
this.logger.push({ args }).log('Unhandled error in Outbound Server');
this.emit('error', 'Unhandled error in Outbound Server');
});
await this.outboundServer.start();
}
const updateFspiopEventHandler = !_.isEqual(this.conf.outbound, newConf.outbound)
&& this.conf.fspiopEventHandler.enabled;
if (updateFspiopEventHandler) {
await this.fspiopEventHandler.stop();
this.fspiopEventHandler = new FSPIOPEventHandler({
config: newConf,
logger: this.logger.push(LOG_ID.FSPIOP_EVENT_HANDLER),
cache: this.cache,
wso2: this.wso2,
});
await this.fspiopEventHandler.start();
}
const updateControlClient = !_.isEqual(this.conf.control, newConf.control);
if (updateControlClient) {
await this.controlClient?.stop();
if (this.conf.pm4mlEnabled) {
const RESTART_INTERVAL_MS = 10000;
this.controlClient = await ControlAgent.Client.Create({
address: newConf.control.mgmtAPIWsUrl,
port: newConf.control.mgmtAPIWsPort,
logger: this.logger.push(LOG_ID.CONTROL),
appConfig: newConf,
});
this.controlClient.on(ControlAgent.EVENT.RECONFIGURE, this.restart.bind(this));
this.controlClient.on('close', () => setTimeout(() => this.restart(_.merge({}, newConf, { control: { stopped: Date.now() } })), RESTART_INTERVAL_MS));
}
}
const updateOAuthTestServer = !_.isEqual(newConf.oauthTestServer, this.conf.oauthTestServer);
if (updateOAuthTestServer) {
await this.oauthTestServer?.stop();
if (this.conf.oauthTestServer.enabled) {
this.oauthTestServer = new OAuthTestServer({
clientKey: newConf.oauthTestServer.clientKey,
clientSecret: newConf.oauthTestServer.clientSecret,
port: newConf.oauthTestServer.listenPort,
logger: this.logger.push(LOG_ID.OAUTHTEST),
});
await this.oauthTestServer.start();
}
}
const updateTestServer = !_.isEqual(newConf.test.port, this.conf.test.port);
if (updateTestServer) {
await this.testServer?.stop();
if (this.conf.enableTestFeatures) {
this.testServer = new TestServer({
port: newConf.test.port,
logger: this.logger.push(LOG_ID.TEST),
cache: this.cache,
});
await this.testServer.start();
}
}
this.conf = newConf;
await Promise.all([
oldCache?.disconnect(),
]);
}
stop() {
this.wso2.auth.stop();
this.controlClient?.removeAllListeners();
this.inboundServer.removeAllListeners();
return Promise.all([
this.cache.disconnect(),
this.inboundServer.stop(),
this.outboundServer.stop(),
this.oauthTestServer?.stop(),
this.testServer?.stop(),
this.controlClient?.stop(),
this.metricsServer.stop(),
this.backendEventHandler?.stop(),
this.fspiopEventHandler?.stop(),
]);
}
}
/*
* Call the Connector Manager in Management API to get the updated config
*/
async function _GetUpdatedConfigFromMgmtAPI(conf, logger, client) {
logger.log(`Getting updated config from Management API at ${conf.control.mgmtAPIWsUrl}:${conf.control.mgmtAPIWsPort}...`);
const clientSendResponse = await client.send(ControlAgent.build.CONFIGURATION.READ());
logger.log('client send returned:: ', clientSendResponse);
const responseRead = await client.receive();
logger.log('client receive returned:: ', responseRead);
return responseRead.data;
}
if(require.main === module) {
(async () => {
// this module is main i.e. we were started as a server;
// not used in unit test or "require" scenarios
const logger = new Logger.Logger({
context: {
// If we're running from a Mojaloop helm chart deployment, we'll have a SIM_NAME
simulator: process.env['SIM_NAME'],
hostname: hostname(),
},
stringify: Logger.buildStringify({ space: config.logIndent }),
});
if(config.pm4mlEnabled) {
const controlClient = await ControlAgent.Client.Create({
address: config.control.mgmtAPIWsUrl,
port: config.control.mgmtAPIWsPort,
logger: logger,
appConfig: config,
});
const updatedConfigFromMgmtAPI = await _GetUpdatedConfigFromMgmtAPI(config, logger, controlClient);
logger.log(`updatedConfigFromMgmtAPI: ${JSON.stringify(updatedConfigFromMgmtAPI)}`);
_.merge(config, updatedConfigFromMgmtAPI);
controlClient.terminate();
}
const svr = new Server(config, logger);
svr.on('error', (err) => {
logger.push({ err }).log('Unhandled server error');
process.exit(1);
});
// handle SIGTERM to exit gracefully
process.on('SIGTERM', async () => {
logger.log('SIGTERM received. Shutting down APIs...');
await svr.stop();
process.exit(0);
});
svr.start().catch(err => {
logger.push({ err }).log('Error starting server');
process.exit(1);
});
})();
}
// export things we want to expose e.g. for unit tests and users who dont want to use the entire
// scheme adapter as a service
module.exports = {
Cache,
ControlAgent,
InboundServerMiddleware,
OutboundServerMiddleware,
Router,
Server,
Validate,
SDKStateEnum,
};