Skip to content

Commit

Permalink
key used for throttling is now configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
jduff committed Jul 6, 2009
1 parent dfc678d commit 07b9cbd
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
1 change: 1 addition & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ begin
gemspec.homepage = "http://github.com/jduff/api-throttling/tree"
gemspec.description = "TODO"
gemspec.authors = ["Luc Castera", "John Duff"]
gemspec.add_development_dependency('context')
end
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
Expand Down
5 changes: 3 additions & 2 deletions lib/api_throttling.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def call(env, options={})

begin
cache = @handler.new(@options[:cache])
key = generate_key(auth)
key = generate_key(env, auth)
cache.increment(key)
return over_rate_limit if cache.get(key).to_i > @options[:requests_per_hour]
rescue Errno::ECONNREFUSED
Expand All @@ -30,7 +30,8 @@ def call(env, options={})
@app.call(env)
end

def generate_key(auth)
def generate_key(env, auth)
return @options[:key].call(env, auth) if @options[:key]
auth ? "#{auth.username}_#{Time.now.strftime("%Y-%m-%d-%H")}" : "#{Time.now.strftime("%Y-%m-%d-%H")}"
end

Expand Down
34 changes: 33 additions & 1 deletion test/test_api_throttling.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,39 @@ def test_should_not_require_authorization
end
end


context "with rate limit key based on url" do
def app
app = Rack::Builder.new {
use ApiThrottling, :requests_per_hour => 3,
:key=>Proc.new{ |env,auth| "#{auth.username}_#{env['PATH_INFO']}_#{Time.now.strftime("%Y-%m-%d-%H")}" }
run lambda {|env| [200, {'Content-Type' => 'text/plain', 'Content-Length' => '12'}, ["Hello World!"] ] }
}
end

test "should throttle requests based on the user and url called" do
authorize "joe", "secret"
3.times do
get '/'
assert_equal 200, last_response.status
end
get '/'
assert_equal 503, last_response.status

3.times do
get '/awesome'
assert_equal 200, last_response.status
end
get '/awesome'
assert_equal 503, last_response.status

authorize "luc", "secret"
get '/awesome'
assert_equal 200, last_response.status

get '/'
assert_equal 200, last_response.status
end
end
end

end

0 comments on commit 07b9cbd

Please sign in to comment.