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 4b06b93
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/yodatra/api_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def _call(env)

status, headers, response = @block.yield(status, headers, response) unless @block.nil?

headers['Content-Length'] = response.first.length.to_s unless response.nil? || response.first.nil?
headers['Content-Length'] = response.first.length.to_s unless response.nil? || !response.respond_to?(:first) || response.first.nil?

[status, headers, response]
end
Expand Down
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 4b06b93

Please sign in to comment.