Skip to content

Commit

Permalink
allow a discrete refilling rate
Browse files Browse the repository at this point in the history
  • Loading branch information
jfromaniello committed Apr 26, 2017
1 parent b13186a commit 504a1ad
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ function normalizeType(params) {
'per_interval',
'interval',
'size',
'unlimited'
'unlimited',
'discrete'
]);

INTERVAL_SHORTCUTS.forEach(ish => {
Expand Down Expand Up @@ -100,7 +101,11 @@ class LimitDB {
const now = Date.now();
const deltaMS = Math.max(now - bucket.lastDrip, 0);
const dripAmount = deltaMS * (type.per_interval / type.interval);
const content = Math.min(bucket.content + dripAmount, type.size);
var content = bucket.content;

if (!type.discrete || dripAmount >= type.per_interval) {
content = Math.floor(Math.min(bucket.content + dripAmount, type.size));
}

return {
content: content,
Expand Down Expand Up @@ -204,7 +209,7 @@ class LimitDB {
if (err) { return callback(err); }
callback(null, {
conformant: bucket.lastConformant,
remaining: Math.floor(bucket.content),
remaining: bucket.content,
reset: bucket.reset,
limit: typeParams.size
});
Expand Down
46 changes: 46 additions & 0 deletions test/discrete_example.tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const LimitDB = require('../lib/db');
const MockDate = require('mockdate');
const assert = require('chai').assert;

const types = {
ip: {
size: 5,
per_interval: 5,
interval: 500,
discrete: true
}
};

describe('when the fill rate is discrete', () => {
afterEach(function () {
MockDate.reset();
});

const db = new LimitDB({
inMemory: true,
types
});

beforeEach(function(done) {
MockDate.set(Date.now());
db.take({ type: 'ip', key: '21.17.65.41', count: 5 }, done);
});

it('should not add less than the per_interval amount', function(done) {
MockDate.set(Date.now() + 150);
db.status({ type: 'ip', prefix: '21.17.65.41' }, (err, result) => {
if (err) { return done(err); }
assert.equal(result.items[0].remaining, 0);
done();
});
});

it('should add the per_interval amount after the elapsed interval', function(done) {
MockDate.set(Date.now() + 500);
db.status({ type: 'ip', prefix: '21.17.65.41' }, (err, result) => {
if (err) { return done(err); }
assert.equal(result.items[0].remaining, 5);
done();
});
});
});

0 comments on commit 504a1ad

Please sign in to comment.