excon-middleware-aws-exponential_backoff 0.0.1

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: 79088f6ebcd87310329c1c8ce66dc3c3aa7184c9
4
+ data.tar.gz: 19f90d70c7292dd6f9d902260dec0297dcd744b1
5
+ SHA512:
6
+ metadata.gz: 165f925409e1d286e97aa3a43aefe56214ed16f22e36aedf58af75f17f7f2bad8725d4c485d47f2ce9ceca22ba53262a1e605ae11d965fe527793428a576fc6a
7
+ data.tar.gz: fb60aa48496cbb24c24d38bd2b156e2c0caae1c6f576a90b4bda775f5a241801cc5ee6ddfc18e28d9b9868dbf46daed75763e6b30f05f56a00754b29c91492b6
data/.gitignore ADDED
@@ -0,0 +1,22 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.bundle
19
+ *.so
20
+ *.o
21
+ *.a
22
+ mkmf.log
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in excon-middleware-aws-exponential_backoff.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Michael Hale
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.
data/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # Excon::Middleware::AWS::ExponentialBackoff
2
+
3
+ Excon middleware to exponentially backoff calling AWS APIs when throttled or experiencing errors.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'excon-middleware-aws-exponential_backoff'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install excon-middleware-aws-exponential_backoff
18
+
19
+ ## Usage
20
+
21
+ This gem is intended to be used with fog and excon when communicating with AWS APIs.
22
+
23
+ ```ruby
24
+ require "fog"
25
+ require "excon/middleware/aws/exponential_backoff/include"
26
+
27
+ 10.times do
28
+ p Fog::DNS::AWS.new(aws_access_key_id: 'key', aws_secret_access_key: 'secret').list_hosted_zones
29
+ end
30
+ ```
31
+
32
+ ## Contributing
33
+
34
+ 1. Fork it ( https://github.com/mikehale/excon-middleware-aws-exponential_backoff/fork )
35
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
36
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
37
+ 4. Push to the branch (`git push origin my-new-feature`)
38
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'excon/middleware/aws/exponential_backoff/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "excon-middleware-aws-exponential_backoff"
8
+ spec.version = Excon::Middleware::AWS::ExponentialBackoff::VERSION
9
+ spec.authors = ["Michael Hale"]
10
+ spec.email = ["mike@hales.ws"]
11
+ spec.summary = %q{Excon middleware to exponentially backoff calling AWS APIs when throttled or experiencing errors.}
12
+ spec.homepage = "https://github.com/mikehale/excon-middleware-aws-exponential_backoff"
13
+ spec.license = "MIT"
14
+
15
+ spec.files = `git ls-files -z`.split("\x0")
16
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
17
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_development_dependency "bundler", "~> 1.6"
21
+ spec.add_development_dependency "rake"
22
+ spec.add_development_dependency "rspec"
23
+ spec.add_dependency "excon"
24
+ end
@@ -0,0 +1,98 @@
1
+ require 'excon'
2
+ require "excon/middleware/aws/exponential_backoff/version"
3
+
4
+ module Excon
5
+ module Middleware
6
+ module AWS
7
+ class ExponentialBackoff < Excon::Middleware::Base
8
+ MILLISECOND = 1.0/1000
9
+ SLEEP_FACTOR = MILLISECOND * 100
10
+ ERROR_CODE_REGEX = Regexp.new(/<Code>([^<]+)<\/Code>/mi)
11
+ THROTTLING_ERROR_CODES = %w[
12
+ Throttling
13
+ ThrottlingException
14
+ ProvisionedThroughputExceededException
15
+ RequestThrottled
16
+ RequestLimitExceeded
17
+ BandwidthLimitExceeded
18
+ ]
19
+ SERVER_ERROR_CLASSES = [
20
+ Excon::Errors::InternalServerError,
21
+ Excon::Errors::BadGateway,
22
+ Excon::Errors::ServiceUnavailable,
23
+ Excon::Errors::GatewayTimeout
24
+ ]
25
+ VALID_MIDDLEWARE_KEYS = [
26
+ :backoff
27
+ ]
28
+
29
+ def error_call(datum)
30
+ datum[:backoff] ||= {}
31
+ datum[:backoff][:max_retries] ||= 0
32
+ datum[:backoff][:max_delay] ||= 30
33
+ datum[:backoff][:retry_count] = 0
34
+
35
+ if (throttle?(datum) || server_error?(datum)) && should_retry?(datum)
36
+ do_backoff(datum)
37
+ else
38
+ do_handoff(datum)
39
+ end
40
+ end
41
+
42
+ def do_handoff(datum)
43
+ @stack.error_call(datum)
44
+ end
45
+
46
+ def do_backoff(datum)
47
+ do_sleep(sleep_time(datum), datum)
48
+ datum[:backoff][:retry_count] += 1
49
+ connection = datum.delete(:connection)
50
+ datum.reject! { |key, _| !(Excon::VALID_REQUEST_KEYS + VALID_MIDDLEWARE_KEYS).include?(key) }
51
+ connection.request(datum)
52
+ end
53
+
54
+ def do_sleep(sleep_time, datum)
55
+ if datum.has_key?(:instrumentor)
56
+ datum[:instrumentor].instrument("#{datum[:instrumentor_name]}.backoff", datum) do
57
+ sleep sleep_time
58
+ end
59
+ else
60
+ sleep sleep_time
61
+ end
62
+ end
63
+
64
+ def sleep_time(datum)
65
+ exponential_wait = (2 ** datum[:backoff][:retry_count] + rand(0.0)) * SLEEP_FACTOR
66
+ [
67
+ exponential_wait,
68
+ datum[:backoff][:max_delay]
69
+ ].min.round(2)
70
+ end
71
+
72
+ def should_retry?(datum)
73
+ # Always retry if max_retries is 0.
74
+ datum[:backoff][:max_retries] == 0 ||
75
+ datum[:backoff][:retry_count] < datum[:backoff][:max_retries]
76
+ end
77
+
78
+ def throttle?(datum)
79
+ datum[:error].kind_of?(Excon::Errors::BadRequest) &&
80
+ THROTTLING_ERROR_CODES.include?(extract_error_code(datum[:error].response.body))
81
+
82
+
83
+ end
84
+
85
+ def server_error?(datum)
86
+ SERVER_ERROR_CLASSES.any? { |ex| datum[:error].kind_of?(ex) }
87
+ end
88
+
89
+ def extract_error_code(body)
90
+ match = ERROR_CODE_REGEX.match(body)
91
+ if match && code = match[1]
92
+ code.strip if code
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,2 @@
1
+ require "excon/middleware/aws/exponential_backoff"
2
+ Excon.defaults[:middlewares] << Excon::Middleware::AWS::ExponentialBackoff
@@ -0,0 +1,11 @@
1
+ require "excon"
2
+
3
+ module Excon
4
+ module Middleware
5
+ module AWS
6
+ class ExponentialBackoff < Excon::Middleware::Base
7
+ VERSION = "0.0.1"
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,106 @@
1
+ require "spec_helper"
2
+
3
+ class Stack
4
+ def error_call(datum); end
5
+ def request_call(datum); end
6
+ def response_call(datum); end
7
+ end
8
+
9
+ RSpec.describe Excon::Middleware::AWS::ExponentialBackoff do
10
+ let(:stack) { Stack.new }
11
+ subject { Excon::Middleware::AWS::ExponentialBackoff.new(stack) }
12
+
13
+ it { is_expected.to respond_to :error_call }
14
+
15
+ it "delays exponentially longer" do
16
+ wait1 = subject.sleep_time(backoff: {max_delay: 10, retry_count: 0 })
17
+ wait2 = subject.sleep_time(backoff: {max_delay: 10, retry_count: 1 })
18
+ wait3 = subject.sleep_time(backoff: {max_delay: 10, retry_count: 2 })
19
+ expect(wait3).to be > wait2
20
+ expect(wait2).to be > wait1
21
+ expect(wait1).to be > 0
22
+ end
23
+
24
+ it "should not exceed max_delay" do
25
+ expect(subject.sleep_time(backoff: {max_delay: 1, retry_count: 10 })).to be 1.0
26
+ end
27
+
28
+ it "always retries if max_retries is 0" do
29
+ expect(subject.should_retry?(backoff: {max_retries: 0})).to be true
30
+ end
31
+
32
+ it "retries if retry_count is < max_retries" do
33
+ expect(subject.should_retry?(backoff: {retry_count:0, max_retries: 1})).to be true
34
+ expect(subject.should_retry?(backoff: {retry_count:1, max_retries: 1})).to be false
35
+ end
36
+
37
+ it "backs off when throttled" do
38
+ throttled = Excon::Errors.status_error({}, throttling_response)
39
+ redirect = Excon::Errors.status_error({}, Excon::Response.new(status: 302))
40
+ bad_request = Excon::Errors.status_error({}, Excon::Response.new(status: 400))
41
+
42
+ expect(subject.throttle?(error: throttled)).to be true
43
+ expect(subject.throttle?(error: redirect)).to be false
44
+ expect(subject.throttle?(error: bad_request)).to be false
45
+ end
46
+
47
+ it "backs off when there is a server error" do
48
+ expect(subject.server_error?(error: Excon::Errors.status_error({}, Excon::Response.new(status: 500)))).to be true
49
+ expect(subject.server_error?(error: Excon::Errors.status_error({}, Excon::Response.new(status: 501)))).to be false
50
+ expect(subject.server_error?(error: Excon::Errors.status_error({}, Excon::Response.new(status: 502)))).to be true
51
+ expect(subject.server_error?(error: Excon::Errors.status_error({}, Excon::Response.new(status: 503)))).to be true
52
+ expect(subject.server_error?(error: Excon::Errors.status_error({}, Excon::Response.new(status: 504)))).to be true
53
+ end
54
+
55
+ it "should call do_backoff when throttled" do
56
+ throttled = Excon::Errors.status_error({}, throttling_response)
57
+ expect(subject).to receive(:do_backoff)
58
+ subject.error_call(error: throttled)
59
+ end
60
+
61
+ it "should call do_handoff when not throttled" do
62
+ bad_request = Excon::Errors.status_error({}, Excon::Response.new(status: 400))
63
+ expect(subject).to receive(:do_handoff)
64
+ subject.error_call(error: bad_request)
65
+ end
66
+
67
+ it "hands off correctly" do
68
+ datum = {}
69
+ expect(stack).to receive(:error_call).with(datum)
70
+ subject.do_handoff(datum)
71
+ end
72
+
73
+ context :do_backoff do
74
+ let(:connection) { double("connection") }
75
+ let(:datum) {
76
+ {
77
+ backoff: {
78
+ retry_count: 1,
79
+ max_delay: 10
80
+ },
81
+ connection: connection
82
+ }
83
+ }
84
+
85
+ before do
86
+ allow(connection).to receive(:request)
87
+ allow(subject).to receive(:do_sleep)
88
+ end
89
+
90
+ it "increments the request_count" do
91
+ subject.do_backoff(datum)
92
+ expect(datum[:backoff][:retry_count]).to be 2
93
+ end
94
+
95
+ it "restarts request call with a reset connection" do
96
+ expect(connection).to receive(:request).with({backoff: {max_delay: 10, retry_count: 2}})
97
+ subject.do_backoff(datum.merge(ignored_stuff: :foo))
98
+ end
99
+
100
+ it "sleeps for the specified time" do
101
+ allow(subject).to receive(:sleep_time) { 1.1 }
102
+ expect(subject).to receive(:do_sleep).with(1.1, datum)
103
+ subject.do_backoff(datum)
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,49 @@
1
+ require "excon/middleware/aws/exponential_backoff"
2
+
3
+ module AWSErrorHelper
4
+ def throttling_response
5
+ body = %(
6
+ <ErrorResponse xmlns="http://some-service.amazonaws.com/doc/2010-05-15/">
7
+ <Error>
8
+ <Type>Sender</Type>
9
+ <Code>Throttling</Code>
10
+ <Message>Rate exceeded</Message>
11
+ </Error>
12
+ </ErrorResponse>
13
+ )
14
+
15
+ Excon::Response.new(status: 400, body: body)
16
+ end
17
+
18
+ def request_time_too_skewed_response
19
+ body = %(
20
+ <Error>
21
+ <Code>RequestTimeTooSkewed</Code>
22
+ <Message>The difference between the request time and the current time is too large.</Message>
23
+ <ServerTime>2006-11-10T13:43:55Z</ServerTime>
24
+ <MaxAllowedSkewMilliseconds>900000</MaxAllowedSkewMilliseconds>
25
+ <RequestTime>Fri, 10 Nov 2006 13:28:46 GMT</RequestTime>
26
+ </Error>
27
+ )
28
+
29
+ Excon::Response.new(status: 400, body: body)
30
+ end
31
+ end
32
+
33
+ RSpec.configure do |config|
34
+ config.expect_with :rspec do |expectations|
35
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
36
+ end
37
+ config.mock_with :rspec do |mocks|
38
+ mocks.verify_partial_doubles = true
39
+ end
40
+ if config.files_to_run.one?
41
+ config.default_formatter = 'doc'
42
+ end
43
+ config.disable_monkey_patching!
44
+ config.warnings = true
45
+ config.order = :random
46
+ Kernel.srand config.seed
47
+
48
+ config.include AWSErrorHelper
49
+ end
metadata ADDED
@@ -0,0 +1,115 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: excon-middleware-aws-exponential_backoff
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Michael Hale
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-09-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.6'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.6'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: excon
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description:
70
+ email:
71
+ - mike@hales.ws
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - excon-middleware-aws-exponential_backoff.gemspec
83
+ - lib/excon/middleware/aws/exponential_backoff.rb
84
+ - lib/excon/middleware/aws/exponential_backoff/include.rb
85
+ - lib/excon/middleware/aws/exponential_backoff/version.rb
86
+ - spec/exponential_backoff_spec.rb
87
+ - spec/spec_helper.rb
88
+ homepage: https://github.com/mikehale/excon-middleware-aws-exponential_backoff
89
+ licenses:
90
+ - MIT
91
+ metadata: {}
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubyforge_project:
108
+ rubygems_version: 2.2.2
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Excon middleware to exponentially backoff calling AWS APIs when throttled
112
+ or experiencing errors.
113
+ test_files:
114
+ - spec/exponential_backoff_spec.rb
115
+ - spec/spec_helper.rb