1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-28 00:06:53 +01:00
unleash.unleash/lib/db/client-metrics-db.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

'use strict';
const METRICS_COLUMNS = ['id', 'created_at', 'metrics'];
const TABLE = 'client_metrics';
const ONE_MINUTE = 60 * 1000;
2017-06-28 10:17:14 +02:00
const mapRow = row => ({
id: row.id,
createdAt: row.created_at,
metrics: row.metrics,
});
class ClientMetricsDb {
constructor(db, getLogger) {
this.db = db;
this.logger = getLogger('client-metrics-db.js');
2016-12-04 14:09:37 +01:00
// Clear old metrics regulary
const clearer = () => this.removeMetricsOlderThanOneHour();
setTimeout(clearer, 10).unref();
setInterval(clearer, ONE_MINUTE).unref();
}
2020-09-18 09:05:09 +02:00
async removeMetricsOlderThanOneHour() {
const rows = await this.db(TABLE)
2017-06-28 10:17:14 +02:00
.whereRaw("created_at < now() - interval '1 hour'")
2020-09-18 09:05:09 +02:00
.del();
if (rows > 0) {
this.logger.debug(`Deleted ${rows} metrics`);
}
}
// Insert new client metrics
2020-09-18 09:05:09 +02:00
async insert(metrics) {
return this.db(TABLE).insert({ metrics });
}
// Used at startup to load all metrics last week into memory!
2020-09-18 09:05:09 +02:00
async getMetricsLastHour() {
const result = await this.db
.select(METRICS_COLUMNS)
.from(TABLE)
.limit(2000)
2017-06-28 10:17:14 +02:00
.whereRaw("created_at > now() - interval '1 hour'")
2020-09-18 09:05:09 +02:00
.orderBy('created_at', 'asc');
return result.map(mapRow);
}
// Used to poll for new metrics
2020-09-18 09:05:09 +02:00
async getNewMetrics(lastKnownId) {
const result = await this.db
.select(METRICS_COLUMNS)
.from(TABLE)
.limit(1000)
.where('id', '>', lastKnownId)
2020-09-18 09:05:09 +02:00
.orderBy('created_at', 'asc');
return result.map(mapRow);
}
2017-06-28 10:17:14 +02:00
}
module.exports = ClientMetricsDb;