typhoeus 0.1.24 → 0.1.25

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,289 @@
1
+ h1. Typhoeus
2
+
3
+ "http://github.com/pauldix/typhoeus/tree/master":http://github.com/pauldix/typhoeus/tree/master
4
+
5
+ "the mailing list":http://groups.google.com/group/typhoeus
6
+
7
+ Thanks to my employer "kgbweb":http://kgbweb.com for allowing me to release this as open source. Btw, we're hiring and we work on cool stuff like this every day. Get a hold of me if you rock at rails/js/html/css or if you have experience in search, information retrieval, and machine learning.
8
+
9
+ I also wanted to thank Todd A. Fisher. I ripped a good chunk of the c libcurl-multi code from his update to Curb. Awesome stuff Todd!
10
+
11
+ h2. Summary
12
+
13
+ Like a modern code version of the mythical beast with 100 serpent heads, Typhoeus runs HTTP requests in parallel while cleanly encapsulating handling logic. To be a little more specific, it's a library for accessing web services in Ruby. It's specifically designed for building RESTful service oriented architectures in Ruby that need to be fast enough to process calls to multiple services within the client's HTTP request/response life cycle.
14
+
15
+ Some of the awesome features are parallel request execution, memoization of request responses (so you don't make the same request multiple times in a single group), built in support for caching responses to memcached (or whatever), and mocking capability baked in. It uses libcurl and libcurl-multi to work this speedy magic. I wrote the c bindings myself so it's yet another Ruby libcurl library, but with some extra awesomeness added in.
16
+
17
+ h2. Installation
18
+
19
+ Typhoeus requires you to have a current version of libcurl installed. I've tested this with 7.19.4 and higher.
20
+ <pre>
21
+ gem install typhoeus --source http://gemcutter.org
22
+ </pre>
23
+ If you're on Debian or Ubuntu and getting errors while trying to install, it could be because you don't have the latest version of libcurl installed. Do this to fix:
24
+ <pre>
25
+ sudo apt-get install libcurl4-gnutls-dev
26
+ </pre>
27
+ There's also something built in so that if you have a super old version of curl that you can't get rid of for some reason, you can install in a user directory and specify that during installation like so:
28
+ <pre>
29
+ gem install typhoeus --source http://gemcutter.org -- --with-curl=/usr/local/curl/7.19.7/
30
+ </pre>
31
+
32
+ Another problem could be if you are running Mac Ports and you have libcurl installed through there. You need to uninstall it for Typhoeus to work! The version in Mac Ports is old and doesn't play nice. You should "download curl":http://curl.haxx.se/download.html and build from source. Then you'll have to install the gem again.
33
+
34
+ If you're still having issues, please let me know on "the mailing list":http://groups.google.com/group/typhoeus.
35
+
36
+ There's one other thing you should know. The Easy object (which is just a libcurl thing) allows you to set timeout values in milliseconds. However, for this to work you need to build libcurl with c-ares support built in.
37
+
38
+ h2. Usage
39
+
40
+ *Deprecation Warning!*
41
+ The old version of Typhoeus used a module that you included in your class to get functionality. That interface has been deprecated. Here is the new interface.
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
+ <pre>
46
+ require 'rubygems'
47
+ require 'typhoeus'
48
+ require 'json'
49
+
50
+ # the request object
51
+ request = Typhoeus::Request.new("http://www.pauldix.net",
52
+ :body => "this is a request body",
53
+ :method => :post,
54
+ :headers => {:Accepts => "text/html"},
55
+ :timeout => 100, # milliseconds
56
+ :cache_timeout => 60, # seconds
57
+ :params => {:field1 => "a field"})
58
+ # we can see from this that the first argument is the url. the second is a set of options.
59
+ # the options are all optional. The default for :method is :get. Timeout is measured in milliseconds.
60
+ # cache_timeout is measured in seconds.
61
+
62
+ # the response object will be set after the request is run
63
+ response = request.response
64
+ response.code # http status code
65
+ response.time # time in seconds the request took
66
+ response.headers # the http headers
67
+ response.headers_hash # http headers put into a hash
68
+ response.body # the response body
69
+ </pre>
70
+
71
+ *Making Quick Requests*
72
+ The request object has some convenience methods for performing single HTTP requests. The arguments are the same as those you pass into the request constructor.
73
+
74
+ <pre>
75
+ response = Typhoeus::Request.get("http://www.pauldix.net")
76
+ response = Typhoeus::Request.head("http://www.pauldix.net")
77
+ response = Typhoeus::Request.put("http://localhost:3000/posts/1", :body => "whoo, a body")
78
+ response = Typhoeus::Request.post("http://localhost:3000/posts", :params => {:title => "test post", :content => "this is my test"})
79
+ response = Typhoeus::Request.delete("http://localhost:3000/posts/1")
80
+ </pre>
81
+
82
+ *Making Parallel Requests*
83
+
84
+ <pre>
85
+ # Generally, you should be running requests through hydra. Here is how that looks
86
+ hydra = Typhoeus::Hydra.new
87
+
88
+ first_request = Typhoeus::Request.new("http://localhost:3000/posts/1.json")
89
+ first_request.on_complete do |response|
90
+ post = JSON.parse(response.body)
91
+ third_request = Typhoeus::Request.new(post.links.first) # get the first url in the post
92
+ third_request.on_complete do |response|
93
+ # do something with that
94
+ end
95
+ hydra.queue third_request
96
+ return post
97
+ end
98
+ second_request = Typhoeus::Request.new("http://localhost:3000/users/1.json")
99
+ second_request.on_complete do |response|
100
+ JSON.parse(response.body)
101
+ end
102
+ hydra.queue first_request
103
+ hydra.queue second_request
104
+ hydra.run # this is a blocking call that returns once all requests are complete
105
+
106
+ first_request.handled_resposne # the value returned from the on_complete block
107
+ second_request.handled_resposne # the value returned from the on_complete block (parsed JSON)
108
+ </pre>
109
+
110
+ 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 up. 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.
111
+
112
+ *Specifying Max Concurrency*
113
+
114
+ 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.
115
+
116
+ <pre>
117
+ hydra = Typhoeus::Hydra.new(:max_concurrency => 20) # keep from killing some servers
118
+ </pre>
119
+
120
+ *Memoization*
121
+ Hydra memoizes requests within a single run call. You can also disable memoization.
122
+
123
+ <pre>
124
+ hydra = Typhoeus::Hydra.new
125
+ 2.times do
126
+ r = Typhoeus::Request.new("http://localhost/3000/users/1")
127
+ hydra.queue r
128
+ end
129
+ hydra.run # this will result in a single request being issued. However, the on_complete handlers of both will be called.
130
+ hydra.disable_memoization
131
+ 2.times do
132
+ r = Typhoeus::Request.new("http://localhost/3000/users/1")
133
+ hydra.queue r
134
+ end
135
+ hydra.run # this will result in a two requests.
136
+ </pre>
137
+
138
+ *Caching*
139
+ Hydra includes built in support for creating cache getters and setters. In the following example, if there is a cache hit, the cached object is passed to the on_complete handler of the request object.
140
+
141
+ <pre>
142
+ hydra = Typhoeus::Hydra.new
143
+ hydra.cache_setter do |request|
144
+ @cache.set(request.cache_key, request.response, request.cache_timeout)
145
+ end
146
+
147
+ hydra.cache_getter do |request|
148
+ @cache.get(request.cache_key) rescue nil
149
+ end
150
+ </pre>
151
+
152
+ *Stubbing*
153
+ Hydra allows you to stub out specific urls and patters to avoid hitting remote servers while testing.
154
+
155
+ <pre>
156
+ hydra = Typhoeus::Hydra.new
157
+ response = Response.new(:code => 200, :headers => "", :body => "{'name' : 'paul'}", :time => 0.3)
158
+ hydra.stub(:get, "http://localhost:3000/users/1").and_return(response)
159
+
160
+ request = Typhoeus::Request.new("http://localhost:3000/users/1")
161
+ request.on_complete do |response|
162
+ JSON.parse(response.body)
163
+ end
164
+ hydra.queue request
165
+ hydra.run
166
+ </pre>
167
+
168
+ The queued request will hit the stub. The on_complete handler will be called and will be passed the response object. You can also specify a regex to match urls.
169
+
170
+ <pre>
171
+ hydra.stub(:get, /http\:\/\/localhost\:3000\/users\/.*/).and_return(response)
172
+ # any requests for a user will be stubbed out with the pre built response.
173
+ </pre>
174
+
175
+ *The Singleton*
176
+ All of the quick requests are done using the singleton hydra object. If you want to enable caching or stubbing on the quick requests, set those options on the singleton.
177
+
178
+ <pre>
179
+ hydra = Typhoeus::Hydra.hydra
180
+ hydra.stub(:get, "http://localhost:3000/users")
181
+ </pre>
182
+
183
+ *Basic Authentication*
184
+
185
+ <pre>
186
+ require 'base64'
187
+ response = Typhoeus::Request.get("http://twitter.com/statuses/followers.json",
188
+ :headers => {"Authorization" => "Basic #{Base64.b64encode("#{username}:#{password}")}"})
189
+ </pre>
190
+
191
+ *SSL*
192
+ SSL comes built in to libcurl so it's in Typhoeus as well. If you pass in a url with "https" it should just work assuming that you have your "cert bundle":http://curl.haxx.se/docs/caextract.html in order and the server is verifiable. You must also have libcurl built with SSL support enabled. You can check that by doing this:
193
+
194
+ <pre>
195
+ Typhoeus::Easy.new.curl_version # output should include OpenSSL/...
196
+ </pre>
197
+
198
+ Now, even if you have libcurl built with OpenSSL you may still have a messed up cert bundle or if you're hitting a non-verifiable SSL server then you'll have to disable peer verification to make SSL work. Like this:
199
+
200
+ <pre>
201
+ Typhoeus::Request.get("https://mail.google.com/mail", :disable_ssl_peer_verification => true)
202
+ </pre>
203
+
204
+ *LibCurl*
205
+ Typhoeus also has a more raw libcurl interface. These are the Easy and Multi objects. If you're into accessing just the raw libcurl style, those are your best bet.
206
+
207
+ h2. NTLM authentication
208
+
209
+ Thanks for the authentication piece and this description go to Oleg Ivanov (morhekil). The major reason to start this fork was the need to perform NTLM authentication in Ruby. Now you can do it via Typhoeus::Easy interface using the following API.
210
+
211
+ <pre>
212
+ e = Typhoeus::Easy.new
213
+ e.auth = {
214
+ :username => 'username',
215
+ :password => 'password',
216
+ :method => Typhoeus::Easy::AUTH_TYPES[:CURLAUTH_NTLM]
217
+ }
218
+ e.url = "http://example.com/auth_ntlm"
219
+ e.method = :get
220
+ e.perform
221
+ </pre>
222
+
223
+ *Other authentication types*
224
+
225
+ The following authentication types are available:
226
+ * CURLAUTH_BASIC
227
+ * CURLAUTH_DIGEST
228
+ * CURLAUTH_GSSNEGOTIATE
229
+ * CURLAUTH_NTLM
230
+ * CURLAUTH_DIGEST_IE
231
+
232
+ *Query of available auth types*
233
+
234
+ After the initial request you can get the authentication types available on the server via Typhoues::Easy#auth_methods call. It will return a number
235
+ that you'll need to decode yourself, please refer to easy.rb source code to see the numeric values of different auth types.
236
+
237
+ h2. Verbose debug output
238
+
239
+ Sometime it's useful to see verbose output from curl. You may now enable it:
240
+
241
+ <pre>
242
+ e = Typhoeus::Easy.new
243
+ e.verbose = 1
244
+ </pre>
245
+
246
+ Please note that libcurl prints it's output to the console, so you'll need to run your scripts from the console to see the debug info.
247
+
248
+ h2. Benchmarks
249
+
250
+ I set up a benchmark to test how the parallel performance works vs Ruby's built in NET::HTTP. The setup was a local evented HTTP server that would take a request, sleep for 500 milliseconds and then issued a blank response. I set up the client to call this 20 times. Here are the results:
251
+
252
+ <pre>
253
+ net::http 0.030000 0.010000 0.040000 ( 10.054327)
254
+ typhoeus 0.020000 0.070000 0.090000 ( 0.508817)
255
+ </pre>
256
+
257
+ We can see from this that NET::HTTP performs as expected, taking 10 seconds to run 20 500ms requests. Typhoeus only takes 500ms (the time of the response that took the longest.) One other thing to note is that Typhoeus keeps a pool of libcurl Easy handles to use. For this benchmark I warmed the pool first. So if you test this out it may be a bit slower until the Easy handle pool has enough in it to run all the simultaneous requests. For some reason the easy handles can take quite some time to allocate.
258
+
259
+ h2. Next Steps
260
+
261
+ * Add in ability to keep-alive requests and reuse them within hydra.
262
+ * Add support for automatic retry, exponential back-off, and queuing for later.
263
+
264
+ h2. LICENSE
265
+
266
+ (The MIT License)
267
+
268
+ Copyright (c) 2009:
269
+
270
+ "Paul Dix":http://pauldix.net
271
+
272
+ Permission is hereby granted, free of charge, to any person obtaining
273
+ a copy of this software and associated documentation files (the
274
+ 'Software'), to deal in the Software without restriction, including
275
+ without limitation the rights to use, copy, modify, merge, publish,
276
+ distribute, sublicense, and/or sell copies of the Software, and to
277
+ permit persons to whom the Software is furnished to do so, subject to
278
+ the following conditions:
279
+
280
+ The above copyright notice and this permission notice shall be
281
+ included in all copies or substantial portions of the Software.
282
+
283
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
284
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
285
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
286
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
287
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
288
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
289
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,33 @@
1
+ require "spec"
2
+ require "spec/rake/spectask"
3
+ require 'lib/typhoeus.rb'
4
+
5
+ begin
6
+ require 'jeweler'
7
+ Jeweler::Tasks.new do |gemspec|
8
+ gemspec.name = "typhoeus"
9
+ gemspec.summary = "A library for interacting with web services (and building SOAs) at blinding speed."
10
+ gemspec.description = "Like a modern code version of the mythical beast with 100 serpent heads, Typhoeus runs HTTP requests in parallel while cleanly encapsulating handling logic."
11
+ gemspec.email = "paul@pauldix.net"
12
+ gemspec.homepage = "http://github.com/pauldix/typhoeus"
13
+ gemspec.authors = ["Paul Dix"]
14
+ end
15
+
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler not available. Install it with: gem install jeweler"
19
+ end
20
+
21
+ Spec::Rake::SpecTask.new do |t|
22
+ t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
23
+ t.spec_files = FileList['spec/**/*_spec.rb']
24
+ end
25
+
26
+ task :install do
27
+ rm_rf "*.gem"
28
+ puts `gem build typhoeus.gemspec`
29
+ puts `sudo gem install typhoeus-#{Typhoeus::VERSION}.gem`
30
+ end
31
+
32
+ desc "Run all the tests"
33
+ task :default => :spec
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.25
@@ -0,0 +1,25 @@
1
+ require File.dirname(__FILE__) + '/../lib/typhoeus.rb'
2
+ require 'rubygems'
3
+ require 'ruby-prof'
4
+
5
+ calls = 20
6
+ @klass = Class.new do
7
+ include Typhoeus
8
+ end
9
+
10
+ Typhoeus.init_easy_objects
11
+
12
+ RubyProf.start
13
+
14
+ responses = []
15
+ calls.times do |i|
16
+ responses << @klass.get("http://127.0.0.1:3000/#{i}")
17
+ end
18
+
19
+ responses.each {|r| }#raise unless r.response_body == "whatever"}
20
+
21
+ result = RubyProf.stop
22
+
23
+ # Print a flat profile to text
24
+ printer = RubyProf::FlatPrinter.new(result)
25
+ printer.print(STDOUT, 0)
@@ -0,0 +1,35 @@
1
+ require 'rubygems'
2
+ require File.dirname(__FILE__) + '/../lib/typhoeus.rb'
3
+ require 'open-uri'
4
+ require 'benchmark'
5
+ include Benchmark
6
+
7
+
8
+ calls = 20
9
+ @klass = Class.new do
10
+ include Typhoeus
11
+ end
12
+
13
+ Typhoeus.init_easy_object_pool
14
+
15
+ benchmark do |t|
16
+ t.report("net::http") do
17
+ responses = []
18
+
19
+ calls.times do |i|
20
+ responses << open("http://127.0.0.1:3000/#{i}").read
21
+ end
22
+
23
+ responses.each {|r| raise unless r == "whatever"}
24
+ end
25
+
26
+ t.report("typhoeus") do
27
+ responses = []
28
+
29
+ calls.times do |i|
30
+ responses << @klass.get("http://127.0.0.1:3000/#{i}")
31
+ end
32
+
33
+ responses.each {|r| raise unless r.body == "whatever"}
34
+ end
35
+ end
@@ -0,0 +1,21 @@
1
+ require File.dirname(__FILE__) + '/../lib/typhoeus.rb'
2
+ require 'rubygems'
3
+ require 'json'
4
+
5
+ class Twitter
6
+ include Typhoeus
7
+ remote_defaults :on_success => lambda {|response| JSON.parse(response.body)},
8
+ :on_failure => lambda {|response| puts "error code: #{response.code}"},
9
+ :base_uri => "http://search.twitter.com"
10
+
11
+ define_remote_method :search, :path => '/search.json'
12
+ define_remote_method :trends, :path => '/trends/:time_frame.json'
13
+ end
14
+
15
+ tweets = Twitter.search(:params => {:q => "railsconf"})
16
+ trends = Twitter.trends(:time_frame => :current)
17
+
18
+ # and then the calls don't actually happen until the first time you
19
+ # call a method on one of the objects returned from the remote_method
20
+
21
+ puts tweets.keys # it's a hash from parsed JSON
@@ -3,6 +3,7 @@ module Typhoeus
3
3
  attr_reader :response_body, :response_header, :method, :headers, :url
4
4
  attr_accessor :start_time
5
5
 
6
+ # These integer codes are available in curl/curl.h
6
7
  CURLINFO_STRING = 1048576
7
8
  OPTION_VALUES = {
8
9
  :CURLOPT_URL => 10002,
@@ -28,7 +29,8 @@ module Typhoeus
28
29
  INFO_VALUES = {
29
30
  :CURLINFO_RESPONSE_CODE => 2097154,
30
31
  :CURLINFO_TOTAL_TIME => 3145731,
31
- :CURLINFO_HTTPAUTH_AVAIL => 0x200000 + 23
32
+ :CURLINFO_HTTPAUTH_AVAIL => 0x200000 + 23,
33
+ :CURLINFO_EFFECTIVE_URL => 0x100000 + 1
32
34
  }
33
35
  AUTH_TYPES = {
34
36
  :CURLAUTH_BASIC => 1,
@@ -69,6 +71,10 @@ module Typhoeus
69
71
  get_info_double(INFO_VALUES[:CURLINFO_TOTAL_TIME])
70
72
  end
71
73
 
74
+ def effective_url
75
+ get_info_string(INFO_VALUES[:CURLINFO_EFFECTIVE_URL])
76
+ end
77
+
72
78
  def response_code
73
79
  get_info_long(INFO_VALUES[:CURLINFO_RESPONSE_CODE])
74
80
  end
@@ -95,6 +101,10 @@ module Typhoeus
95
101
  @timeout && total_time_taken > @timeout && response_code == 0
96
102
  end
97
103
 
104
+ def supports_zlib?
105
+ @supports_zlib ||= !!(version.match(/zlib/))
106
+ end
107
+
98
108
  def request_body=(request_body)
99
109
  @request_body = request_body
100
110
  if @method == :put