2016-11-28 17:11:11 +01:00
|
|
|
'use strict';
|
|
|
|
|
2017-08-04 16:03:15 +02:00
|
|
|
const logger = require('../logger')('client-metrics-db.js');
|
2016-11-28 17:11:11 +01:00
|
|
|
|
|
|
|
const METRICS_COLUMNS = ['id', 'created_at', 'metrics'];
|
|
|
|
const TABLE = 'client_metrics';
|
|
|
|
|
2017-09-07 22:52:24 +02:00
|
|
|
const ONE_MINUTE = 60 * 1000;
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
const mapRow = row => ({
|
2016-11-28 17:11:11 +01:00
|
|
|
id: row.id,
|
|
|
|
createdAt: row.created_at,
|
|
|
|
metrics: row.metrics,
|
|
|
|
});
|
|
|
|
|
|
|
|
class ClientMetricsDb {
|
2017-06-28 10:17:14 +02:00
|
|
|
constructor(db) {
|
2016-11-28 17:11:11 +01:00
|
|
|
this.db = db;
|
2016-12-04 14:09:37 +01:00
|
|
|
|
|
|
|
// Clear old metrics regulary
|
2017-09-07 22:52:24 +02:00
|
|
|
const clearer = () => this.removeMetricsOlderThanOneHour();
|
|
|
|
setTimeout(clearer, 10).unref();
|
|
|
|
setInterval(clearer, ONE_MINUTE).unref();
|
2016-11-28 17:11:11 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 10:17:14 +02:00
|
|
|
removeMetricsOlderThanOneHour() {
|
2016-11-28 17:11:11 +01:00
|
|
|
this.db(TABLE)
|
2017-06-28 10:17:14 +02:00
|
|
|
.whereRaw("created_at < now() - interval '1 hour'")
|
2016-11-28 17:11:11 +01:00
|
|
|
.del()
|
2017-06-28 10:17:14 +02:00
|
|
|
.then(res => res > 0 && logger.info(`Deleted ${res} metrics`));
|
2016-11-28 17:11:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Insert new client metrics
|
2017-06-28 10:17:14 +02:00
|
|
|
insert(metrics) {
|
2016-11-28 17:11:11 +01:00
|
|
|
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() {
|
2016-11-28 17:11:11 +01:00
|
|
|
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'")
|
2016-11-28 17:11:11 +01:00
|
|
|
.orderBy('created_at', 'asc')
|
|
|
|
.map(mapRow);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Used to poll for new metrics
|
2017-06-28 10:17:14 +02:00
|
|
|
getNewMetrics(lastKnownId) {
|
2016-11-28 17:11:11 +01:00
|
|
|
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
|
|
|
}
|
2016-11-28 17:11:11 +01:00
|
|
|
|
|
|
|
module.exports = ClientMetricsDb;
|