From 3fca4d67eccdf4c2126fb18bd6b995411fc9995d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Neuh=C3=A4user?= Date: Mon, 19 Oct 2015 17:04:53 +0200 Subject: [PATCH 1/2] Fixed out-of-sync ttls --- index.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 16df973..687c467 100644 --- a/index.js +++ b/index.js @@ -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(); @@ -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(); From 9831466040b01ab2f08b34c0338f17e2c8396e90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Neuh=C3=A4user?= Date: Tue, 20 Oct 2015 09:03:33 +0200 Subject: [PATCH 2/2] Added a test for out-of-sync ttls --- test/index.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/index.js b/test/index.js index acd5b46..5419f81 100644 --- a/test/index.js +++ b/test/index.js @@ -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() {