Skip to content

Commit

Permalink
Added an atomic addCount to RateLimit
Browse files Browse the repository at this point in the history
  • Loading branch information
chriso committed May 19, 2011
1 parent 6ec4ba7 commit d69bc75
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
47 changes: 47 additions & 0 deletions lib/advanced_structures/RateLimit.js
Expand Up @@ -139,3 +139,50 @@ RateLimit.prototype.count = function (subject, interval, callback) {

return this;
}

/**
* An alias for `ratelimit.add(subject).count(subject, interval);`
*
* @param {string} subject
* @param {int} interval
* @param {Function} callback
* @return this
* @api public
*/

RateLimit.prototype.addCount = function (subject, interval, callback) {
var bucket = this.getBucket(),
multi = this.client.multi(),
count = Math.floor(interval / this.bucket_interval);

subject = this.key + ':' + subject;

//Increment the current bucket
multi.hincrby(subject, bucket, 1)

//Clear the buckets ahead
multi.hdel(subject, (bucket + 1) % this.bucket_count)
.hdel(subject, (bucket + 2) % this.bucket_count)

//Renew the key TTL
multi.expire(subject, this.subject_expiry);

//Get the counts from the previous `count` buckets
multi.hget(subject, bucket);
while (count--) {
multi.hget(subject, (--bucket + this.bucket_count) % this.bucket_count);
}

//Add up the counts from each bucket
multi.exec(function (err, counts) {
if (err) return callback(err, null);
for (var count = 0, i = 4, l = counts.length; i < l; i++) {
if (counts[i]) {
count += parseInt(counts[i], 10);
}
}
callback(null, count);
});

return this;
}
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{ "name" : "redback",
"description" : "A high-level Redis library",
"version" : "0.2.2",
"version" : "0.2.3",
"homepage" : "https://github.com/chriso/redback",
"author" : "Chris O'Hara <cohara87@gmail.com>",
"main" : "index",
Expand Down
2 changes: 1 addition & 1 deletion site/index.html
Expand Up @@ -78,7 +78,7 @@
#content h2 {
font-size: 24px;
margin: 28px 0 14px 0;
text-shadow: 1px 1px 1px rgba(20,20,20,0.3);
text-shadow: 1px 1px 1px rgba(20,20,20,0.2);
}
#content p {
padding-left: 2px;
Expand Down

0 comments on commit d69bc75

Please sign in to comment.