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

62 lines
1.5 KiB
JavaScript
Raw Normal View History

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