tech-angels-typhoeus 0.1.36

Sign up to get free protection for your applications and to get access to all the features.
Files changed (44) hide show
  1. data/.gitignore +2 -0
  2. data/README.textile +312 -0
  3. data/Rakefile +39 -0
  4. data/VERSION +1 -0
  5. data/benchmarks/profile.rb +25 -0
  6. data/benchmarks/vs_nethttp.rb +35 -0
  7. data/examples/twitter.rb +21 -0
  8. data/ext/typhoeus/.gitignore +5 -0
  9. data/ext/typhoeus/Makefile +157 -0
  10. data/ext/typhoeus/extconf.rb +65 -0
  11. data/ext/typhoeus/native.c +11 -0
  12. data/ext/typhoeus/native.h +21 -0
  13. data/ext/typhoeus/typhoeus_easy.c +207 -0
  14. data/ext/typhoeus/typhoeus_easy.h +19 -0
  15. data/ext/typhoeus/typhoeus_multi.c +225 -0
  16. data/ext/typhoeus/typhoeus_multi.h +16 -0
  17. data/lib/typhoeus.rb +55 -0
  18. data/lib/typhoeus/.gitignore +1 -0
  19. data/lib/typhoeus/easy.rb +329 -0
  20. data/lib/typhoeus/filter.rb +28 -0
  21. data/lib/typhoeus/hydra.rb +235 -0
  22. data/lib/typhoeus/multi.rb +35 -0
  23. data/lib/typhoeus/remote.rb +306 -0
  24. data/lib/typhoeus/remote_method.rb +108 -0
  25. data/lib/typhoeus/remote_proxy_object.rb +48 -0
  26. data/lib/typhoeus/request.rb +159 -0
  27. data/lib/typhoeus/response.rb +49 -0
  28. data/lib/typhoeus/service.rb +20 -0
  29. data/profilers/valgrind.rb +24 -0
  30. data/spec/fixtures/result_set.xml +60 -0
  31. data/spec/servers/app.rb +73 -0
  32. data/spec/spec.opts +2 -0
  33. data/spec/spec_helper.rb +11 -0
  34. data/spec/typhoeus/easy_spec.rb +236 -0
  35. data/spec/typhoeus/filter_spec.rb +35 -0
  36. data/spec/typhoeus/hydra_spec.rb +311 -0
  37. data/spec/typhoeus/multi_spec.rb +74 -0
  38. data/spec/typhoeus/remote_method_spec.rb +141 -0
  39. data/spec/typhoeus/remote_proxy_object_spec.rb +65 -0
  40. data/spec/typhoeus/remote_spec.rb +695 -0
  41. data/spec/typhoeus/request_spec.rb +169 -0
  42. data/spec/typhoeus/response_spec.rb +63 -0
  43. data/typhoeus.gemspec +112 -0
  44. metadata +203 -0
@@ -0,0 +1,2 @@
1
+ .*.sw?
2
+ *.gem
@@ -0,0 +1,312 @@
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_response # the value returned from the on_complete block
107
+ second_request.handled_response # 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
+ SSL Certs can be provided to the Easy interface :
208
+
209
+ <pre>
210
+ e = Typhoeus::Easy.new
211
+ e.url = "https://example.com/action"
212
+ s.ssl_cacert = "ca_file.cer"
213
+ e.ssl_cert = "acert.crt"
214
+ e.ssl_key = "akey.key"
215
+ [...]
216
+ e.perform
217
+ </pre>
218
+
219
+ or directly to a Typhoeus::Request :
220
+
221
+ <pre>
222
+ e = Typhoeus::Request.get("https://example.com/action",
223
+ :ssl_cacert => "ca_file.cer",
224
+ :ssl_cert => "acert.crt",
225
+ :ssl_key => "akey.key",
226
+ [...]
227
+ end
228
+ </pre>
229
+
230
+ h2. NTLM authentication
231
+
232
+ 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.
233
+
234
+ <pre>
235
+ e = Typhoeus::Easy.new
236
+ e.auth = {
237
+ :username => 'username',
238
+ :password => 'password',
239
+ :method => Typhoeus::Easy::AUTH_TYPES[:CURLAUTH_NTLM]
240
+ }
241
+ e.url = "http://example.com/auth_ntlm"
242
+ e.method = :get
243
+ e.perform
244
+ </pre>
245
+
246
+ *Other authentication types*
247
+
248
+ The following authentication types are available:
249
+ * CURLAUTH_BASIC
250
+ * CURLAUTH_DIGEST
251
+ * CURLAUTH_GSSNEGOTIATE
252
+ * CURLAUTH_NTLM
253
+ * CURLAUTH_DIGEST_IE
254
+
255
+ *Query of available auth types*
256
+
257
+ 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
258
+ that you'll need to decode yourself, please refer to easy.rb source code to see the numeric values of different auth types.
259
+
260
+ h2. Verbose debug output
261
+
262
+ Sometime it's useful to see verbose output from curl. You may now enable it:
263
+
264
+ <pre>
265
+ e = Typhoeus::Easy.new
266
+ e.verbose = 1
267
+ </pre>
268
+
269
+ 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.
270
+
271
+ h2. Benchmarks
272
+
273
+ 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:
274
+
275
+ <pre>
276
+ net::http 0.030000 0.010000 0.040000 ( 10.054327)
277
+ typhoeus 0.020000 0.070000 0.090000 ( 0.508817)
278
+ </pre>
279
+
280
+ 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.
281
+
282
+ h2. Next Steps
283
+
284
+ * Add in ability to keep-alive requests and reuse them within hydra.
285
+ * Add support for automatic retry, exponential back-off, and queuing for later.
286
+
287
+ h2. LICENSE
288
+
289
+ (The MIT License)
290
+
291
+ Copyright (c) 2009:
292
+
293
+ "Paul Dix":http://pauldix.net
294
+
295
+ Permission is hereby granted, free of charge, to any person obtaining
296
+ a copy of this software and associated documentation files (the
297
+ 'Software'), to deal in the Software without restriction, including
298
+ without limitation the rights to use, copy, modify, merge, publish,
299
+ distribute, sublicense, and/or sell copies of the Software, and to
300
+ permit persons to whom the Software is furnished to do so, subject to
301
+ the following conditions:
302
+
303
+ The above copyright notice and this permission notice shall be
304
+ included in all copies or substantial portions of the Software.
305
+
306
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
307
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
308
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
309
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
310
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
311
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
312
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,39 @@
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
+ gemspec.add_dependency "rack"
15
+ gemspec.add_development_dependency "rspec"
16
+ gemspec.add_development_dependency "jeweler"
17
+ gemspec.add_development_dependency "diff-lcs"
18
+ gemspec.add_development_dependency "sinatra"
19
+ gemspec.add_development_dependency "json"
20
+ end
21
+
22
+ Jeweler::GemcutterTasks.new
23
+ rescue LoadError
24
+ puts "Jeweler not available. Install it with: gem install jeweler"
25
+ end
26
+
27
+ Spec::Rake::SpecTask.new do |t|
28
+ t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
29
+ t.spec_files = FileList['spec/**/*_spec.rb']
30
+ end
31
+
32
+ task :install do
33
+ rm_rf "*.gem"
34
+ puts `gem build typhoeus.gemspec`
35
+ puts `sudo gem install typhoeus-#{Typhoeus::VERSION}.gem`
36
+ end
37
+
38
+ desc "Run all the tests"
39
+ task :default => :spec
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.28
@@ -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
@@ -0,0 +1,5 @@
1
+ conftest.dSYM/*
2
+ conftest.dSYM
3
+ mkmf.log
4
+ *.o
5
+ native.bundle