Created
October 5, 2011 07:40
-
-
Save gjohnson/1263873 to your computer and use it in GitHub Desktop.
cluster throttle idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var utils = require('cluster/lib/utils'); | |
var redis = require('redis'); | |
var rc = redis.createClient(); | |
exports = module.exports = function(options) { | |
ratelimit.enableInWorker = true; | |
options = options || {}; | |
var interval = options.interval = (options.interval || 1); | |
var now = function () { | |
return (new Date).getTime() / 1000; | |
}; | |
function ratelimit(master) { | |
var server = master.server; | |
var listeners = server.listeners('request'); | |
if (master.isWorker) { | |
server.removeAllListeners('request'); | |
server.on('request', function(req, res) { | |
var ctx = this; | |
var id = req.connection.remoteAddress + req.headers['user-agent']; | |
rc.getset(id, now(), function(err, then) { | |
if (then && (now() - then) < interval) { | |
res.writeHead(500); | |
res.end(); | |
} else { | |
listeners.forEach(function(fn) { | |
fn.call(ctx, req, res); | |
}); | |
} | |
}); | |
}); | |
} | |
} | |
return ratelimit; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment