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

54 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-11-05 13:36:44 +01:00
'use strict';
const logger = require('../logger');
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 {
constructor (metricsDb, pollInterval = TEN_SECONDS) {
super();
this.metricsDb = metricsDb;
this.highestIdSeen = 0;
2016-12-04 14:09:37 +01:00
// Build internal state
metricsDb.getMetricsLastHour()
.then((metrics) => this._emitMetrics(metrics))
.then(() => this._startPoller(pollInterval))
.then(() => this.emit('ready'))
.catch((err) => logger.error(err));
2016-11-05 13:36:44 +01:00
}
_startPoller (pollInterval) {
this.timer = setInterval(() => this._fetchNewAndEmit(), pollInterval);
this.timer.unref();
2016-11-05 13:36:44 +01:00
}
2016-12-04 14:09:37 +01:00
_fetchNewAndEmit () {
this.metricsDb.getNewMetrics(this.highestIdSeen)
2016-12-04 14:09:37 +01:00
.then((metrics) => this._emitMetrics(metrics));
2016-11-05 13:36:44 +01: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
insert (metrics) {
2016-12-04 14:09:37 +01:00
return this.metricsDb.insert(metrics);
2016-11-05 13:36:44 +01:00
}
2016-12-04 14:09:37 +01:00
destroy () {
try {
clearInterval(this.timer);
} catch (e) {}
2016-11-05 13:36:44 +01:00
}
};
module.exports = ClientMetricsStore;