Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes out-of-sync TTLs after running decr() #13

Merged
merged 2 commits into from
Oct 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ Limiter.prototype.get = function (fn) {
var n = ~~res[0];
var max = ~~res[1];
var ex = ~~res[2];
var dateNow = Date.now();

if (n <= 0) return done();

Expand All @@ -103,7 +104,9 @@ Limiter.prototype.get = function (fn) {
}

db.multi()
.set([count, n - 1, 'PX', ex * 1000 - Date.now(), 'XX'])
.set([count, n - 1, 'PX', ex * 1000 - dateNow, 'XX'])
.pexpire([limit, ex * 1000 - dateNow])
.pexpire([reset, ex * 1000 - dateNow])
.exec(function (err, res) {
if (err) return fn(err);
if (isFirstReplyNull(res)) return mget();
Expand Down
24 changes: 24 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,30 @@ var Limiter = require('..');
done();
});
});
it('updating the count should keep all TTLs in sync', function(done) {
var limit = new Limiter({
duration: 10000,
max: 2,
id: 'something',
db: db
});
limit.get(function(err, res) {}); // All good here.
limit.get(function(err, res) {
db.multi()
.pttl(['limit:something:count'])
.pttl(['limit:something:limit'])
.pttl(['limit:something:reset'])
.exec(function (err, res) {
if (err) return done(err);
var ttlCount = (typeof res[0] === 'number') ? res[0] : res[0][1];
var ttlLimit = (typeof res[1] === 'number') ? res[1] : res[1][1];
var ttlReset = (typeof res[2] === 'number') ? res[2] : res[2][1];
ttlLimit.should.equal(ttlCount);
ttlReset.should.equal(ttlCount);
done();
});
});
});
});

describe('when trying to decrease before setting value', function() {
Expand Down