Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

key used for throttling is now configurable

  • Loading branch information...
commit 07b9cbd615126d4043741afc01fcfaee65a0cab2 1 parent dfc678d
@jduff jduff authored
Showing with 37 additions and 3 deletions.
  1. +1 −0  Rakefile
  2. +3 −2 lib/api_throttling.rb
  3. +33 −1 test/test_api_throttling.rb
View
1  Rakefile
@@ -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"
View
5 lib/api_throttling.rb
@@ -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
@@ -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
View
34 test/test_api_throttling.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.