pigeon-http 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at fitra.pradana@mekari.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in pigeon.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 0.80"
data/Gemfile.lock ADDED
@@ -0,0 +1,102 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ pigeon-http (0.1.0)
5
+ circuitbox
6
+ ddtrace
7
+ dogstatsd-ruby
8
+ http
9
+ http-cookie
10
+ mime-types
11
+ retryable
12
+
13
+ GEM
14
+ remote: https://rubygems.org/
15
+ specs:
16
+ addressable (2.8.4)
17
+ public_suffix (>= 2.0.2, < 6.0)
18
+ ast (2.4.2)
19
+ circuitbox (2.0.0)
20
+ ddtrace (1.5.2)
21
+ debase-ruby_core_source (>= 0.10.16, <= 0.10.17)
22
+ libdatadog (~> 0.7.0.1.1)
23
+ libddwaf (~> 1.5.1.0.0)
24
+ msgpack
25
+ debase-ruby_core_source (0.10.17)
26
+ diff-lcs (1.5.0)
27
+ dogstatsd-ruby (5.3.3)
28
+ domain_name (0.5.20190701)
29
+ unf (>= 0.0.5, < 1.0.0)
30
+ ffi (1.15.5)
31
+ ffi-compiler (1.0.1)
32
+ ffi (>= 1.0.0)
33
+ rake
34
+ http (4.4.1)
35
+ addressable (~> 2.3)
36
+ http-cookie (~> 1.0)
37
+ http-form_data (~> 2.2)
38
+ http-parser (~> 1.2.0)
39
+ http-cookie (1.0.5)
40
+ domain_name (~> 0.5)
41
+ http-form_data (2.3.0)
42
+ http-parser (1.2.3)
43
+ ffi-compiler (>= 1.0, < 2.0)
44
+ libdatadog (0.7.0.1.1)
45
+ libddwaf (1.5.1.0.1)
46
+ ffi (~> 1.0)
47
+ mime-types (3.5.1)
48
+ mime-types-data (~> 3.2015)
49
+ mime-types-data (3.2023.0808)
50
+ msgpack (1.7.2)
51
+ parallel (1.23.0)
52
+ parser (3.2.2.3)
53
+ ast (~> 2.4.1)
54
+ racc
55
+ public_suffix (5.0.3)
56
+ racc (1.7.1)
57
+ rainbow (3.1.1)
58
+ rake (13.0.6)
59
+ regexp_parser (2.8.1)
60
+ retryable (3.0.5)
61
+ rexml (3.2.6)
62
+ rspec (3.12.0)
63
+ rspec-core (~> 3.12.0)
64
+ rspec-expectations (~> 3.12.0)
65
+ rspec-mocks (~> 3.12.0)
66
+ rspec-core (3.12.2)
67
+ rspec-support (~> 3.12.0)
68
+ rspec-expectations (3.12.3)
69
+ diff-lcs (>= 1.2.0, < 2.0)
70
+ rspec-support (~> 3.12.0)
71
+ rspec-mocks (3.12.6)
72
+ diff-lcs (>= 1.2.0, < 2.0)
73
+ rspec-support (~> 3.12.0)
74
+ rspec-support (3.12.1)
75
+ rubocop (0.93.1)
76
+ parallel (~> 1.10)
77
+ parser (>= 2.7.1.5)
78
+ rainbow (>= 2.2.2, < 4.0)
79
+ regexp_parser (>= 1.8)
80
+ rexml
81
+ rubocop-ast (>= 0.6.0)
82
+ ruby-progressbar (~> 1.7)
83
+ unicode-display_width (>= 1.4.0, < 2.0)
84
+ rubocop-ast (1.29.0)
85
+ parser (>= 3.2.1.0)
86
+ ruby-progressbar (1.13.0)
87
+ unf (0.1.4)
88
+ unf_ext
89
+ unf_ext (0.0.8.2)
90
+ unicode-display_width (1.8.0)
91
+
92
+ PLATFORMS
93
+ -darwin-21
94
+
95
+ DEPENDENCIES
96
+ pigeon-http!
97
+ rake (~> 13.0)
98
+ rspec (~> 3.0)
99
+ rubocop (~> 0.80)
100
+
101
+ BUNDLED WITH
102
+ 2.2.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Fitra Aditya
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,43 @@
1
+ # Pigeon
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/pigeon`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'pigeon'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install pigeon
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/pigeon. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/pigeon/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Pigeon project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/pigeon/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "pigeon"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
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
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require 'circuitbox'
5
+ require 'datadog/statsd'
6
+ require 'ddtrace'
7
+ require 'ddtrace/auto_instrument'
8
+ require 'http'
9
+ require 'http-cookie'
10
+ require 'mime/types'
11
+ require 'net/http'
12
+ require 'openssl'
13
+ require 'securerandom'
14
+ require 'stringio'
15
+ require 'uri'
16
+ require 'zlib'
17
+ rescue LoadError => e
18
+ print "load error: #{e.message}"
19
+ end
20
+
21
+ module Pigeon
22
+ VALID_OPTIONS = %w[request_timeout request_open_timeout ssl_verify volume_threshold error_threshold time_window sleep_window retryable retry_threshold].freeze
23
+ VALID_CALLBACKS = %w[CircuitBreakerOpen CircuitBreakerClose HttpSuccess HttpError RetrySuccess RetryFailure]
24
+
25
+ DEFAULT_OPTIONS = {
26
+ request_name: 'pigeon_default',
27
+ request_timeout: 60,
28
+ request_open_timeout: 0,
29
+ ssl_verify: true,
30
+ volume_threshold: 10,
31
+ error_threshold: 10,
32
+ time_window: 10,
33
+ sleep_window: 10,
34
+ retryable: true,
35
+ retry_threshold: 3
36
+ }
37
+ DEFAULT_CALLBACKS = {
38
+ CircuitBreakerOpen: nil,
39
+ CircuitBreakerClose: nil,
40
+ HttpSuccess: nil,
41
+ HttpError: nil,
42
+ RetrySuccess: nil,
43
+ RetryFailure: nil
44
+ }
45
+
46
+ class Client
47
+ attr_writer :request_name, :options, :callbacks
48
+
49
+ def initialize name, opts = {}, clbk = {}
50
+ @options = DEFAULT_OPTIONS
51
+ @callbacks = DEFAULT_CALLBACKS
52
+
53
+ @options['request_name'] = name
54
+
55
+ opts.each do |k, v|
56
+ raise Error::Argument, "unknown option #{k}" unless VALID_OPTIONS.include?(k.to_s)
57
+ @options[k] = v
58
+ end
59
+
60
+ clbk.each do |k, v|
61
+ raise Error::Argument, "unknown callback #{k}" unless VALID_CALLBACKS.include?(k.to_s)
62
+ @callbacks[k] = v
63
+ end
64
+
65
+ if @options['retryable']
66
+ Retryable.configure do |config|
67
+ config.sleep = lambda { |n| 4**n }
68
+ end
69
+ end
70
+
71
+ Datadog.configure do |c|
72
+ c.env = ENV['DD_ENV']
73
+ c.service = ENV['DD_SERVICE']
74
+ c.tracing.partial_flush.enabled = true
75
+ c.profiling.enabled = false
76
+ c.runtime_metrics.enabled = false
77
+ c.runtime_metrics.statsd = Datadog::Statsd.new
78
+ c.tracing.sampler = Datadog::Tracing::Sampling::PrioritySampler.new(
79
+ post_sampler: Datadog::Tracing::Sampling::RuleSampler.new(
80
+ [Datadog::Tracing::Sampling::SimpleRule.new(service: ENV['DD_SERVICE'], sample_rate: 1.0)]
81
+ )
82
+ )
83
+ end
84
+ end
85
+
86
+ def get url, args = {}
87
+ start = Time.now
88
+ response = http(:get, url, args)
89
+ Pigeon::Statsd.new(@options['request_name'] + '_latency', tags: [url]).capture(action: :histogram, count: (Time.now - start))
90
+
91
+ response
92
+ rescue => e
93
+ @callbacks['HttpError']&.call(e)
94
+ end
95
+
96
+ def post url, args = {}
97
+ start = Time.now
98
+ response = http(:post, url, args)
99
+ Pigeon::Statsd.new(@options['request_name'] + '_latency', tags: [url]).capture(action: :histogram, count: (Time.now - start))
100
+
101
+ response
102
+ rescue => e
103
+ @callbacks['HttpError']&.call(e)
104
+ end
105
+
106
+ def put url, args = {}
107
+ http(:put, url, args)
108
+ rescue => e
109
+ @callbacks['HttpError']&.call(e)
110
+ end
111
+
112
+ def delete url, args = {}
113
+ http(:delete, url, args)
114
+ rescue => e
115
+ @callbacks['HttpError']&.call(e)
116
+ end
117
+
118
+ def http method, url, args = {}
119
+ args.merge({
120
+ read_timeout: @options['request_timeout'],
121
+ open_timeout: @options['request_open_timeout'],
122
+ ssl_verify: @options['ssl_verify']
123
+ })
124
+ response = Pigeon::Http::Request.new(method, url, args).execute
125
+ Pigeon::Statsd.new(@options['request_name'] + '_througput', tags: [url]).capture
126
+
127
+ response
128
+ end
129
+
130
+ def circuit
131
+ Circuitbox.circuit(@options['request_name'], exceptions: [HTTP::ConnectionError, HTTP::HeaderError, HTTP::RequestError, HTTP::ResponseError, HTTP::TimeoutError])
132
+ end
133
+ end
134
+
135
+ class Error < StandardError; end
136
+ end
@@ -0,0 +1,235 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pigeon
4
+ module Http
5
+ GET = Net::HTTP::Get
6
+ HEAD = Net::HTTP::Head
7
+ PUT = Net::HTTP::Put
8
+ POST = Net::HTTP::Post
9
+ DELETE = Net::HTTP::Delete
10
+ OPTIONS = Net::HTTP::Options
11
+ TRACE = Net::HTTP::Trace
12
+ SSL_VERIFY_NONE = OpenSSL::SSL::VERIFY_NONE
13
+ SSL_VERIFY_PEER = OpenSSL::SSL::VERIFY_PEER
14
+
15
+ class << self
16
+ attr_accessor :open_timeout, :ssl_timeout, :read_timeout, :so_linger
17
+ end
18
+
19
+ class Request
20
+ VALID_PARAMETERS = %w[headers query body auth timeout open_timeout ssl_timeout read_timeout max_redirects ssl_verify]
21
+ DEFAULT_HEADERS = { 'User-Agent' => 'HTTP Client API/1.0' }
22
+ VALID_VERBS = [GET, HEAD, PUT, POST, DELETE, OPTIONS, TRACE]
23
+ VALID_SSL_VERIFICATIONS = [SSL_VERIFY_NONE, SSL_VERIFY_PEER]
24
+
25
+ def initialize verb, uri, args = {}
26
+ args.each do |k, v|
27
+ raise Error::Argument, "unknown argument #{k}" unless VALID_PARAMETERS.include?(k.to_s)
28
+ end
29
+
30
+ uri = parse_uri!(uri)
31
+ @delegate = create_request_delegate(verb, uri, args)
32
+
33
+ # set timeout
34
+ @open_timeout = args[:open_timeout] if args[:open_timeout]
35
+ @read_timeout = args[:read_timeout] if args[:read_timeout]
36
+ @ssl_timeout = args[:ssl_timeout] if args[:ssl_timeout]
37
+ @ssl_verify = args.fetch(:ssl_verify, SSL_VERIFY_PEER)
38
+
39
+ # handle basic auth
40
+ if (auth = args[:auth])
41
+ @delegate.basic_auth(auth.fetch(:username), auth.fetch(:password))
42
+ end
43
+
44
+ if uri.user && uri.password
45
+ @delegate.basic_auth(uri.user, uri.password)
46
+ end
47
+ end
48
+
49
+ def execute
50
+ response = request!(uri, @delegate)
51
+ Response.new(response, uri)
52
+ end
53
+
54
+ private
55
+
56
+ def uri
57
+ @delegate.uri
58
+ end
59
+
60
+ def parse_uri! uri
61
+ uri = uri.is_a?(URI) ? uri : URI.parse(uri)
62
+
63
+ case uri
64
+ when URI::HTTP, URI::HTTPS
65
+ raise Error::URI, "invalid URI #{uri}" if uri.host.nil?
66
+ uri
67
+ when URI::Generic
68
+ if @delegate&.uri
69
+ @delegate.uri.dup.tap { |s| s += uri }
70
+ else
71
+ raise Error::URI, "invalid URI #{uri}"
72
+ end
73
+ else
74
+ raise Error::URI, "invalid URI #{uri}"
75
+ end
76
+ rescue URI::InvalidURIError => e
77
+ raise Error::URI, "invalid URI #{uri}"
78
+ end
79
+
80
+ def create_request_delegate verb, uri, args
81
+ klass = find_delegate_class(verb)
82
+ headers = DEFAULT_HEADERS.merge(args.fetch(:headers, {}))
83
+ body = args[:body]&.to_json
84
+ query = args[:query]
85
+ uri = uri.dup
86
+ delegate = klass.new(uri, headers)
87
+
88
+ if body
89
+ raise Error::Argument, "#{verb} cannot have body" unless klass.const_get(:REQUEST_HAS_BODY)
90
+ delegate.content_type = 'application/json'
91
+ delegate.body = body
92
+ elsif query
93
+ if klass.const_get(:REQUEST_HAS_BODY)
94
+ delegate = klass.new(uri, headers)
95
+ delegate.set_form_data(query)
96
+ else
97
+ uri.query = URI.encode_www_form(query)
98
+ delegate = klass.new(uri, headers)
99
+ end
100
+ else
101
+ delegate = klass.new(uri, headers)
102
+ end
103
+
104
+ delegate
105
+ end
106
+
107
+ def request! uri, delegate
108
+ http = Net::HTTP.new(uri.host, uri.port, :ENV)
109
+
110
+ if uri.scheme == 'https'
111
+ http.use_ssl = true
112
+ http.verify_mode = @ssl_verify
113
+ end
114
+
115
+ http.open_timeout = @open_timeout if @open_timeout
116
+ http.read_timeout = @read_timeout if @read_timeout
117
+ http.ssl_timeout = @ssl_timeout if @ssl_timeout
118
+ response = http.request(delegate)
119
+
120
+ http.finish if http.started?
121
+ response
122
+ rescue URI::Error => e
123
+ raise Error::URI.new(e.message, e)
124
+ rescue Zlib::Error => e
125
+ raise Error::Zlib.new(e.message, e)
126
+ rescue Timeout::Error => e
127
+ raise Error::Timeout.new(e.message, e)
128
+ rescue Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
129
+ raise Error::Transport.new(e.message, e)
130
+ end
131
+
132
+ def find_delegate_class verb
133
+ if VALID_VERBS.include?(verb)
134
+ verb
135
+ else
136
+ find_verb_class(verb.to_s)
137
+ end
138
+ end
139
+
140
+ def find_verb_class string
141
+ case string
142
+ when /^get$/i then GET
143
+ when /^head$/i then HEAD
144
+ when /^put$/i then PUT
145
+ when /^post$/i then POST
146
+ when /^delete$/i then DELETE
147
+ else
148
+ raise Error::Argument, "invalid verb #{string}"
149
+ end
150
+ end
151
+ end
152
+
153
+ class Response
154
+ attr_reader :uri, :response
155
+
156
+ def initialize response, uri
157
+ @response = response
158
+ @uri = uri
159
+ end
160
+
161
+ def code
162
+ response.code.to_i
163
+ end
164
+
165
+ def headers
166
+ @headers ||= Hash[response.each_header.entries]
167
+ end
168
+
169
+ def body
170
+ case headers['content-encoding'].to_s.downcase
171
+ when 'gzip'
172
+ gz = Zlib::GzipReader.new(StringIO.new(response.body))
173
+ begin
174
+ gz.read
175
+ ensure
176
+ gz.close
177
+ end
178
+ when 'deflate'
179
+ Zlib.inflate(response.body)
180
+ else
181
+ response.body
182
+ end
183
+ end
184
+
185
+ def inspect
186
+ "#<#{self.class} @code=#{code} @uri=#{uri}>"
187
+ end
188
+ end
189
+
190
+ class << self
191
+ def get uri, args = {}
192
+ Request.new(GET, uri, args).execute
193
+ end
194
+
195
+ def put uri, args = {}
196
+ Request.new(PUT, uri, args).execute
197
+ end
198
+
199
+ def post uri, args = {}
200
+ Request.new(POST, uri, args).execute
201
+ end
202
+
203
+ def delete uri, args = {}
204
+ Request.new(DELETE, uri, args).execute
205
+ end
206
+
207
+ def options uri, args = {}
208
+ Request.new(OPTIONS, uri, args).execute
209
+ end
210
+
211
+ def trace uri, args = {}
212
+ Request.new(TRACE, uri, args).execute
213
+ end
214
+ end
215
+
216
+ class Error < StandardError
217
+ attr_reader :original_error
218
+
219
+ def initialize message, original_error = nil
220
+ @original_error = original_error
221
+ super(message)
222
+ end
223
+
224
+ class URI < Error; end
225
+
226
+ class Zlib < Error; end
227
+
228
+ class Timeout < Error; end
229
+
230
+ class Transport < Error; end
231
+
232
+ class Argument < Error; end
233
+ end
234
+ end
235
+ end