-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(bandwith_throttling): Adds a throttling middleware to keep bots …
…out of the api
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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 |