2016-11-05 13:36:44 +01:00
|
|
|
'use strict';
|
|
|
|
|
2017-08-04 16:03:15 +02:00
|
|
|
const logger = require('../logger')('client-metrics-store.js');
|
2016-11-05 13:36:44 +01:00
|
|
|
|
2016-11-28 17:11:11 +01:00
|
|
|
const { EventEmitter } = require('events');
|
2016-11-05 13:36:44 +01:00
|
|
|
|
2016-11-28 17:11:11 +01:00
|
|
|
const TEN_SECONDS = 10 * 1000;
|
2016-11-05 13:36:44 +01:00
|
|
|
|
2016-11-28 17:11:11 +01:00
|
|
|
class ClientMetricsStore extends EventEmitter {
|
2017-06-28 10:17:14 +02:00
|
|
|
constructor(metricsDb, pollInterval = TEN_SECONDS) {
|
2016-11-28 17:11:11 +01:00
|
|
|
super();
|
|
|
|
this.metricsDb = metricsDb;
|
|
|
|
this.highestIdSeen = 0;
|
|
|
|
|
2016-12-04 14:09:37 +01:00
|
|
|
// Build internal state
|
2017-06-28 10:17:14 +02:00
|
|
|
metricsDb
|
|
|
|
.getMetricsLastHour()
|
|
|
|
.then(metrics => this._emitMetrics(metrics))
|
2016-11-28 17:11:11 +01:00
|
|
|
.then(() => this._startPoller(pollInterval))
|
|
|
|
.then(() => this.emit('ready'))
|
2017-06-28 10:17:14 +02:00
|
|
|
.catch(err => logger.error(err));
|
2016-11-05 13:36:44 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
_startPoller(pollInterval) {
|
2016-11-28 17:11:11 +01:00
|
|
|
this.timer = setInterval(() => this._fetchNewAndEmit(), pollInterval);
|
|
|
|
this.timer.unref();
|
2016-11-05 13:36:44 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
_fetchNewAndEmit() {
|
|
|
|
this.metricsDb
|
|
|
|
.getNewMetrics(this.highestIdSeen)
|
|
|
|
.then(metrics => this._emitMetrics(metrics));
|
2016-11-05 13:36:44 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
_emitMetrics(metrics) {
|
2016-11-28 17:11:11 +01:00
|
|
|
if (metrics && metrics.length > 0) {
|
|
|
|
this.highestIdSeen = metrics[metrics.length - 1].id;
|
|
|
|
metrics.forEach(m => this.emit('metrics', m.metrics));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert new client metrics
|
2017-06-28 10:17:14 +02:00
|
|
|
insert(metrics) {
|
2016-12-04 14:09:37 +01:00
|
|
|
return this.metricsDb.insert(metrics);
|
2016-11-05 13:36:44 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
destroy() {
|
2016-11-28 17:11:11 +01:00
|
|
|
try {
|
|
|
|
clearInterval(this.timer);
|
2017-11-11 08:43:08 +01:00
|
|
|
} catch (e) {
|
|
|
|
// empty
|
|
|
|
}
|
2016-11-05 13:36:44 +01:00
|
|
|
}
|
2017-06-28 10:17:14 +02:00
|
|
|
}
|
2016-11-05 13:36:44 +01:00
|
|
|
|
|
|
|
module.exports = ClientMetricsStore;
|