1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00
unleash.unleash/lib/db/client-metrics-store.js

57 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);
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;