full_throttle 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 452b5545989069904cecc0d3ef959653fc9d21df
4
+ data.tar.gz: 3a83890b6ca55ce24fb3edfe8dfeb7d462f09fb9
5
+ SHA512:
6
+ metadata.gz: dce830e7b8cb7a47a8459803255f355a635b69c0f2fea4558cbf9ffa97dc9b7d75b9e5612ddad575805884d9061ec04155fbd75ecd0f63b5f0cb335322c89d97
7
+ data.tar.gz: 83434f7de365a34edc82a3e0cec07d2bcf487a4cd9d30221f074d25e5ec0741594e0758506d9e3ac46f6d18ade72ba31e1f25e22304a9858c007c74f8096b372
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in throttle.gemspec
4
+ gemspec
@@ -0,0 +1,31 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ throttle (0.0.1)
5
+ redis (~> 3.0.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ diff-lcs (1.2.5)
11
+ rake (10.3.2)
12
+ redis (3.0.7)
13
+ rspec (2.99.0)
14
+ rspec-core (~> 2.99.0)
15
+ rspec-expectations (~> 2.99.0)
16
+ rspec-mocks (~> 2.99.0)
17
+ rspec-core (2.99.2)
18
+ rspec-expectations (2.99.2)
19
+ diff-lcs (>= 1.1.3, < 2.0)
20
+ rspec-mocks (2.99.2)
21
+ timecop (0.7.1)
22
+
23
+ PLATFORMS
24
+ ruby
25
+
26
+ DEPENDENCIES
27
+ bundler (~> 1.7)
28
+ rake (~> 10.0)
29
+ rspec (~> 2.3)
30
+ throttle!
31
+ timecop (~> 0.7.1)
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Rafael Bandeira
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,31 @@
1
+ # Throttle
2
+
3
+ TODO: Write a gem description
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'throttle'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install throttle
20
+
21
+ ## Usage
22
+
23
+ TODO: Write usage instructions here
24
+
25
+ ## Contributing
26
+
27
+ 1. Fork it ( https://github.com/[my-github-username]/throttle/fork )
28
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
29
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
30
+ 4. Push to the branch (`git push origin my-new-feature`)
31
+ 5. Create a new Pull Request
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'throttle/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "full_throttle"
8
+ spec.version = Throttle::VERSION
9
+ spec.authors = ["Rafael Bandeira"]
10
+ spec.email = ["rafaelbandeira3@gmail.com"]
11
+ spec.summary = %q{Throttle mechanism for distributed work}
12
+ spec.description = %q{Redis based throttle mechanism to be used by concurrent background jobs}
13
+ spec.homepage = "https://github.com/rafaelbandeira3/full_throttle"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_dependency "redis", "~> 3.0.0"
22
+ spec.add_development_dependency "bundler", "~> 1.7"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "rspec", "~> 2.3"
25
+ spec.add_development_dependency "timecop", "~> 0.7.1"
26
+ end
@@ -0,0 +1 @@
1
+ require "./throttle"
@@ -0,0 +1,15 @@
1
+ local time = tonumber(ARGV[1])
2
+ local bucket_size = tonumber(redis.call("get", KEYS[1])) or math.huge
3
+ local bucket_time = tonumber(redis.call("get", KEYS[2])) or time
4
+ local bucket_count = tonumber(redis.call("get", KEYS[3])) or 0
5
+ local bucket_duration = tonumber(redis.call("get", KEYS[4])) or 1
6
+
7
+ if time - bucket_time >= bucket_duration then -- reset bucket
8
+ redis.call("mset", KEYS[2], time, KEYS[3], 1)
9
+ return {1, 1, time}
10
+ elseif bucket_count >= bucket_size then -- throttled
11
+ return {0, bucket_count, bucket_time}
12
+ else -- good to go
13
+ redis.call("mset", KEYS[2], time, KEYS[3], bucket_count + 1)
14
+ return {1, bucket_count + 1, bucket_time}
15
+ end
@@ -0,0 +1,28 @@
1
+ require "redis"
2
+ require "throttle/version"
3
+ require "throttle/instance"
4
+ require "throttle/redis_script"
5
+
6
+ module Throttle
7
+ ThrottledError = Class.new(StandardError)
8
+
9
+ class << self
10
+ attr_accessor :default_redis_client,
11
+ :default_timeout,
12
+ :default_ns,
13
+ :default_polling
14
+
15
+ def for(key, max_per_second, opts = {}, &block)
16
+ polling = opts[:polling] || Throttle.default_polling
17
+ timeout = opts[:timeout] || Throttle.default_timeout
18
+ redis = opts[:redis] || Throttle.default_redis_client
19
+ namespace = opts[:ns] || Throttle.default_ns
20
+
21
+ strategy = RedisScript.new(redis, "#{namespace}:#{key}", max_per_second)
22
+ strategy.set_bucket_size!
23
+
24
+ instance = Instance.new(strategy, polling, timeout)
25
+ instance.limit(&block)
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,31 @@
1
+ require "timeout"
2
+
3
+ module Throttle
4
+ class Instance
5
+ def initialize(strategy, polling, timeout)
6
+ @strategy = strategy
7
+ @polling = polling
8
+ @timeout = timeout
9
+ end
10
+
11
+ def limit(&block)
12
+ timeout(@timeout) do
13
+ loop do
14
+ go, count, time = @strategy.acquire
15
+ if go
16
+ return yield(count, time) if block.arity > 0
17
+ return yield
18
+ end
19
+ sleep @polling
20
+ end
21
+ end
22
+
23
+ rescue Timeout::Error
24
+ raise Throttle::ThrottledError, "can't execute at this time"
25
+ end
26
+
27
+ def status
28
+ @strategy.status
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,45 @@
1
+ require "digest"
2
+
3
+ module Throttle
4
+ class RedisScript
5
+ SCRIPT = File.read("lib/throttle.lua").freeze
6
+ SCRIPT_SHA1 = Digest::SHA1.hexdigest(SCRIPT)
7
+
8
+ def self.key(key, type)
9
+ "#{@key}:#{type}"
10
+ end
11
+
12
+ def initialize(redis, key, default_bucket_size)
13
+ @redis = redis
14
+ @key = key
15
+ @default_bucket_size = default_bucket_size
16
+ end
17
+
18
+ def acquire
19
+ begin
20
+ keys = [key(:size), key(:time), key(:count), key(:duration)]
21
+ go, count, time = @redis.evalsha(SCRIPT_SHA1, keys, [Time.now.utc.to_i])
22
+ [go == 1, count, time]
23
+ rescue Redis::CommandError => e
24
+ raise unless e.message =~ /NOSCRIPT/
25
+
26
+ @redis.send("script", "load", SCRIPT)
27
+ acquire
28
+ end
29
+ end
30
+
31
+ def status
32
+ time, count, size = @redis.mget(key(:time), key(:count), key(:size))
33
+ [Time.at(time.to_i), count.to_i, size.to_i]
34
+ end
35
+
36
+ def set_bucket_size!(val = nil)
37
+ @redis.set(key(:size), val || @default_bucket_size)
38
+ end
39
+
40
+ private
41
+ def key(k)
42
+ self.class.key(@key, k)
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,3 @@
1
+ module Throttle
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,60 @@
1
+ require "spec_helper"
2
+
3
+ describe Throttle::Instance do
4
+ let(:counter) { double(:counter, count: nil) }
5
+ let(:strategy) { double(:throttle_strategy) }
6
+ let(:polling) { 1 }
7
+ let(:timeout) { 1 }
8
+ let(:key) { "test" }
9
+
10
+ subject { described_class.new(strategy, polling, timeout) }
11
+
12
+ it "executes block if throttle strategy returns true" do
13
+ expect(strategy).to receive(:acquire).
14
+ exactly(3).times.and_return([true, :na, :na])
15
+ expect(counter).to receive(:count).exactly(3).times
16
+
17
+ 3.times { subject.limit { counter.count } }
18
+ end
19
+
20
+ it "passes bucket count and time to block if it has arity" do
21
+ 3.times do |n|
22
+ expect(strategy).to receive(:acquire).
23
+ and_return([true, n, t = Time.now])
24
+
25
+ subject.limit do |count, time|
26
+ expect(count).to eq n
27
+ expect(time).to eq t
28
+ end
29
+ end
30
+ end
31
+
32
+ it "raises error if can't acquire before timeout" do
33
+ expect(strategy).to receive(:acquire).
34
+ once.and_return([false, :na, :na])
35
+ expect(counter).to_not receive(:count)
36
+
37
+ expect { subject.limit { counter.count } }.to raise_error(Throttle::ThrottledError)
38
+ end
39
+
40
+ describe "retrying" do
41
+ let(:timeout) { 0.60 }
42
+ let(:expected_repetition) { 4 }
43
+ let(:polling) { timeout / expected_repetition }
44
+
45
+ it "retries once every `polling` seconds up to `timeout` seconds" do
46
+ expect(strategy).to receive(:acquire).
47
+ exactly(expected_repetition).times.and_return([false, :na, :na],
48
+ [false, :na, :na],
49
+ [false, :na, :na],
50
+ [true, :na, :na])
51
+
52
+ subject.limit { counter.count }
53
+ end
54
+ end
55
+
56
+ it "returns status" do
57
+ expect(strategy).to receive(:status).and_return(:arbitrary_status)
58
+ expect(subject.status).to eq :arbitrary_status
59
+ end
60
+ end
@@ -0,0 +1,62 @@
1
+ require "spec_helper"
2
+
3
+ describe Throttle::RedisScript do
4
+ let(:redis) { Redis.current }
5
+ let(:time) { Time.now }
6
+
7
+ describe "instance" do
8
+ let(:key) { "test" }
9
+ let(:size) { 3 }
10
+ subject! { described_class.new(redis, key, size) }
11
+
12
+ describe "managing bucket size" do
13
+ let(:bucket_size) { redis.get(described_class.key(key, :size)).to_i }
14
+
15
+ it "sets to default if no value given" do
16
+ subject.set_bucket_size!
17
+ expect(bucket_size).to eq size
18
+ end
19
+
20
+ it "sets to given value" do
21
+ subject.set_bucket_size!(100)
22
+ expect(bucket_size).to eq 100
23
+ end
24
+ end
25
+
26
+ describe "status" do
27
+ it "returns info on window time, window runs, bucket size" do
28
+ expect(Time).to receive(:at).with(time.to_i).and_return(time)
29
+ redis.set(described_class.key(key, :time), time.to_i)
30
+ redis.set(described_class.key(key, :count), "12")
31
+ redis.set(described_class.key(key, :size), "24")
32
+ expect(subject.status).to eq [time, 12, 24]
33
+ end
34
+ end
35
+
36
+ describe "acquiring permission" do
37
+ before(:each) { subject.set_bucket_size! }
38
+
39
+ it "acquires entry on bucket if possible and returns time, count and flag" do
40
+ Timecop.freeze(time) do |t|
41
+ expect(subject.acquire).to eq [true, 1, t.to_i]
42
+ expect(subject.acquire).to eq [true, 2, t.to_i]
43
+ expect(subject.acquire).to eq [true, 3, t.to_i]
44
+ expect(subject.acquire).to eq [false, 3, t.to_i]
45
+ expect(subject.acquire).to eq [false, 3, t.to_i]
46
+ end
47
+ end
48
+
49
+ it "changes bucket size at runtime" do
50
+ Timecop.freeze(time) do |t|
51
+ expect(subject.acquire).to eq [true, 1, t.to_i]
52
+ expect(subject.acquire).to eq [true, 2, t.to_i]
53
+ expect(subject.acquire).to eq [true, 3, t.to_i]
54
+ expect(subject.acquire).to eq [false, 3, t.to_i]
55
+
56
+ subject.set_bucket_size!(4)
57
+ expect(subject.acquire).to eq [true, 4, t.to_i]
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,43 @@
1
+ require "spec_helper"
2
+
3
+ describe Throttle do
4
+ let(:key) { :test }
5
+ let(:max) { 30 }
6
+ let(:polling) { 0.25 }
7
+ let(:timeout) { 1 }
8
+ let(:redis) { Redis.current }
9
+ let(:ns) { :throttled_actions }
10
+ let(:counter) { double(:counter, count: nil) }
11
+ let(:opts) { {} }
12
+
13
+ shared_examples "Throttle API" do
14
+ it "initializes throttle with options and limits given block" do
15
+ expect(described_class::RedisScript).to receive(:new).
16
+ with(redis, "#{ns}:#{key}", max).
17
+ and_call_original
18
+
19
+ expect(described_class::Instance).to receive(:new).
20
+ with(kind_of(described_class::RedisScript), polling, timeout).
21
+ and_call_original
22
+
23
+ expect(counter).to receive(:count)
24
+
25
+ described_class.for(key, max, opts) { counter.count }
26
+ end
27
+ end
28
+
29
+ describe "using options" do
30
+ let(:opts) { {polling: polling, timeout: timeout, redis: redis, ns: ns} }
31
+ it_behaves_like "Throttle API"
32
+ end
33
+
34
+ describe "using defaults" do
35
+ before(:each) do
36
+ Throttle.default_polling = polling
37
+ Throttle.default_timeout = timeout
38
+ Throttle.default_redis_client = redis
39
+ Throttle.default_ns = ns
40
+ end
41
+ it_behaves_like "Throttle API"
42
+ end
43
+ end
@@ -0,0 +1,12 @@
1
+ require File.join(File.dirname(__FILE__), "..", "lib", "throttle")
2
+
3
+ require "byebug"
4
+ require "timecop"
5
+
6
+ RSpec.configure do |config|
7
+ config.before(:each) do
8
+ keys = Redis.current.scan_each.to_a
9
+ Redis.current.del(keys) if keys.any?
10
+ end
11
+ end
12
+
metadata ADDED
@@ -0,0 +1,135 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: full_throttle
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Rafael Bandeira
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-09-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 3.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 3.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.7'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.7'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.3'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.3'
69
+ - !ruby/object:Gem::Dependency
70
+ name: timecop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 0.7.1
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 0.7.1
83
+ description: Redis based throttle mechanism to be used by concurrent background jobs
84
+ email:
85
+ - rafaelbandeira3@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - Gemfile
91
+ - Gemfile.lock
92
+ - LICENSE.txt
93
+ - README.md
94
+ - Rakefile
95
+ - full_throttle.gemspec
96
+ - lib/full_throttle.rb
97
+ - lib/throttle.lua
98
+ - lib/throttle.rb
99
+ - lib/throttle/instance.rb
100
+ - lib/throttle/redis_script.rb
101
+ - lib/throttle/version.rb
102
+ - spec/lib/throttle/instance_spec.rb
103
+ - spec/lib/throttle/redis_script_spec.rb
104
+ - spec/lib/throttle_spec.rb
105
+ - spec/spec_helper.rb
106
+ homepage: https://github.com/rafaelbandeira3/full_throttle
107
+ licenses:
108
+ - MIT
109
+ metadata: {}
110
+ post_install_message:
111
+ rdoc_options: []
112
+ require_paths:
113
+ - lib
114
+ required_ruby_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '0'
119
+ required_rubygems_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ requirements: []
125
+ rubyforge_project:
126
+ rubygems_version: 2.4.1
127
+ signing_key:
128
+ specification_version: 4
129
+ summary: Throttle mechanism for distributed work
130
+ test_files:
131
+ - spec/lib/throttle/instance_spec.rb
132
+ - spec/lib/throttle/redis_script_spec.rb
133
+ - spec/lib/throttle_spec.rb
134
+ - spec/spec_helper.rb
135
+ has_rdoc: