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

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-11-05 13:36:44 +01:00
'use strict';
const { EventEmitter } = require('events');
2019-08-04 11:15:40 +02:00
const metricsHelper = require('../metrics-helper');
const { DB_TIME } = 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, eventBus, getLogger, pollInterval = TEN_SECONDS) {
super();
this.logger = getLogger('client-metrics-store.js');
this.metricsDb = metricsDb;
this.eventBus = eventBus;
this.highestIdSeen = 0;
2020-09-18 09:05:09 +02:00
this.startTimer = action =>
metricsHelper.wrapTimer(eventBus, DB_TIME, {
store: 'metrics',
action,
});
this._init(pollInterval);
}
async _init(pollInterval) {
try {
const metrics = await this.metricsDb.getMetricsLastHour();
this._emitMetrics(metrics);
} catch (err) {
this.logger.error('Error fetching metrics last hour', err);
}
this._startPoller(pollInterval);
this.emit('ready');
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
2020-09-18 09:05:09 +02:00
async insert(metrics) {
const stopTimer = this.startTimer('insert');
await this.metricsDb.insert(metrics);
stopTimer();
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;