typhoeus 0.4.2 → 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +8 -0
  3. data/.rspec +4 -0
  4. data/.travis.yml +26 -0
  5. data/CHANGELOG.md +341 -28
  6. data/CONTRIBUTING.md +20 -0
  7. data/Gemfile +31 -2
  8. data/Guardfile +9 -0
  9. data/LICENSE +1 -1
  10. data/README.md +486 -357
  11. data/Rakefile +21 -12
  12. data/UPGRADE.md +55 -0
  13. data/lib/rack/typhoeus/middleware/params_decoder/helper.rb +76 -0
  14. data/lib/rack/typhoeus/middleware/params_decoder.rb +57 -0
  15. data/lib/rack/typhoeus.rb +1 -0
  16. data/lib/typhoeus/adapters/faraday.rb +180 -0
  17. data/lib/typhoeus/cache/dalli.rb +28 -0
  18. data/lib/typhoeus/cache/rails.rb +28 -0
  19. data/lib/typhoeus/cache/redis.rb +35 -0
  20. data/lib/typhoeus/config.rb +69 -0
  21. data/lib/typhoeus/easy_factory.rb +180 -0
  22. data/lib/typhoeus/errors/no_stub.rb +12 -0
  23. data/lib/typhoeus/errors/typhoeus_error.rb +8 -0
  24. data/lib/typhoeus/errors.rb +9 -0
  25. data/lib/typhoeus/expectation.rb +217 -0
  26. data/lib/typhoeus/hydra/addable.rb +23 -0
  27. data/lib/typhoeus/hydra/before.rb +31 -0
  28. data/lib/typhoeus/hydra/block_connection.rb +35 -0
  29. data/lib/typhoeus/hydra/cacheable.rb +15 -0
  30. data/lib/typhoeus/hydra/memoizable.rb +56 -0
  31. data/lib/typhoeus/hydra/queueable.rb +83 -0
  32. data/lib/typhoeus/hydra/runnable.rb +19 -0
  33. data/lib/typhoeus/hydra/stubbable.rb +28 -0
  34. data/lib/typhoeus/hydra.rb +84 -236
  35. data/lib/typhoeus/pool.rb +70 -0
  36. data/lib/typhoeus/railtie.rb +12 -0
  37. data/lib/typhoeus/request/actions.rb +125 -0
  38. data/lib/typhoeus/request/before.rb +30 -0
  39. data/lib/typhoeus/request/block_connection.rb +52 -0
  40. data/lib/typhoeus/request/cacheable.rb +38 -0
  41. data/lib/typhoeus/request/callbacks.rb +151 -0
  42. data/lib/typhoeus/request/marshal.rb +22 -0
  43. data/lib/typhoeus/request/memoizable.rb +38 -0
  44. data/lib/typhoeus/request/operations.rb +40 -0
  45. data/lib/typhoeus/request/responseable.rb +29 -0
  46. data/lib/typhoeus/request/streamable.rb +34 -0
  47. data/lib/typhoeus/request/stubbable.rb +30 -0
  48. data/lib/typhoeus/request.rb +186 -231
  49. data/lib/typhoeus/response/cacheable.rb +14 -0
  50. data/lib/typhoeus/response/header.rb +105 -0
  51. data/lib/typhoeus/response/informations.rb +248 -0
  52. data/lib/typhoeus/response/status.rb +106 -0
  53. data/lib/typhoeus/response.rb +60 -115
  54. data/lib/typhoeus/version.rb +3 -1
  55. data/lib/typhoeus.rb +126 -39
  56. data/perf/profile.rb +14 -0
  57. data/perf/vs_nethttp.rb +64 -0
  58. data/spec/rack/typhoeus/middleware/params_decoder/helper_spec.rb +156 -0
  59. data/spec/rack/typhoeus/middleware/params_decoder_spec.rb +31 -0
  60. data/spec/spec_helper.rb +29 -0
  61. data/spec/support/localhost_server.rb +94 -0
  62. data/spec/support/memory_cache.rb +15 -0
  63. data/spec/support/server.rb +116 -0
  64. data/spec/typhoeus/adapters/faraday_spec.rb +339 -0
  65. data/spec/typhoeus/cache/dalli_spec.rb +41 -0
  66. data/spec/typhoeus/cache/redis_spec.rb +41 -0
  67. data/spec/typhoeus/config_spec.rb +15 -0
  68. data/spec/typhoeus/easy_factory_spec.rb +143 -0
  69. data/spec/typhoeus/errors/no_stub_spec.rb +13 -0
  70. data/spec/typhoeus/expectation_spec.rb +280 -0
  71. data/spec/typhoeus/hydra/addable_spec.rb +22 -0
  72. data/spec/typhoeus/hydra/before_spec.rb +98 -0
  73. data/spec/typhoeus/hydra/block_connection_spec.rb +18 -0
  74. data/spec/typhoeus/hydra/cacheable_spec.rb +88 -0
  75. data/spec/typhoeus/hydra/memoizable_spec.rb +53 -0
  76. data/spec/typhoeus/hydra/queueable_spec.rb +98 -0
  77. data/spec/typhoeus/hydra/runnable_spec.rb +137 -0
  78. data/spec/typhoeus/hydra/stubbable_spec.rb +48 -0
  79. data/spec/typhoeus/hydra_spec.rb +22 -0
  80. data/spec/typhoeus/pool_spec.rb +137 -0
  81. data/spec/typhoeus/request/actions_spec.rb +19 -0
  82. data/spec/typhoeus/request/before_spec.rb +93 -0
  83. data/spec/typhoeus/request/block_connection_spec.rb +75 -0
  84. data/spec/typhoeus/request/cacheable_spec.rb +94 -0
  85. data/spec/typhoeus/request/callbacks_spec.rb +91 -0
  86. data/spec/typhoeus/request/marshal_spec.rb +60 -0
  87. data/spec/typhoeus/request/memoizable_spec.rb +34 -0
  88. data/spec/typhoeus/request/operations_spec.rb +101 -0
  89. data/spec/typhoeus/request/responseable_spec.rb +13 -0
  90. data/spec/typhoeus/request/stubbable_spec.rb +45 -0
  91. data/spec/typhoeus/request_spec.rb +232 -0
  92. data/spec/typhoeus/response/header_spec.rb +147 -0
  93. data/spec/typhoeus/response/informations_spec.rb +283 -0
  94. data/spec/typhoeus/response/status_spec.rb +256 -0
  95. data/spec/typhoeus/response_spec.rb +100 -0
  96. data/spec/typhoeus_spec.rb +105 -0
  97. data/typhoeus.gemspec +25 -0
  98. metadata +146 -158
  99. data/lib/typhoeus/curl.rb +0 -453
  100. data/lib/typhoeus/easy/auth.rb +0 -14
  101. data/lib/typhoeus/easy/callbacks.rb +0 -33
  102. data/lib/typhoeus/easy/ffi_helper.rb +0 -61
  103. data/lib/typhoeus/easy/infos.rb +0 -90
  104. data/lib/typhoeus/easy/options.rb +0 -115
  105. data/lib/typhoeus/easy/proxy.rb +0 -20
  106. data/lib/typhoeus/easy/ssl.rb +0 -82
  107. data/lib/typhoeus/easy.rb +0 -115
  108. data/lib/typhoeus/filter.rb +0 -28
  109. data/lib/typhoeus/form.rb +0 -61
  110. data/lib/typhoeus/header.rb +0 -54
  111. data/lib/typhoeus/hydra/callbacks.rb +0 -24
  112. data/lib/typhoeus/hydra/connect_options.rb +0 -61
  113. data/lib/typhoeus/hydra/stubbing.rb +0 -68
  114. data/lib/typhoeus/hydra_mock.rb +0 -131
  115. data/lib/typhoeus/multi.rb +0 -146
  116. data/lib/typhoeus/param_processor.rb +0 -43
  117. data/lib/typhoeus/remote.rb +0 -306
  118. data/lib/typhoeus/remote_method.rb +0 -108
  119. data/lib/typhoeus/remote_proxy_object.rb +0 -50
  120. data/lib/typhoeus/utils.rb +0 -50
data/README.md CHANGED
@@ -1,440 +1,569 @@
1
- # Typhoeus [![Build Status](https://secure.travis-ci.org/typhoeus/typhoeus.png?branch=master)](http://travis-ci.org/typhoeus/typhoeus)
2
-
3
- [the mailing list](http://groups.google.com/group/typhoeus)
4
-
5
- ## Summary
6
-
7
- Like a modern code version of the mythical beast with 100 serpent heads,
8
- Typhoeus runs HTTP requests in parallel while cleanly encapsulating handling
9
- logic. To be a little more specific, it’s a library for accessing web services
10
- in Ruby. It’s specifically designed for building RESTful service oriented
11
- architectures in Ruby that need to be fast enough to process calls to multiple
12
- services within the client’s HTTP request/response life cycle.
13
-
14
- Some of the awesome features are parallel request execution, memoization of
15
- request responses (so you don’t make the same request multiple times in a
16
- single group), built in support for caching responses to memcached (or
17
- whatever), and mocking capability baked in. It uses libcurl and libcurl-multi
18
- to work this speedy magic. I wrote the bindings myself so it’s yet another
19
- Ruby libcurl library, but with some extra awesomeness added in. FFI is used to
20
- interface with the library so it works with any Ruby implementation.
21
-
22
- ## Installation
23
-
24
- Typhoeus requires you to have a current version of libcurl installed. The
25
- easiest solution is to use your system’s package manager to install it. If
26
- that doesn’t work, you can grab a package off of [the curl
27
- website](http://curl.haxx.se/download.html) and manually install it following
28
- the instructions given there. Typhoeus will work with version 7.19.4 or higher
29
- (earlier versions might work but no guarantees are provided).
30
-
31
- To install Typhoeus, simply run:
32
-
33
- gem install typhoeus
34
-
35
- If you’re on Debian or Ubuntu and getting errors while trying to install, it
36
- could be because you don’t have the latest version of libcurl installed. Do
37
- this to fix:
38
-
39
- sudo apt-get install libcurl4-gnutls-dev
40
-
41
- If you’re still having issues, please let me know on [the mailing
42
- list](http://groups.google.com/group/typhoeus).
43
-
44
- There’s one other thing you should know. The Easy object (which is just a
45
- libcurl thing) allows you to set timeout values in milliseconds. However, for
46
- this to work you need to build libcurl with c-ares support built in.
47
-
48
- ## Windows Support
49
-
50
- Typhoeus runs perfectly on Windows. The tricky part is knowing how to install
51
- libcurl in the absence of a package manager.
52
-
53
- To install libcurl, simply grab [the latest libcurl
54
- package](http://curl.haxx.se/download.html#Win32) off of the curl website,
55
- extract the bin directory, and then add the path to the bin directory into the
56
- PATH environment variable. Ruby with then be able to find libcurl properly and
57
- everything will just work.
58
-
59
- ## Usage
60
-
61
- The primary interface for Typhoeus is comprised of three classes: Request,
62
- Response, and Hydra. Request represents an HTTP request object, response
63
- represents an HTTP response, and Hydra manages making parallel HTTP
64
- connections.
65
-
66
- require 'rubygems'
67
- require 'typhoeus'
68
- require 'json'
69
-
70
- # the request object
71
- request = Typhoeus::Request.new("http://www.pauldix.net",
72
- :body => "this is a request body",
73
- :method => :post,
74
- :headers => {:Accept => "text/html"},
75
- :timeout => 100, # milliseconds
76
- :cache_timeout => 60, # seconds
77
- :params => {:field1 => "a field"})
78
- # we can see from this that the first argument is the url. the second is a set of options.
79
- # the options are all optional. The default for :method is :get. Timeout is measured in milliseconds.
80
- # cache_timeout is measured in seconds.
81
-
82
- # Run the request via Hydra.
83
- hydra = Typhoeus::Hydra.new
84
- hydra.queue(request)
85
- hydra.run
86
-
87
- # the response object will be set after the request is run
88
- response = request.response
89
- response.code # http status code
90
- response.time # time in seconds the request took
91
- response.headers # the http headers
92
- response.headers_hash # http headers put into a hash
93
- response.body # the response body
94
-
95
- **Making Quick Requests**
96
-
97
- The request object has some convenience methods for performing single HTTP
98
- requests. The arguments are the same as those you pass into the request
99
- constructor.
100
-
101
- response = Typhoeus::Request.get("http://www.pauldix.net")
102
- response = Typhoeus::Request.head("http://www.pauldix.net")
103
- response = Typhoeus::Request.put("http://localhost:3000/posts/1", :body => "whoo, a body")
104
- response = Typhoeus::Request.post("http://localhost:3000/posts", :params => {:title => "test post", :content => "this is my test"})
105
- response = Typhoeus::Request.delete("http://localhost:3000/posts/1")
106
-
107
- **Handling HTTP errors**
1
+ # Typhoeus [![Build Status](https://img.shields.io/travis/typhoeus/typhoeus/master.svg)](https://travis-ci.org/typhoeus/typhoeus) [![Code Climate](https://img.shields.io/codeclimate/maintainability/typhoeus/typhoeus.svg)](https://codeclimate.com/github/typhoeus/typhoeus) [![Gem Version](https://img.shields.io/gem/v/typhoeus.svg)](https://rubygems.org/gems/typhoeus)
2
+
3
+ Like a modern code version of the mythical beast with 100 serpent heads, Typhoeus runs HTTP requests in parallel while cleanly encapsulating handling logic.
4
+
5
+ ## Example
6
+
7
+ A single request:
8
+
9
+ ```ruby
10
+ Typhoeus.get("www.example.com", followlocation: true)
11
+ ```
12
+
13
+ Parallel requests:
14
+
15
+ ```ruby
16
+ hydra = Typhoeus::Hydra.new
17
+ 10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) }
18
+ hydra.run
19
+ ```
20
+
21
+ ## Installation
22
+ Add the following line to your Gemfile:
23
+ ```
24
+ gem "typhoeus"
25
+ ```
26
+ Then run `bundle install`
27
+
28
+ Or install it yourself as:
29
+
30
+ ```
31
+ gem install typhoeus
32
+ ```
33
+
34
+ ## Project Tracking
35
+
36
+ * [Documentation](http://rubydoc.info/github/typhoeus/typhoeus/frames/Typhoeus) (GitHub master)
37
+ * [Mailing list](http://groups.google.com/group/typhoeus)
38
+
39
+ ## Usage
40
+
41
+ ### Introduction
42
+
43
+ The primary interface for Typhoeus is comprised of three classes: Request, Response, and Hydra. Request represents an HTTP request object, response represents an HTTP response, and Hydra manages making parallel HTTP connections.
44
+
45
+ ```ruby
46
+ request = Typhoeus::Request.new(
47
+ "www.example.com",
48
+ method: :post,
49
+ body: "this is a request body",
50
+ params: { field1: "a field" },
51
+ headers: { Accept: "text/html" }
52
+ )
53
+ ```
54
+
55
+ We can see from this that the first argument is the url. The second is a set of options.
56
+ The options are all optional. The default for `:method` is `:get`.
57
+
58
+ When you want to send URL parameters, you can use `:params` hash to do so. Please note that in case of you should send a request via `x-www-form-urlencoded` parameters, you need to use `:body` hash instead. `params` are for URL parameters and `:body` is for the request body.
59
+
60
+ #### Sending requests through the proxy
61
+
62
+ Add a proxy url to the list of options:
63
+
64
+ ```ruby
65
+ options = {proxy: 'http://myproxy.org'}
66
+ req = Typhoeus::Request.new(url, options)
67
+ ```
68
+
69
+ If your proxy requires authentication, add it with `proxyuserpwd` option key:
70
+
71
+ ```ruby
72
+ options = {proxy: 'http://proxyurl.com', proxyuserpwd: 'user:password'}
73
+ req = Typhoeus::Request.new(url, options)
74
+ ```
75
+
76
+ Note that `proxyuserpwd` is a colon-separated username and password, in the vein of basic auth `userpwd` option.
77
+
78
+
79
+ You can run the query either on its own or through the hydra:
80
+
81
+ ``` ruby
82
+ request.run
83
+ #=> <Typhoeus::Response ... >
84
+ ```
85
+
86
+ ```ruby
87
+ hydra = Typhoeus::Hydra.hydra
88
+ hydra.queue(request)
89
+ hydra.run
90
+ ```
91
+
92
+ The response object will be set after the request is run.
93
+
94
+ ```ruby
95
+ response = request.response
96
+ response.code
97
+ response.total_time
98
+ response.headers
99
+ response.body
100
+ ```
101
+
102
+ ### Making Quick Requests
103
+
104
+ Typhoeus has some convenience methods for performing single HTTP requests. The arguments are the same as those you pass into the request constructor.
105
+
106
+ ```ruby
107
+ Typhoeus.get("www.example.com")
108
+ Typhoeus.head("www.example.com")
109
+ Typhoeus.put("www.example.com/posts/1", body: "whoo, a body")
110
+ Typhoeus.patch("www.example.com/posts/1", body: "a new body")
111
+ Typhoeus.post("www.example.com/posts", body: { title: "test post", content: "this is my test"})
112
+ Typhoeus.delete("www.example.com/posts/1")
113
+ Typhoeus.options("www.example.com")
114
+ ```
115
+ #### Sending params in the body with PUT
116
+ When using POST the content-type is set automatically to 'application/x-www-form-urlencoded'. That's not the case for any other method like PUT, PATCH, HEAD and so on, irrespective of whether you are using body or not. To get the same result as POST, i.e. a hash in the body coming through as params in the receiver, you need to set the content-type as shown below:
117
+ ```ruby
118
+ Typhoeus.put("www.example.com/posts/1",
119
+ headers: {'Content-Type'=> "application/x-www-form-urlencoded"},
120
+ body: {title:"test post updated title", content: "this is my updated content"}
121
+ )
122
+ ```
123
+
124
+ ### Handling HTTP errors
108
125
 
109
126
  You can query the response object to figure out if you had a successful
110
127
  request or not. Here’s some example code that you might use to handle errors.
111
-
112
- request.on_complete do |response|
113
- if response.success?
114
- # hell yeah
115
- elsif response.timed_out?
116
- # aw hell no
117
- log("got a time out")
118
- elsif response.code == 0
119
- # Could not get an http response, something's wrong.
120
- log(response.curl_error_message)
121
- else
122
- # Received a non-successful http response.
123
- log("HTTP request failed: " + response.code.to_s)
124
- end
125
- end
128
+ The callbacks are executed right after the request is finished, make sure to define
129
+ them before running the request.
130
+
131
+ ```ruby
132
+ request = Typhoeus::Request.new("www.example.com", followlocation: true)
133
+
134
+ request.on_complete do |response|
135
+ if response.success?
136
+ # hell yeah
137
+ elsif response.timed_out?
138
+ # aw hell no
139
+ log("got a time out")
140
+ elsif response.code == 0
141
+ # Could not get an http response, something's wrong.
142
+ log(response.return_message)
143
+ else
144
+ # Received a non-successful http response.
145
+ log("HTTP request failed: " + response.code.to_s)
146
+ end
147
+ end
148
+
149
+ request.run
150
+ ```
126
151
 
127
152
  This also works with serial (blocking) requests in the same fashion. Both
128
153
  serial and parallel requests return a Response object.
129
154
 
130
- **Handling file uploads**
155
+ ### Handling file uploads
131
156
 
132
157
  A File object can be passed as a param for a POST request to handle uploading
133
158
  files to the server. Typhoeus will upload the file as the original file name
134
159
  and use Mime::Types to set the content type.
135
160
 
136
- response = Typhoeus::Request.post("http://localhost:3000/posts",
137
- :params => {
138
- :title => "test post", :content => "this is my test",
139
- :file => File.open("thesis.txt","r")
140
- }
141
- )
161
+ ```ruby
162
+ Typhoeus.post(
163
+ "http://localhost:3000/posts",
164
+ body: {
165
+ title: "test post",
166
+ content: "this is my test",
167
+ file: File.open("thesis.txt","r")
168
+ }
169
+ )
170
+ ```
171
+
172
+ ### Streaming the response body
173
+
174
+ Typhoeus can stream responses. When you're expecting a large response,
175
+ set the `on_body` callback on a request. Typhoeus will yield to the callback
176
+ with chunks of the response, as they're read. When you set an `on_body` callback,
177
+ Typhoeus will not store the complete response.
178
+
179
+ ```ruby
180
+ downloaded_file = File.open 'huge.iso', 'wb'
181
+ request = Typhoeus::Request.new("www.example.com/huge.iso")
182
+ request.on_headers do |response|
183
+ if response.code != 200
184
+ raise "Request failed"
185
+ end
186
+ end
187
+ request.on_body do |chunk|
188
+ downloaded_file.write(chunk)
189
+ end
190
+ request.on_complete do |response|
191
+ downloaded_file.close
192
+ # Note that response.body is ""
193
+ end
194
+ request.run
195
+ ```
196
+
197
+ If you need to interrupt the stream halfway,
198
+ you can return the `:abort` symbol from the `on_body` block, example:
199
+
200
+ ```ruby
201
+ request.on_body do |chunk|
202
+ buffer << chunk
203
+ :abort if buffer.size > 1024 * 1024
204
+ end
205
+ ```
206
+
207
+ This will properly stop the stream internally and avoid any memory leak which
208
+ may happen if you interrupt with something like a `return`, `throw` or `raise`.
209
+
210
+ ### Making Parallel Requests
211
+
212
+ Generally, you should be running requests through hydra. Here is how that looks:
213
+
214
+ ```ruby
215
+ hydra = Typhoeus::Hydra.hydra
216
+
217
+ first_request = Typhoeus::Request.new("http://example.com/posts/1")
218
+ first_request.on_complete do |response|
219
+ third_url = response.body
220
+ third_request = Typhoeus::Request.new(third_url)
221
+ hydra.queue third_request
222
+ end
223
+ second_request = Typhoeus::Request.new("http://example.com/posts/2")
224
+
225
+ hydra.queue first_request
226
+ hydra.queue second_request
227
+ hydra.run # this is a blocking call that returns once all requests are complete
228
+ ```
229
+
230
+ The execution of that code goes something like this. The first and second requests are built and queued. When hydra is run the first and second requests run in parallel. When the first request completes, the third request is then built and queued, in this example based on the result of the first request. The moment it is queued Hydra starts executing it. Meanwhile the second request would continue to run (or it could have completed before the first). Once the third request is done, `hydra.run` returns.
231
+
232
+ How to get an array of response bodies back after executing a queue:
233
+
234
+ ```ruby
235
+ hydra = Typhoeus::Hydra.new
236
+ requests = 10.times.map {
237
+ request = Typhoeus::Request.new("www.example.com", followlocation: true)
238
+ hydra.queue(request)
239
+ request
240
+ }
241
+ hydra.run
242
+
243
+ responses = requests.map { |request|
244
+ request.response.body
245
+ }
246
+ ```
247
+ `hydra.run` is a blocking request. You can also use the `on_complete` callback to handle each request as it completes:
248
+
249
+ ```ruby
250
+ hydra = Typhoeus::Hydra.new
251
+ 10.times do
252
+ request = Typhoeus::Request.new("www.example.com", followlocation: true)
253
+ request.on_complete do |response|
254
+ #do_something_with response
255
+ end
256
+ hydra.queue(request)
257
+ end
258
+ hydra.run
259
+ ```
260
+
261
+ ### Making Parallel Requests with Faraday + Typhoeus
262
+
263
+ ```ruby
264
+ require 'faraday'
265
+
266
+ conn = Faraday.new(:url => 'http://httppage.com') do |builder|
267
+ builder.request :url_encoded
268
+ builder.response :logger
269
+ builder.adapter :typhoeus
270
+ end
271
+
272
+ conn.in_parallel do
273
+ response1 = conn.get('/first')
274
+ response2 = conn.get('/second')
275
+
276
+ # these will return nil here since the
277
+ # requests have not been completed
278
+ response1.body
279
+ response2.body
280
+ end
281
+
282
+ # after it has been completed the response information is fully available
283
+ # response1.status, etc
284
+ response1.body
285
+ response2.body
286
+ ```
287
+
288
+ ### Specifying Max Concurrency
289
+
290
+ Hydra will also handle how many requests you can make in parallel. Things will get flakey if you try to make too many requests at the same time. The built in limit is 200. When more requests than that are queued up, hydra will save them for later and start the requests as others are finished. You can raise or lower the concurrency limit through the Hydra constructor.
291
+
292
+ ```ruby
293
+ Typhoeus::Hydra.new(max_concurrency: 20)
294
+ ```
142
295
 
143
- **Making Parallel Requests**
144
-
145
- # Generally, you should be running requests through hydra. Here is how that looks
146
- hydra = Typhoeus::Hydra.new
147
-
148
- first_request = Typhoeus::Request.new("http://localhost:3000/posts/1.json")
149
- first_request.on_complete do |response|
150
- post = JSON.parse(response.body)
151
- third_request = Typhoeus::Request.new(post.links.first) # get the first url in the post
152
- third_request.on_complete do |response|
153
- # do something with that
154
- end
155
- hydra.queue third_request
156
- return post
157
- end
158
- second_request = Typhoeus::Request.new("http://localhost:3000/users/1.json")
159
- second_request.on_complete do |response|
160
- JSON.parse(response.body)
161
- end
162
- hydra.queue first_request
163
- hydra.queue second_request
164
- hydra.run # this is a blocking call that returns once all requests are complete
165
-
166
- first_request.handled_response # the value returned from the on_complete block
167
- second_request.handled_response # the value returned from the on_complete block (parsed JSON)
168
-
169
- The execution of that code goes something like this. The first and second
170
- requests are built and queued. When hydra is run the first and second requests
171
- run in parallel. When the first request completes, the third request is then
172
- built and queued up. The moment it is queued Hydra starts executing it.
173
- Meanwhile the second request would continue to run (or it could have completed
174
- before the first). Once the third request is done, hydra.run returns.
175
-
176
- **Specifying Max Concurrency**
177
-
178
- Hydra will also handle how many requests you can make in parallel. Things will
179
- get flakey if you try to make too many requests at the same time. The built in
180
- limit is 200. When more requests than that are queued up, hydra will save them
181
- for later and start the requests as others are finished. You can raise or
182
- lower the concurrency limit through the Hydra constructor.
183
-
184
- hydra = Typhoeus::Hydra.new(:max_concurrency => 20) # keep from killing some servers
185
-
186
- **Memoization**
187
-
188
- Hydra memoizes requests within a single run call. You can also disable
189
- memoization.
190
-
191
- hydra = Typhoeus::Hydra.new
192
- 2.times do
193
- r = Typhoeus::Request.new("http://localhost/3000/users/1")
194
- hydra.queue r
195
- end
196
- hydra.run # this will result in a single request being issued. However, the on_complete handlers of both will be called.
197
- hydra.disable_memoization
198
- 2.times do
199
- r = Typhoeus::Request.new("http://localhost/3000/users/1")
200
- hydra.queue r
201
- end
202
- hydra.run # this will result in a two requests.
203
-
204
- **Caching**
205
-
206
- Hydra includes built in support for creating cache getters and setters. In the
207
- following example, if there is a cache hit, the cached object is passed to the
208
- on\_complete handler of the request object.
209
-
210
- hydra = Typhoeus::Hydra.new
211
- hydra.cache_setter do |request|
212
- @cache.set(request.cache_key, request.response, request.cache_timeout)
213
- end
214
-
215
- hydra.cache_getter do |request|
216
- @cache.get(request.cache_key) rescue nil
217
- end
218
-
219
- **Direct Stubbing**
296
+ ### Memoization
220
297
 
221
- Hydra allows you to stub out specific urls and patterns to avoid hitting
222
- remote servers while testing.
298
+ Hydra memoizes requests within a single run call. You have to enable memoization.
299
+ This will result in a single request being issued. However, the on_complete handlers of both will be called.
223
300
 
224
- hydra = Typhoeus::Hydra.new
225
- response = Response.new(:code => 200, :headers => "", :body => "{'name' : 'paul'}", :time => 0.3)
226
- hydra.stub(:get, "http://localhost:3000/users/1").and_return(response)
301
+ ```ruby
302
+ Typhoeus::Config.memoize = true
227
303
 
228
- request = Typhoeus::Request.new("http://localhost:3000/users/1")
229
- request.on_complete do |response|
230
- JSON.parse(response.body)
231
- end
232
- hydra.queue request
233
- hydra.run
304
+ hydra = Typhoeus::Hydra.new(max_concurrency: 1)
305
+ 2.times do
306
+ hydra.queue Typhoeus::Request.new("www.example.com")
307
+ end
308
+ hydra.run
309
+ ```
234
310
 
235
- The queued request will hit the stub. The on\_complete handler will be called
236
- and will be passed the response object. You can also specify a regex to match
237
- urls.
311
+ This will result in two requests.
238
312
 
239
- hydra.stub(:get, /http\:\/\/localhost\:3000\/users\/.*/).and_return(response)
240
- # any requests for a user will be stubbed out with the pre built response.
313
+ ```ruby
314
+ Typhoeus::Config.memoize = false
315
+
316
+ hydra = Typhoeus::Hydra.new(max_concurrency: 1)
317
+ 2.times do
318
+ hydra.queue Typhoeus::Request.new("www.example.com")
319
+ end
320
+ hydra.run
321
+ ```
241
322
 
242
- **The Singleton**
323
+ ### Caching
243
324
 
244
- All of the quick requests are done using the singleton hydra object. If you
245
- want to enable caching or stubbing on the quick requests, set those options on
246
- the singleton.
325
+ Typhoeus includes built in support for caching. In the following example, if there is a cache hit, the cached object is passed to the on_complete handler of the request object.
247
326
 
248
- hydra = Typhoeus::Hydra.hydra
249
- hydra.stub(:get, "http://localhost:3000/users")
327
+ ```ruby
328
+ class Cache
329
+ def initialize
330
+ @memory = {}
331
+ end
250
332
 
251
- **Timeouts**
333
+ def get(request)
334
+ @memory[request]
335
+ end
252
336
 
253
- No exceptions are raised on HTTP timeouts. You can check whether a request
254
- timed out with the following methods:
337
+ def set(request, response)
338
+ @memory[request] = response
339
+ end
340
+ end
255
341
 
256
- easy.timed_out? # for a raw Easy handle
257
- response.timed_out? # for a Response handle
342
+ Typhoeus::Config.cache = Cache.new
258
343
 
259
- **Following Redirections**
344
+ Typhoeus.get("www.example.com").cached?
345
+ #=> false
346
+ Typhoeus.get("www.example.com").cached?
347
+ #=> true
348
+ ```
260
349
 
261
- Use `:follow_location => true`, eg:
350
+ For use with [Dalli](https://github.com/mperham/dalli):
262
351
 
263
- Typhoeus::Request.new(“www.example.com”, :follow_location => true)
352
+ ```ruby
353
+ dalli = Dalli::Client.new(...)
354
+ Typhoeus::Config.cache = Typhoeus::Cache::Dalli.new(dalli)
355
+ ```
264
356
 
265
- **Basic Authentication**
357
+ For use with Rails:
266
358
 
267
- response = Typhoeus::Request.get("http://twitter.com/statuses/followers.json",
268
- :username => username, :password => password)
359
+ ```ruby
360
+ Typhoeus::Config.cache = Typhoeus::Cache::Rails.new
361
+ ```
269
362
 
270
- **SSL**
363
+ For use with [Redis](https://github.com/redis/redis-rb):
271
364
 
272
- SSL comes built in to libcurl so it’s in Typhoeus as well. If you pass in a
273
- url with “https” it should just work assuming that you have your [cert
274
- bundle](http://curl.haxx.se/docs/caextract.html) in order and the server is
275
- verifiable. You must also have libcurl built with SSL support enabled. You can
276
- check that by doing this:
365
+ ```ruby
366
+ redis = Redis.new(...)
367
+ Typhoeus::Config.cache = Typhoeus::Cache::Redis.new(redis)
368
+ ```
277
369
 
278
- Typhoeus::Easy.new.curl_version # output should include OpenSSL/...
370
+ All three of these adapters take an optional keyword argument `default_ttl`, which sets a default
371
+ TTL on cached responses (in seconds), for requests which do not have a cache TTL set.
279
372
 
280
- Now, even if you have libcurl built with OpenSSL you may still have a messed
281
- up cert bundle or if you’re hitting a non-verifiable SSL server then you’ll
282
- have to disable peer verification to make SSL work. Like this:
373
+ You may also selectively choose not to cache by setting `cache` to `false` on a request or to use
374
+ a different adapter.
283
375
 
284
- Typhoeus::Request.get("https://mail.google.com/mail", :disable_ssl_peer_verification => true)
376
+ ```ruby
377
+ cache = Cache.new
378
+ Typhoeus.get("www.example.com", cache: cache)
379
+ ```
285
380
 
286
- If you are getting “SSL: certificate subject name does not match target host
287
- name” from curl (ex:- you are trying to access to b.c.host.com when the
288
- certificate subject is \*.host.com). You can disable host verification. Like
289
- this:
381
+ ### Direct Stubbing
290
382
 
291
- Typhoeus::Request.get("https://mail.google.com/mail", :disable_ssl_host_verification => true)
383
+ Hydra allows you to stub out specific urls and patterns to avoid hitting
384
+ remote servers while testing.
292
385
 
293
- **LibCurl**
386
+ ```ruby
387
+ response = Typhoeus::Response.new(code: 200, body: "{'name' : 'paul'}")
388
+ Typhoeus.stub('www.example.com').and_return(response)
294
389
 
295
- Typhoeus also has a more raw libcurl interface. These are the Easy and Multi
296
- objects. If you’re into accessing just the raw libcurl style, those are your
297
- best bet.
390
+ Typhoeus.get("www.example.com") == response
391
+ #=> true
392
+ ```
298
393
 
299
- However, by using this raw interface, you do not get access to Hydra-specific
300
- features, such as stubbing/mocking.
394
+ The queued request will hit the stub. You can also specify a regex to match urls.
301
395
 
302
- SSL Certs can be provided to the Easy interface:
396
+ ```ruby
397
+ response = Typhoeus::Response.new(code: 200, body: "{'name' : 'paul'}")
398
+ Typhoeus.stub(/example/).and_return(response)
303
399
 
304
- e = Typhoeus::Easy.new
305
- e.url = "https://example.com/action"
306
- s.ssl_cacert = "ca_file.cer"
307
- e.ssl_cert = "acert.crt"
308
- e.ssl_key = "akey.key"
309
- [...]
310
- e.perform
400
+ Typhoeus.get("www.example.com") == response
401
+ #=> true
402
+ ```
311
403
 
312
- or directly to a Typhoeus::Request :
404
+ You may also specify an array for the stub to return sequentially.
313
405
 
314
- e = Typhoeus::Request.get("https://example.com/action",
315
- :ssl_cacert => "ca_file.cer",
316
- :ssl_cert => "acert.crt",
317
- :ssl_key => "akey.key",
318
- [...]
319
- end
406
+ ```ruby
407
+ Typhoeus.stub('www.example.com').and_return([response1, response2])
320
408
 
321
- ## Advanced authentication
409
+ Typhoeus.get('www.example.com') == response1 #=> true
410
+ Typhoeus.get('www.example.com') == response2 #=> true
411
+ ```
322
412
 
323
- Thanks for the authentication piece and this description go to Oleg Ivanov
324
- (morhekil). The major reason to start this fork was the need to perform NTLM
325
- authentication in Ruby, and other libcurl’s authentications method were made
326
- possible as a result. Now you can do it via Typhoeus::Easy interface using the
327
- following API.
413
+ When testing make sure to clear your expectations or the stubs will persist between tests. The following can be included in your spec_helper.rb file to do this automatically.
328
414
 
329
- e = Typhoeus::Easy.new
330
- e.auth = {
331
- :username => 'username',
332
- :password => 'password',
333
- :method => Typhoeus::Easy::AUTH_TYPES[:CURLAUTH_NTLM]
334
- }
335
- e.url = "http://example.com/auth_ntlm"
336
- e.method = :get
337
- e.perform
415
+ ```ruby
416
+ RSpec.configure do |config|
417
+ config.before :each do
418
+ Typhoeus::Expectation.clear
419
+ end
420
+ end
421
+ ```
338
422
 
339
- **Other authentication types**
423
+ ### Timeouts
340
424
 
341
- The following authentication types are available:
425
+ No exceptions are raised on HTTP timeouts. You can check whether a request timed out with the following method:
342
426
 
343
- * CURLAUTH\_BASIC
344
- * CURLAUTH\_DIGEST
345
- * CURLAUTH\_GSSNEGOTIATE
346
- * CURLAUTH\_NTLM
347
- * CURLAUTH\_DIGEST\_IE
348
- * CURLAUTH\_AUTO
427
+ ```ruby
428
+ Typhoeus.get("www.example.com", timeout: 1).timed_out?
429
+ ```
349
430
 
350
- The last one (CURLAUTH\_AUTO) is really a combination of all previous methods
351
- and is provided by Typhoeus for convenience. When you set authentication to
352
- auto, Typhoeus will retrieve the given URL first and examine it’s headers to
353
- confirm what auth types are supported by the server. The it will select the
354
- strongest of available auth methods and will send the second request using the
355
- selected authentication method.
431
+ Timed out responses also have their success? method return false.
356
432
 
357
- **Authentication via the quick request interface**
433
+ There are two different timeouts available: [`timeout`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTIMEOUT)
434
+ and [`connecttimeout`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUT).
435
+ `timeout` is the time limit for the entire request in seconds.
436
+ `connecttimeout` is the time limit for just the connection phase, again in seconds.
358
437
 
359
- There’s also an easy way to perform any kind of authentication via the quick
360
- request interface:
438
+ There are two additional more fine grained options `timeout_ms` and
439
+ `connecttimeout_ms`. These options offer millisecond precision but are not always available (for instance on linux if `nosignal` is not set to true).
361
440
 
362
- e = Typhoeus::Request.get("http://example.com",
363
- :username => 'username',
364
- :password => 'password',
365
- :auth_method => :ntlm)
441
+ When you pass a floating point `timeout` (or `connecttimeout`) Typhoeus will set `timeout_ms` for you if it has not been defined. The actual timeout values passed to curl will always be rounded up.
366
442
 
367
- All methods listed above is available in a shorter form :basic, :digest,
368
- :gssnegotiate, :ntlm, :digest\_ie, :auto.
443
+ DNS timeouts of less than one second are not supported unless curl is compiled with an asynchronous resolver.
369
444
 
370
- **Query of available auth types**
445
+ The default `timeout` is 0 (zero) which means curl never times out during transfer. The default `connecttimeout` is 300 seconds. A `connecttimeout` of 0 will also result in the default `connecttimeout` of 300 seconds.
371
446
 
372
- After the initial request you can get the authentication types available on
373
- the server via Typhoues::Easy#auth\_methods call. It will return a number
447
+ ### Following Redirections
374
448
 
375
- that you’ll need to decode yourself, please refer to easy.rb source code to
376
- see the numeric values of different auth types.
449
+ Use `followlocation: true`, eg:
377
450
 
378
- ## Verbose debug output
451
+ ```ruby
452
+ Typhoeus.get("www.example.com", followlocation: true)
453
+ ```
379
454
 
380
- Sometime it’s useful to see verbose output from curl. You may now enable it:
455
+ ### Basic Authentication
381
456
 
382
- e = Typhoeus::Easy.new
383
- e.verbose = 1
457
+ ```ruby
458
+ Typhoeus::Request.get("www.example.com", userpwd: "user:password")
459
+ ```
384
460
 
385
- or using the quick request:
461
+ ### Compression
386
462
 
387
- e = Typhoeus::Request.get("http://example.com", :verbose => true)
463
+ ```ruby
464
+ Typhoeus.get("www.example.com", accept_encoding: "gzip")
465
+ ```
388
466
 
389
- Just remember that libcurl prints it’s debug output to the console (to
390
- STDERR), so you’ll need to run your scripts from the console to see it.
467
+ The above has a different behavior than setting the header directly in the header hash, eg:
468
+ ```ruby
469
+ Typhoeus.get("www.example.com", headers: {"Accept-Encoding" => "gzip"})
470
+ ```
471
+
472
+ Setting the header hash directly will not include the `--compressed` flag in the libcurl command and therefore libcurl will not decompress the response. If you want the `--compressed` flag to be added automatically, set `:accept_encoding` Typhoeus option.
473
+
474
+
475
+ ### Cookies
476
+
477
+ ```ruby
478
+ Typhoeus::Request.get("www.example.com", cookiefile: "/path/to/file", cookiejar: "/path/to/file")
479
+ ```
391
480
 
392
- ## Benchmarks
481
+ Here, `cookiefile` is a file to read cookies from, and `cookiejar` is a file to write received cookies to.
482
+ If you just want cookies enabled, you need to pass the same filename for both options.
393
483
 
394
- I set up a benchmark to test how the parallel performance works vs Ruby’s
395
- built in NET::HTTP. The setup was a local evented HTTP server that would take
396
- a request, sleep for 500 milliseconds and then issued a blank response. I set
397
- up the client to call this 20 times. Here are the results:
484
+ ### Other CURL options
398
485
 
399
- net::http 0.030000 0.010000 0.040000 ( 10.054327)
400
- typhoeus 0.020000 0.070000 0.090000 ( 0.508817)
486
+ Are available and documented [here](http://rubydoc.info/github/typhoeus/ethon/Ethon/Easy/Options)
487
+
488
+ ### SSL
489
+
490
+ SSL comes built in to libcurl so it’s in Typhoeus as well. If you pass in a
491
+ url with "https" it should just work assuming that you have your [cert
492
+ bundle](http://curl.haxx.se/docs/caextract.html) in order and the server is
493
+ verifiable. You must also have libcurl built with SSL support enabled. You can
494
+ check that by doing this:
495
+
496
+ ```
497
+ curl --version
498
+ ```
499
+
500
+ Now, even if you have libcurl built with OpenSSL you may still have a messed
501
+ up cert bundle or if you’re hitting a non-verifiable SSL server then you’ll
502
+ have to disable peer verification to make SSL work. Like this:
503
+
504
+ ```ruby
505
+ Typhoeus.get("https://www.example.com", ssl_verifypeer: false)
506
+ ```
507
+
508
+ If you are getting "SSL: certificate subject name does not match target host
509
+ name" from curl (ex:- you are trying to access to b.c.host.com when the
510
+ certificate subject is \*.host.com). You can disable host verification. Like
511
+ this:
512
+
513
+ ```ruby
514
+ # host checking enabled
515
+ Typhoeus.get("https://www.example.com", ssl_verifyhost: 2)
516
+ # host checking disabled
517
+ Typhoeus.get("https://www.example.com", ssl_verifyhost: 0)
518
+ ```
519
+
520
+ ### Verbose debug output
521
+
522
+ It’s sometimes useful to see verbose output from curl. You can enable it on a per-request basis:
523
+
524
+ ```ruby
525
+ Typhoeus.get("http://example.com", verbose: true)
526
+ ```
527
+
528
+ or globally:
529
+
530
+ ```ruby
531
+ Typhoeus::Config.verbose = true
532
+ ```
533
+
534
+ Just remember that libcurl prints it’s debug output to the console (to
535
+ STDERR), so you’ll need to run your scripts from the console to see it.
401
536
 
402
- We can see from this that NET::HTTP performs as expected, taking 10 seconds to
403
- run 20 500ms requests. Typhoeus only takes 500ms (the time of the response
404
- that took the longest.) One other thing to note is that Typhoeus keeps a pool
405
- of libcurl Easy handles to use. For this benchmark I warmed the pool first. So
406
- if you test this out it may be a bit slower until the Easy handle pool has
407
- enough in it to run all the simultaneous requests. For some reason the easy
408
- handles can take quite some time to allocate.
537
+ ### Default User Agent Header
409
538
 
410
- ## Running the specs
539
+ In many cases, all HTTP requests made by an application require the same User-Agent header set. Instead of supplying it on a per-request basis by supplying a custom header, it is possible to override it for all requests using:
411
540
 
412
- Running the specs requires a couple of Sinatra servers to be booted. rake spec
413
- will do this for you, but if you’re needing to run the specs a lot, spinning
414
- up the servers manually and leaving them running should speed things up a bit.
415
- Do this:
416
541
 
417
- # Start up the test servers (in another terminal)
418
- rake start_test_servers
542
+ ```ruby
543
+ Typhoeus::Config.user_agent = "custom user agent"
544
+ ```
419
545
 
420
- # Run the specs
421
- rake spec
546
+ ### Running the specs
422
547
 
548
+ Running the specs should be as easy as:
423
549
 
424
- ## Next Steps
550
+ ```
551
+ bundle install
552
+ bundle exec rake
553
+ ```
554
+ ## Semantic Versioning
425
555
 
426
- * Add in ability to keep-alive requests and reuse them within hydra.
427
- * Add support for automatic retry, exponential back-off, and queuing for later.
556
+ This project conforms to [semver](http://semver.org/).
428
557
 
429
- ## LICENSE
558
+ ## LICENSE
430
559
 
431
560
  (The MIT License)
432
561
 
433
- Copyright © 2009-2010 Paul Dix
562
+ Copyright © 2009-2010 [Paul Dix](http://www.pauldix.net/)
434
563
 
435
- Copyright © 2011 David Balatero
564
+ Copyright © 2011-2012 [David Balatero](https://github.com/dbalatero/)
436
565
 
437
- Copyright © 2012 [Hans Hasselberg](http://www.hans.io)
566
+ Copyright © 2012-2016 [Hans Hasselberg](http://github.com/i0rek/)
438
567
 
439
568
  Permission is hereby granted, free of charge, to any person obtaining a
440
569
  copy of this software and associated documentation files (the "Software"),