forked from fippo/rtcstats-server
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapp.js
More file actions
364 lines (303 loc) · 9.76 KB
/
app.js
File metadata and controls
364 lines (303 loc) · 9.76 KB
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
const assert = require('assert').strict;
const config = require('config');
const fs = require('fs');
const http = require('http');
const https = require('https');
const path = require('path');
const { name: appName, version: appVersion } = require('../package');
const DumpPersister = require('./DumpPersister');
const OrphanFileHelper = require('./OrphanFileHelper');
const WsHandler = require('./WsHandler');
const AmplitudeConnector = require('./database/AmplitudeConnector');
const FeaturesPublisher = require('./database/FeaturesPublisher');
const FirehoseConnector = require('./database/FirehoseConnector');
const logger = require('./logging');
const PromCollector = require('./metrics/PromCollector');
const { getEnvName,
getIdealWorkerCount,
ResponseType,
obfuscatePII } = require('./utils/utils');
const AwsSecretManager = require('./webhooks/AwsSecretManager');
const WebhookSender = require('./webhooks/WebhookSender');
const WorkerPool = require('./worker-pool/WorkerPool');
let amplitude;
let featPublisher;
let webhookSender;
let secretManager;
let tempDumpPath;
const { s3, features: {
disableFeatExtraction,
reconnectTimeout,
sequenceNumberSendingInterval,
cleanupCronHour }
} = config;
const workerScriptPath = path.join(__dirname, './worker-pool/ExtractWorker.js');
const workerPool = new WorkerPool(workerScriptPath, getIdealWorkerCount());
logger.info('[App] worker pool:', workerPool);
const dumpPersister = new DumpPersister({
tempPath: getTempPath(),
s3,
disableFeatExtraction,
webhookSender,
config
});
const wsHandler = new WsHandler({
tempPath: getTempPath(),
reconnectTimeout,
sequenceNumberSendingInterval,
workerPool,
config
});
const orphanFileHelper = new OrphanFileHelper({
tempPath: getTempPath(),
reconnectTimeout,
wsHandler,
cleanupCronHour
});
workerPool.on(ResponseType.DONE, body => {
const { dumpInfo = {}, features = {} } = body;
const obfuscatedDumpInfo = obfuscatePII(dumpInfo);
try {
logger.info('[App] Handling DONE event for %o', obfuscatedDumpInfo);
const { metrics: { dsRequestBytes = 0,
dumpFileSizeBytes = 0,
otherRequestBytes = 0,
statsRequestBytes = 0,
sdpRequestBytes = 0,
sentimentRequestBytes = 0,
sessionDurationMs = 0,
totalProcessedBytes = 0,
totalProcessedCount = 0 } } = features;
PromCollector.processed.inc();
PromCollector.dsRequestSizeBytes.observe(dsRequestBytes);
PromCollector.otherRequestSizeBytes.observe(otherRequestBytes);
PromCollector.statsRequestSizeBytes.observe(statsRequestBytes);
PromCollector.sdpRequestSizeBytes.observe(sdpRequestBytes);
PromCollector.sessionDurationMs.observe(sessionDurationMs);
PromCollector.sentimentRequestSizeBytes.observe(sentimentRequestBytes);
PromCollector.totalProcessedBytes.observe(totalProcessedBytes);
PromCollector.totalProcessedCount.observe(totalProcessedCount);
PromCollector.dumpSize.observe(dumpFileSizeBytes);
amplitude?.track(dumpInfo, features);
featPublisher?.publish(body);
} catch (e) {
logger.error('[App] Handling DONE event error %o and body %o', e, obfuscatedDumpInfo);
}
dumpPersister.persistDumpData(dumpInfo);
});
workerPool.on(ResponseType.ERROR, body => {
const { dumpInfo = {}, error } = body;
const obfuscatedDumpInfo = obfuscatePII(dumpInfo);
logger.error('[App] Handling ERROR event for: %o, error: %o', obfuscatedDumpInfo, error);
PromCollector.processErrorCount.inc();
// If feature extraction failed at least attempt to store the dump in s3.
if (dumpInfo.clientId) {
dumpPersister.persistDumpData(dumpInfo);
} else {
logger.error('[App] Handling ERROR without a clientId field!');
}
});
/**
* Configure Amplitude backend
*/
function setupAmplitudeConnector() {
const { amplitude: { key } = {} } = config;
if (key) {
amplitude = new AmplitudeConnector(key);
} else {
logger.warn('[App] Amplitude is not configured!');
}
}
/**
* Initialize the service that will send extracted features to the configured database.
*/
function setupFeaturesPublisher() {
const {
firehose = {},
server: {
appEnvironment
}
} = config;
// We use the `region` as a sort of enabled/disabled flag, if this config is set then so to must all other
// parameters in the firehose config section, invariant check will fail otherwise and the server
// will fail to start.
if (firehose.region) {
const dbConnector = new FirehoseConnector(firehose);
featPublisher = new FeaturesPublisher(dbConnector, appEnvironment);
} else {
logger.warn('[App] Firehose is not configured!');
}
}
/**
*
*/
function getTempPath() {
// Temporary path for stats dumps must be configured.
const { server: { tempPath } } = config;
if (tempDumpPath === undefined) {
tempDumpPath = tempPath;
}
assert(tempDumpPath);
return tempDumpPath;
}
/**
* Initialize the directory where temporary dump files will be stored.
*/
function setupWorkDirectory() {
const tempPath = getTempPath();
try {
if (!fs.existsSync(tempPath)) {
logger.debug(`[App] Creating working dir ${tempPath}`);
fs.mkdirSync(tempPath);
}
} catch (e) {
logger.error(`[App] Error while accessing working dir ${tempPath} - ${e}`);
// The app is probably in an inconsistent state at this point, throw and stop process.
throw e;
}
}
/**
* Initialize http server exposing prometheus statistics.
*/
function setupMetricsServer() {
const { metrics: port } = config.get('server');
if (!port) {
logger.warn('[App] Metrics server is not configured!');
return;
}
const metricsServer = http
.createServer((request, response) => {
switch (request.url) {
case '/metrics':
PromCollector.queueSize.set(workerPool.getTaskQueueSize());
PromCollector.collectDefaultMetrics();
response.writeHead(200, { 'Content-Type': PromCollector.getPromContentType() });
response.end(PromCollector.metrics());
break;
default:
response.writeHead(404);
response.end();
}
})
.listen(port);
return metricsServer;
}
/**
* Handler used for basic availability checks.
*
* @param {*} request
* @param {*} response
*/
function serverHandler(request, response) {
switch (request.url) {
case '/healthcheck':
response.writeHead(200);
response.end();
break;
case '/bindcheck':
logger.info('Accessing bind check!');
response.writeHead(200);
response.end();
break;
default:
response.writeHead(404);
response.end();
}
}
/**
* In case one wants to run the server locally, https is required, as browsers normally won't allow non
* secure web sockets on a https domain, so something like the bello
* server instead of http.
*
* @param {number} port
*/
function setupHttpsServer(port) {
const { keyPath, certPath } = config.get('server');
if (!(keyPath && certPath)) {
throw new Error('[App] Please provide certificates for the https server!');
}
const options = {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
return https.createServer(options, serverHandler).listen(port);
}
/**
*
*/
function setupHttpServer(port) {
return http.createServer(serverHandler).listen(port);
}
/**
* Initialize the http or https server used for websocket connections.
*/
function setupWebServer() {
const { useHTTPS, port } = config.get('server');
if (!port) {
throw new Error('[App] Please provide a server port!');
}
let server;
if (useHTTPS) {
server = setupHttpsServer(port);
} else {
server = setupHttpServer(port);
}
wsHandler.setupWebSocketsServer(server);
}
/**
* Initialize service that sends webhooks through the JaaS Webhook API.
*/
async function setupWebhookSender() {
const { webhooks: { apiEndpoint } } = config;
// If an endpoint is configured enable the webhook sender.
if (apiEndpoint && secretManager) {
webhookSender = new WebhookSender(config, secretManager);
await webhookSender.init();
} else {
logger.warn('[App] Webhook sender is not configured');
}
}
/**
* Initialize service responsible with retrieving required secrets..
*/
function setupSecretManager() {
const { secretmanager: { region } = {} } = config;
if (region) {
secretManager = new AwsSecretManager(config);
} else {
logger.warn('[App] Secret manager is not configured');
}
}
/**
*
*/
async function startRtcstatsServer() {
logger.info('[App] Initializing: %s; version: %s; env: %s ...', appName, appVersion, getEnvName());
setupSecretManager();
await setupWebhookSender();
setupWorkDirectory();
orphanFileHelper.processOldFiles();
setupFeaturesPublisher();
setupAmplitudeConnector();
setupMetricsServer();
setupWebServer();
logger.info('[App] Initialization complete.');
}
/**
* Currently used from test script.
*/
function stop() {
process.exit();
}
// For now just log unhandled promise rejections, as the initial code did not take them into account and by default
// node just silently eats them.
process.on('unhandledRejection', reason => {
logger.error('[App] Unhandled rejection: %s', reason);
});
startRtcstatsServer();
module.exports = {
stop,
// We expose the number of processed items for use in the test script
PromCollector,
workerPool
};