prorate 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: d846e16d888b11395f59a44e8d487e9c3cccf336
4
+ data.tar.gz: 16051a7c67452164d40c3d8c785a26b973eaf54e
5
+ SHA512:
6
+ metadata.gz: b241b77bf6ec18bd394a0360bebd6b9e10b3b0cde21f1642860b0425d33b8b3a50dbaba9a5fe4fd7b5595dd95a566dfe122939a94711b651afec125e3ecfcc94
7
+ data.tar.gz: 1f110ef412d5c231f1eed8550f3957c4fc9797eef42f3a92de802b2be1d15b06c450b1913706c036dd30924925acfce410ec29adf495539ea0dd08763f904d50
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.5
5
+ before_install: gem install bundler -v 1.12.5
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in prorate.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Julik Tarkhanov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # Prorate
2
+
3
+ Provides a low-level time-based throttle. Is mainly meant for situations where using something like Rack::Attack is not very
4
+ useful since you need access to more variables.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'prorate'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install prorate
21
+
22
+ ## Usage
23
+
24
+ Within your Rails controller:
25
+
26
+ throttle_args[:block_for] ||= throttle_args.fetch(:period)
27
+ t = Prorate::Throttle.new(redis: Redis.new, logger: Rails.logger,
28
+ name: "throttle-login-email", limit: 20, period: 5.seconds)
29
+ # Add all the parameters that function as a discriminator
30
+ t << request.ip
31
+ t << params.require(:email)
32
+ # ...and call the throttle! method
33
+ t.throttle! # Will raise a Prorate::Throttled exception if the limit has been reached
34
+
35
+ To capture that exception, in the controller
36
+
37
+ rescue_from Prorate::Throttled do |e|
38
+ render nothing: true, status: 429
39
+ end
40
+
41
+ ## Development
42
+
43
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
44
+
45
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
46
+
47
+ ## Contributing
48
+
49
+ Bug reports and pull requests are welcome on GitHub at https://github.com/WeTransfer/prorate.
50
+
51
+
52
+ ## License
53
+
54
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
55
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "prorate"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/prorate.rb ADDED
@@ -0,0 +1,11 @@
1
+ require "prorate/version"
2
+ require "ks"
3
+ require "logger"
4
+ require "redis"
5
+
6
+ module Prorate
7
+ Dir.glob(__dir__ + '/prorate/**/*.rb').sort.each do |path|
8
+ require path
9
+ end
10
+ # Your code goes here...
11
+ end
@@ -0,0 +1,13 @@
1
+ module Prorate
2
+ module BlockFor
3
+ def self.block!(redis:, id:, duration:)
4
+ k = "bl:%s" % id
5
+ redis.setex(k, duration.to_i, 1)
6
+ end
7
+
8
+ def self.blocked?(redis:, id:)
9
+ k = "bl:%s" % id
10
+ !!redis.get(k)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,53 @@
1
+ module Prorate
2
+ # The counter implements a rolling window throttling mechanism. At each call to incr(), the Redis time
3
+ # is obtained. A counter then gets set at the key corresponding to the timestamp of the request, with a
4
+ # granularity of a second. If requests are done continuously and in large volume, the counter will therefore
5
+ # create one key for each second of the given rolling window size. he counters per second are set to auto-expire
6
+ # after the window lapses. When incr() is performed, there is
7
+ class Counter
8
+ def initialize(redis:, logger: NullLogger, id:, window_size:)
9
+ @redis = redis
10
+ @logger = logger
11
+ @id = id
12
+ @in_span_of_seconds = window_size.to_i.abs
13
+ end
14
+
15
+ # Increments the throttle counter for this identifier, and returns the total number of requests
16
+ # performed so far within the given time span. The caller can then determine whether the request has
17
+ # to be throttled or can be let through.
18
+ def incr
19
+ sec, _ = @redis.time # Use Redis time instead of the system timestamp, so that all the nodes are consistent
20
+ ts = sec.to_i # All Redis results are strings
21
+ k = key_for_ts(ts)
22
+ # Do the Redis stuff in a transaction, and capture only the necessary values
23
+ # (the result of MULTI is all the return values of each call in sequence)
24
+ *_, done_last_second, _, counter_values = @redis.multi do |txn|
25
+ # Increment the counter
26
+ txn.incr(k)
27
+ txn.expire(k, @in_span_of_seconds)
28
+
29
+ span_start = ts - @in_span_of_seconds
30
+ span_end = ts + 1
31
+ possible_keys = (span_start..span_end).map{|prev_time| key_for_ts(prev_time) }
32
+ @logger.debug { "%s: Scanning %d possible keys" % [@id, possible_keys.length] }
33
+
34
+ # Fetch all the counter values within the time window. Despite the fact that this
35
+ # will return thousands of elements for large sliding window sizes, the values are
36
+ # small and an MGET in Redis is pretty cheap, so perf should stay well within limits.
37
+ txn.mget(*possible_keys)
38
+ end
39
+
40
+ # Sum all the values. The empty keys return nils from MGET, which become 0 on to_i casts.
41
+ total_requests_during_period = counter_values.map(&:to_i).inject(&:+)
42
+ @logger.debug { "%s: %d reqs total during the last %d seconds" % [@id, total_requests_during_period, @in_span_of_seconds] }
43
+
44
+ total_requests_during_period
45
+ end
46
+
47
+ private
48
+
49
+ def key_for_ts(ts)
50
+ "th:%s:%d" % [@id, ts]
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,10 @@
1
+ module Prorate
2
+ module NullLogger
3
+ def self.debug(*); end
4
+ def self.info(*); end
5
+ def self.warn(*); end
6
+ def self.error(*); end
7
+ def self.fatal(*); end
8
+ def self.unknown(*); end
9
+ end
10
+ end
@@ -0,0 +1,5 @@
1
+ module Prorate
2
+ class NullPool < Struct.new(:conn)
3
+ def with; yield conn; end
4
+ end
5
+ end
@@ -0,0 +1,34 @@
1
+ require 'digest'
2
+
3
+ module Prorate
4
+ class Throttle < Ks.strict(:name, :limit, :period, :block_for, :redis, :logger)
5
+ def initialize(*)
6
+ super
7
+ @discriminators = [name.to_s]
8
+ self.redis = NullPool.new(redis) unless redis.respond_to?(:with)
9
+ end
10
+
11
+ def <<(discriminator)
12
+ @discriminators << discriminator
13
+ end
14
+
15
+ def throttle!
16
+ discriminator = Digest::SHA1.hexdigest(Marshal.dump(@discriminators))
17
+ identifier = [name, discriminator].join(':')
18
+
19
+ redis.with do |r|
20
+ logger.info { "Checking throttle block %s" % name }
21
+ raise Throttled.new(block_for) if Prorate::BlockFor.blocked?(id: identifier, redis: r)
22
+
23
+ logger.info { "Applying throttle counter %s" % name }
24
+ c = Prorate::Counter.new(redis: r, id: identifier, logger: logger, window_size: period)
25
+ after_increment = c.incr
26
+ if after_increment > limit
27
+ logger.warn { "Throttle %s exceeded limit of %d at %d" % [name, limit, after_increment] }
28
+ Prorate::BlockFor.block!(redis: r, id: identifier, duration: block_for)
29
+ raise Throttled.new(period)
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,9 @@
1
+ module Prorate
2
+ class Throttled < StandardError
3
+ attr_reader :retry_in_seconds
4
+ def initialize(try_again_in)
5
+ @retry_in_seconds = try_again_in
6
+ super("Throttled, please lower your temper and try again in %d seconds" % try_again_in)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,3 @@
1
+ module Prorate
2
+ VERSION = "0.1.0"
3
+ end
data/prorate.gemspec ADDED
@@ -0,0 +1,36 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'prorate/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "prorate"
8
+ spec.version = Prorate::VERSION
9
+ spec.authors = ["Julik Tarkhanov"]
10
+ spec.email = ["me@julik.nl"]
11
+
12
+ spec.summary = %q{Time-restricted rate limiter using Redis}
13
+ spec.description = %q{Can be used to implement all kinds of throttles}
14
+ spec.homepage = "https://github.com/WeTransfer/prorate"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "ks"
31
+ spec.add_dependency "redis", ">= 2"
32
+ spec.add_development_dependency "connection_pool", "~> 1"
33
+ spec.add_development_dependency "bundler", "~> 1.12"
34
+ spec.add_development_dependency "rake", "~> 10.0"
35
+ spec.add_development_dependency "rspec", "~> 3.0"
36
+ end
metadata ADDED
@@ -0,0 +1,147 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: prorate
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Julik Tarkhanov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-02-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ks
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: redis
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2'
41
+ - !ruby/object:Gem::Dependency
42
+ name: connection_pool
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.12'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.12'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ description: Can be used to implement all kinds of throttles
98
+ email:
99
+ - me@julik.nl
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - ".travis.yml"
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - lib/prorate.rb
114
+ - lib/prorate/block_for.rb
115
+ - lib/prorate/counter.rb
116
+ - lib/prorate/null_logger.rb
117
+ - lib/prorate/null_pool.rb
118
+ - lib/prorate/throttle.rb
119
+ - lib/prorate/throttled.rb
120
+ - lib/prorate/version.rb
121
+ - prorate.gemspec
122
+ homepage: https://github.com/WeTransfer/prorate
123
+ licenses:
124
+ - MIT
125
+ metadata:
126
+ allowed_push_host: https://rubygems.org
127
+ post_install_message:
128
+ rdoc_options: []
129
+ require_paths:
130
+ - lib
131
+ required_ruby_version: !ruby/object:Gem::Requirement
132
+ requirements:
133
+ - - ">="
134
+ - !ruby/object:Gem::Version
135
+ version: '0'
136
+ required_rubygems_version: !ruby/object:Gem::Requirement
137
+ requirements:
138
+ - - ">="
139
+ - !ruby/object:Gem::Version
140
+ version: '0'
141
+ requirements: []
142
+ rubyforge_project:
143
+ rubygems_version: 2.4.5.1
144
+ signing_key:
145
+ specification_version: 4
146
+ summary: Time-restricted rate limiter using Redis
147
+ test_files: []