Skip to content

Commit

Permalink
Expire entries when caches request eviction
Browse files Browse the repository at this point in the history
  • Loading branch information
aholstenson committed Jun 14, 2017
1 parent eb618b1 commit 38c5129
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
13 changes: 7 additions & 6 deletions cache/expire-after-write.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const { DATA, ON_REMOVE } = require('./symbols');
const { DATA, ON_REMOVE, EVICT } = require('./symbols');
const RemovalCause = require('../utils/removal-cause');
const TimerWheel = require('../utils/timer-wheel');

Expand All @@ -14,9 +14,7 @@ module.exports = ParentCache => class ExpireAfterWriteCache extends ParentCache
super(options);

this[DATA].maxWriteAge = options.maxWriteAge;
this[DATA].timerWheel = new TimerWheel(keys => setImmediate(
() => keys.forEach(key => this.delete(key))
));
this[DATA].timerWheel = new TimerWheel(keys => keys.forEach(key => this.delete(key)));
}

set(key, value) {
Expand All @@ -31,8 +29,6 @@ module.exports = ParentCache => class ExpireAfterWriteCache extends ParentCache
}

try {
timerWheel.advance();

const replaced = super.set(key, node);
return replaced ? replaced.value : null;
} catch(ex) {
Expand Down Expand Up @@ -73,4 +69,9 @@ module.exports = ParentCache => class ExpireAfterWriteCache extends ParentCache
}
super[ON_REMOVE](key, value.value, cause);
}

[EVICT]() {
this[DATA].timerWheel.advance();
super[EVICT]();
}
};
14 changes: 13 additions & 1 deletion test/expire-after-write.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const RemovalCause = require('../utils/removal-cause');
const newCache = (listener) => {
let Impl = ExpireAfterWriteCache(BoundlessCache);
return new Impl({
maxWriteAge: () => 5,
maxWriteAge: () => 10,
removalListener: listener
});
};
Expand Down Expand Up @@ -49,6 +49,18 @@ describe('ExpireAfterWriteCache', function() {
}, 20);
});

it('Set evicts old keys', function(cb) {
const cache = newCache();
cache.set('key', 'value');

setTimeout(() => {
cache.set('key2', 'value');
cache.__await();
expect(cache.size).to.equal(1);
cb();
}, 1080);
});

describe('Removal listeners', function() {
it('Triggers on delete', function() {
const listener = removalListener();
Expand Down
2 changes: 1 addition & 1 deletion utils/timer-wheel.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ module.exports = class TimerWheel {
*/
schedule(node, time) {
node.remove();
node.time = time;
node.time = this.localTime + time;

const parent = this._findBucket(node);
if(! parent) return null;
Expand Down

0 comments on commit 38c5129

Please sign in to comment.