Skip to content

Commit

Permalink
feat(bandwith_throttling): Adds a throttling middleware to keep bots …
Browse files Browse the repository at this point in the history
…out of the api
  • Loading branch information
paulRbr committed Mar 2, 2014
1 parent ecffaf4 commit 6b366d4
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/yodatra/throttling.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
begin
require 'redis'

module Yodatra
class Throttle
def initialize(app, *opts)
@app = app
@redis = Redis.new opts[:redis_conf]
@rpm = opts[:rpm] || 100
end

def call(env)
req = Rack::Request.new(env)
key = "throttle:#{req.ip}"
@redis.incr(key) == 1 && @redis.expire(key, 60)
if @redis.get(key).to_i > @rpm
Rack::Response.new('Too many API calls', 403)
else
@app.call(env)
end
end
end
end
rescue LoadError
raise "Error: in order to use Yodatra's throttling middleware you will need Redis. Add 'redis' to your Gemfile or simply gem install 'redis'"
end

0 comments on commit 6b366d4

Please sign in to comment.