2016-11-28 17:11:11 +01:00
|
|
|
'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 => ({
|
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
|
2016-11-28 17:11:11 +01:00
|
|
|
setTimeout(() => this.removeMetricsOlderThanOneHour(), 10).unref();
|
2017-06-28 10:17:14 +02:00
|
|
|
setInterval(
|
|
|
|
() => this.removeMetricsOlderThanOneHour(),
|
|
|
|
60 * 1000
|
|
|
|
).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;
|