1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/lib/db/client-metrics-store.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-11-05 13:36:44 +01:00
'use strict';
const logger = require('../logger')('client-metrics-store.js');
2016-11-05 13:36:44 +01:00
const { EventEmitter } = require('events');
2016-11-05 13:36:44 +01:00
const TEN_SECONDS = 10 * 1000;
2016-11-05 13:36:44 +01:00
class ClientMetricsStore extends EventEmitter {
2017-06-28 10:17:14 +02:00
constructor(metricsDb, pollInterval = TEN_SECONDS) {
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))
.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) {
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) {
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() {
try {
clearInterval(this.timer);
} catch (e) {}
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;