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

60 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-11-04 16:16:55 +01:00
'use strict';
const { EventEmitter } = require('events');
2016-11-06 20:52:08 +01:00
const List = require('./list');
2016-11-04 16:16:55 +01:00
const moment = require('moment');
2016-11-06 20:52:08 +01:00
// this list must have entries with sorted ttl range
module.exports = class TTLList extends EventEmitter {
2016-11-06 20:52:08 +01:00
constructor ({
interval = 1000,
expireAmount = 1,
expireType = 'hours',
} = {}) {
2016-11-04 16:16:55 +01:00
super();
this.interval = interval;
2016-11-06 20:52:08 +01:00
this.expireAmount = expireAmount;
this.expireType = expireType;
this.list = new List();
this.list.on('evicted', ({ value, ttl }) => {
this.emit('expire', value, ttl);
});
this.startTimer();
}
2016-11-04 16:16:55 +01:00
startTimer () {
if (this.list) {
this.timer = setTimeout(() => {
if (this.list) {
this.timedCheck();
}
}, this.interval);
this.timer.unref();
}
2016-11-04 16:16:55 +01:00
}
2016-11-06 20:52:08 +01:00
add (value, timestamp = new Date()) {
const ttl = moment(timestamp).add(this.expireAmount, this.expireType);
if (moment().isBefore(ttl)) {
this.list.add({ ttl, value });
} else {
this.emit('expire', value, ttl);
}
2016-11-04 16:16:55 +01:00
}
timedCheck () {
const now = moment();
2016-11-06 20:52:08 +01:00
this.list.reverseRemoveUntilTrue(({ value }) => now.isBefore(value.ttl));
this.startTimer();
2016-11-06 20:52:08 +01:00
}
destroy () {
// https://github.com/nodejs/node/issues/9561
// clearTimeout(this.timer);
// this.timer = null;
2016-11-06 20:52:08 +01:00
this.list = null;
2016-11-04 16:16:55 +01:00
}
2016-11-04 23:09:50 +01:00
};