Giter Club home page Giter Club logo

typhoeus's Introduction

Typhoeus CI Experimental Code Climate Gem Version

Like a modern code version of the mythical beast with 100 serpent heads, Typhoeus runs HTTP requests in parallel while cleanly encapsulating handling logic.

Example

A single request:

Typhoeus.get("www.example.com", followlocation: true)

Parallel requests:

hydra = Typhoeus::Hydra.new
10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) }
hydra.run

Installation

Run:

bundle add typhoeus

Or install it yourself as:

gem install typhoeus

Project Tracking

Usage

Introduction

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.

request = Typhoeus::Request.new(
  "www.example.com",
  method: :post,
  body: "this is a request body",
  params: { field1: "a field" },
  headers: { Accept: "text/html" }
)

We can see from this that the first argument is the url. The second is a set of options. The options are all optional. The default for :method is :get.

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.

Sending requests through the proxy

Add a proxy url to the list of options:

options = {proxy: 'http://myproxy.org'}
req = Typhoeus::Request.new(url, options)

If your proxy requires authentication, add it with proxyuserpwd option key:

options = {proxy: 'http://proxyurl.com', proxyuserpwd: 'user:password'}
req = Typhoeus::Request.new(url, options)

Note that proxyuserpwd is a colon-separated username and password, in the vein of basic auth userpwd option.

You can run the query either on its own or through the hydra:

request.run
#=> <Typhoeus::Response ... >
hydra = Typhoeus::Hydra.hydra
hydra.queue(request)
hydra.run

The response object will be set after the request is run.

response = request.response
response.code
response.total_time
response.headers
response.body

Making Quick Requests

Typhoeus has some convenience methods for performing single HTTP requests. The arguments are the same as those you pass into the request constructor.

Typhoeus.get("www.example.com")
Typhoeus.head("www.example.com")
Typhoeus.put("www.example.com/posts/1", body: "whoo, a body")
Typhoeus.patch("www.example.com/posts/1", body: "a new body")
Typhoeus.post("www.example.com/posts", body: { title: "test post", content: "this is my test"})
Typhoeus.delete("www.example.com/posts/1")
Typhoeus.options("www.example.com")

Sending params in the body with PUT

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:

Typhoeus.put("www.example.com/posts/1",
        headers: {'Content-Type'=> "application/x-www-form-urlencoded"},
        body: {title:"test post updated title", content: "this is my updated content"}
    )

Handling HTTP errors

You can query the response object to figure out if you had a successful request or not. Here’s some example code that you might use to handle errors. The callbacks are executed right after the request is finished, make sure to define them before running the request.

request = Typhoeus::Request.new("www.example.com", followlocation: true)

request.on_complete do |response|
  if response.success?
    # hell yeah
  elsif response.timed_out?
    # aw hell no
    log("got a time out")
  elsif response.code == 0
    # Could not get an http response, something's wrong.
    log(response.return_message)
  else
    # Received a non-successful http response.
    log("HTTP request failed: " + response.code.to_s)
  end
end

request.run

This also works with serial (blocking) requests in the same fashion. Both serial and parallel requests return a Response object.

Handling file uploads

A File object can be passed as a param for a POST request to handle uploading files to the server. Typhoeus will upload the file as the original file name and use Mime::Types to set the content type.

Typhoeus.post(
  "http://localhost:3000/posts",
  body: {
    title: "test post",
    content: "this is my test",
    file: File.open("thesis.txt","r")
  }
)

Streaming the response body

Typhoeus can stream responses. When you're expecting a large response, set the on_body callback on a request. Typhoeus will yield to the callback with chunks of the response, as they're read. When you set an on_body callback, Typhoeus will not store the complete response.

downloaded_file = File.open 'huge.iso', 'wb'
request = Typhoeus::Request.new("www.example.com/huge.iso")
request.on_headers do |response|
  if response.code != 200
    raise "Request failed"
  end
end
request.on_body do |chunk|
  downloaded_file.write(chunk)
end
request.on_complete do |response|
  downloaded_file.close
  # Note that response.body is ""
end
request.run

If you need to interrupt the stream halfway, you can return the :abort symbol from the on_body block, example:

request.on_body do |chunk|
  buffer << chunk
  :abort if buffer.size > 1024 * 1024
end

This will properly stop the stream internally and avoid any memory leak which may happen if you interrupt with something like a return, throw or raise.

Making Parallel Requests

Generally, you should be running requests through hydra. Here is how that looks:

hydra = Typhoeus::Hydra.hydra

first_request = Typhoeus::Request.new("http://example.com/posts/1")
first_request.on_complete do |response|
  third_url = response.body
  third_request = Typhoeus::Request.new(third_url)
  hydra.queue third_request
end
second_request = Typhoeus::Request.new("http://example.com/posts/2")

hydra.queue first_request
hydra.queue second_request
hydra.run # this is a blocking call that returns once all requests are complete

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.

How to get an array of response bodies back after executing a queue:

hydra = Typhoeus::Hydra.new
requests = 10.times.map {
  request = Typhoeus::Request.new("www.example.com", followlocation: true)
  hydra.queue(request)
  request
}
hydra.run

responses = requests.map { |request|
  request.response.body
}

hydra.run is a blocking request. You can also use the on_complete callback to handle each request as it completes:

hydra = Typhoeus::Hydra.new
10.times do
  request = Typhoeus::Request.new("www.example.com", followlocation: true)
  request.on_complete do |response|
    #do_something_with response
  end
  hydra.queue(request)
end
hydra.run

Making Parallel Requests with Faraday + Typhoeus

require 'faraday'

conn = Faraday.new(:url => 'http://httppage.com') do |builder|
  builder.request  :url_encoded
  builder.response :logger
  builder.adapter  :typhoeus
end

conn.in_parallel do
  response1 = conn.get('/first')
  response2 = conn.get('/second')

  # these will return nil here since the
  # requests have not been completed
  response1.body
  response2.body
end

# after it has been completed the response information is fully available
# response1.status, etc
response1.body
response2.body

Specifying Max Concurrency

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.

Typhoeus::Hydra.new(max_concurrency: 20)

Memoization

Hydra memoizes requests within a single run call. You have to enable memoization. This will result in a single request being issued. However, the on_complete handlers of both will be called.

Typhoeus::Config.memoize = true

hydra = Typhoeus::Hydra.new(max_concurrency: 1)
2.times do
  hydra.queue Typhoeus::Request.new("www.example.com")
end
hydra.run

This will result in two requests.

Typhoeus::Config.memoize = false

hydra = Typhoeus::Hydra.new(max_concurrency: 1)
2.times do
  hydra.queue Typhoeus::Request.new("www.example.com")
end
hydra.run

Caching

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.

class Cache
  def initialize
    @memory = {}
  end

  def get(request)
    @memory[request]
  end

  def set(request, response)
    @memory[request] = response
  end
end

Typhoeus::Config.cache = Cache.new

Typhoeus.get("www.example.com").cached?
#=> false
Typhoeus.get("www.example.com").cached?
#=> true

For use with Dalli:

require "typhoeus/cache/dalli"

dalli = Dalli::Client.new(...)
Typhoeus::Config.cache = Typhoeus::Cache::Dalli.new(dalli)

For use with Rails:

require "typhoeus/cache/rails"

Typhoeus::Config.cache = Typhoeus::Cache::Rails.new

For use with Redis:

require "typhoeus/cache/redis"

redis = Redis.new(...)
Typhoeus::Config.cache = Typhoeus::Cache::Redis.new(redis)

All three of these adapters take an optional keyword argument default_ttl, which sets a default TTL on cached responses (in seconds), for requests which do not have a cache TTL set.

You may also selectively choose not to cache by setting cache to false on a request or to use a different adapter.

cache = Cache.new
Typhoeus.get("www.example.com", cache: cache)

Direct Stubbing

Hydra allows you to stub out specific urls and patterns to avoid hitting remote servers while testing.

response = Typhoeus::Response.new(code: 200, body: "{'name' : 'paul'}")
Typhoeus.stub('www.example.com').and_return(response)

Typhoeus.get("www.example.com") == response
#=> true

The queued request will hit the stub. You can also specify a regex to match urls.

response = Typhoeus::Response.new(code: 200, body: "{'name' : 'paul'}")
Typhoeus.stub(/example/).and_return(response)

Typhoeus.get("www.example.com") == response
#=> true

You may also specify an array for the stub to return sequentially.

Typhoeus.stub('www.example.com').and_return([response1, response2])

Typhoeus.get('www.example.com') == response1 #=> true
Typhoeus.get('www.example.com') == response2 #=> true

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.

RSpec.configure do |config|
  config.before :each do
    Typhoeus::Expectation.clear
  end
end

Timeouts

No exceptions are raised on HTTP timeouts. You can check whether a request timed out with the following method:

Typhoeus.get("www.example.com", timeout: 1).timed_out?

Timed out responses also have their success? method return false.

There are two different timeouts available: timeout and connecttimeout. timeout is the time limit for the entire request in seconds. connecttimeout is the time limit for just the connection phase, again in seconds.

There are two additional more fine grained options timeout_ms and connecttimeout_ms. These options offer millisecond precision but are not always available (for instance on linux if nosignal is not set to true).

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.

DNS timeouts of less than one second are not supported unless curl is compiled with an asynchronous resolver.

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.

Following Redirections

Use followlocation: true, eg:

Typhoeus.get("www.example.com", followlocation: true)

Basic Authentication

Typhoeus::Request.get("www.example.com", userpwd: "user:password")

Compression

Typhoeus.get("www.example.com", accept_encoding: "gzip")

The above has a different behavior than setting the header directly in the header hash, eg:

Typhoeus.get("www.example.com", headers: {"Accept-Encoding" => "gzip"})

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.

Cookies

Typhoeus::Request.get("www.example.com", cookiefile: "/path/to/file", cookiejar: "/path/to/file")

Here, cookiefile is a file to read cookies from, and cookiejar is a file to write received cookies to. If you just want cookies enabled, you need to pass the same filename for both options.

Other CURL options

Are available and documented here

SSL

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 in order and the server is verifiable. You must also have libcurl built with SSL support enabled. You can check that by doing this:

curl --version

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:

Typhoeus.get("https://www.example.com", ssl_verifypeer: false)

If you are getting "SSL: certificate subject name does not match target host name" from curl (ex:- you are trying to access to b.c.host.com when the certificate subject is *.host.com). You can disable host verification. Like this:

# host checking enabled
Typhoeus.get("https://www.example.com", ssl_verifyhost: 2)
# host checking disabled
Typhoeus.get("https://www.example.com", ssl_verifyhost: 0)

Verbose debug output

It’s sometimes useful to see verbose output from curl. You can enable it on a per-request basis:

Typhoeus.get("http://example.com", verbose: true)

or globally:

Typhoeus::Config.verbose = true

Just remember that libcurl prints it’s debug output to the console (to STDERR), so you’ll need to run your scripts from the console to see it.

Default User Agent Header

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:

Typhoeus::Config.user_agent = "custom user agent"

Running the specs

Running the specs should be as easy as:

bundle install
bundle exec rake

Semantic Versioning

This project conforms to semver.

LICENSE

(The MIT License)

Copyright © 2009-2010 Paul Dix

Copyright © 2011-2012 David Balatero

Copyright © 2012-2016 Hans Hasselberg

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

typhoeus's People

Contributors

balexis avatar craiglittle avatar danielcavanagh avatar dbalatero avatar dwaynemac avatar ezkl avatar fdeschenes avatar gravis avatar hanshasselberg avatar ifesdjeen avatar jarthod avatar jtarchie avatar jwagner avatar kjarrigan avatar marnen avatar morhekil avatar mschulkind avatar myronmarston avatar olleolleolle avatar pauldix avatar periclestheo avatar richievos avatar ryan2johnson9 avatar ryankinderman avatar sbryant avatar skalee avatar smulube avatar spraints avatar wilson avatar zapotek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typhoeus's Issues

Compiling under MinGW (WORKS, but not out of the box?)

It might just be my own confusion, but in order to get this running under Windows I had to jump through some hoops. Thought I'd jot down my steps here, maybe some things in the gem install or instructions can change.

Environment: Ruby 1.8.6 [i386-mingw32](w/Ruby MinGW Dev Kit installed)

Theoretically, I should be able to download the latest Windows libcurl (curl-7.19.7-devel-mingw32.zip), unzip it, copy the DLL bin/libcurl.dll into c:\ruby\bin, and install this gem no problem. However, this command does not work:

C:>gem install typhoeus -- --with-curl=c:\curl-7.19.7-devel-mingw32

The reason it doesn't work is because Typhoeus' extconf.rb has some logic I don't quite understand, which skips checking the --with-curl option if compiling under MinGW. It looks like it might be as-yet-unfinished cross-compilation logic?

To fix this problem, I cloned from github to c:\typhoeus and commented out all the "if MinGW" logic in extconf.rb. (That is, I forced it to use my --with-curl option.)

After editing extconf:
C:\typhoeus>gem build typhoeus.gemspec
C:\typhoeus>gem install typhoeus-0.1.18.gem -- --with-curl=c:\curl-7.19.7-devel-mingw32

Installed without a hitch and works fine.

So, this gem WILL compile and work just fine under Windows using MinGW, but as of version 0.1.18, you need to hack it a bit. Hopefully that can be streamlined in a future version.

Ruby 1.9 and fibers

Hi, was just wondering have you given any thought to using ruby fibers with this. Would that have any positive effect on performance?

Support for Ruby 1.8.5

If you have ruby 1.8.5, the RSTRING_PTR macro isn’t defined. You can workaround by putting these in ext/typhoeus/native.h (maybe someone should have #ifndef RSTRING_PTR around it):

#define RSTRING_PTR(s) (RSTRING(s)->ptr)

#define RSTRING_LEN(s) (RSTRING(s)->len)

FYI: Centos 5 comes with Ruby 1.8.5, which is why I'm using that version.

error: incompatible encoding regexp match

Hi,

I keep getting the following error from utlls.rb [line 5]:
incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)

This is the culprit:
/([^ a-zA-Z0-9_.-]+)/u

I'm not sure why it needs a fixed encoding regexp, when I remove the "u" flag it works without killing the whole process; however I have no idea how this change might affect everything else.

Any ideas?

Multi-thread problem

I get the following error if I run typhoeus in a multi threaded app

/usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.23/lib/typhoeus/multi.rb:20:in multi_perform': error on thread select (RuntimeError) from /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.23/lib/typhoeus/mu lti.rb:20:inperform'
from /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.23/lib/typhoeus/hy dra.rb:70:in run' from /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.23/lib/typhoeus/re quest.rb:100:inrun'
from /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.23/lib/typhoeus/re quest.rb:105:in `get'

from scripts/typheous.rb:19:in `block (2 levels) in '

Provide a mechanism to "stream" POST and PUT data

It would be nice if when an object that responded to :each was passed as the request_body to an easy object, it would be iterated over and sent to the server.

This would allow for streaming the request (useful for uploading large files, etc).

how could set timeout for some url

i tried use typhoeus for downloading some web pages,but there will some page have some issue,didn't return,so the typhoeus didn't return,i just find on_complete,how to record some error url then we can re-download them,

to be clear,is there some way for on_error to do sth for log

require 'typhoeus' doesn't load gem

I'm running on fedora 13 and cannot load typhoeus gem. Output track returns:
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'typhoeus'
TypeError: can't convert Array into String
from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/utils.rb:138:in union' from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/utils.rb:138 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require'
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require' from /usr/lib/ruby/gems/1.8/gems/typhoeus-0.1.31/lib/typhoeus.rb:3 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:ingem_original_require'
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from (irb):2

Does somebody help me?

Changelog

Hi,

it would be handy to have a changelog file the in the project, could you add one please ?

thanks

Typhoeus::Easy not invoking success/failure callbacks

It appears that Typhoeus::Easy isn't responding to callbacks, here is my usage

e = Typhoeus::Easy.new
e.auth = {
  :username => 'myusername',
  :password => 'mypassword',
  :method => Typhoeus::Easy::AUTH_TYPES[:CURLAUTH_DIGEST]
}
e.headers = { :Accept => 'application/json' }
e.verbose = 0
e.url = "http://my.url"
e.method = :get
e.on_success {
  puts 'oh yes!'
}
e.on_failure {
  puts 'oh no!'
}
e.perform

I've been able to work around this for now by adding conditions based on the response code, but was hoping to use the callbacks if possible. Am I missing something?

Slow SSL connections

Using Typhoeus to access https://graph.facebook.com takes about 9 seconds for the first connect, and instantaneous thereafter. Using Net::HTTP is instantaneous every time.

I was playing with the curl binary and Facebook has a very slow handshaking process for SSL. Is there some way to fix this within Typhoeus to make it skip handshaking?

Doesn't handle threads

You really need to use rb_thread_select instead of select in typhoeus_multi.c. Look at a recent version of curb, and their implementation in curb_multi.c.

head request is slow

response times when specifying a HEAD method on request is very slow, sometimes over a minute.
all other methods using the same connection the response times are normal.

fwiw, the head request completes successfully.

Documentation Request: Hydra#stub

I'm adding this here as a marker. I don't mind submitting a doc patch for this, but I have a imminent release coming up in the next couple weeks.

In trying to use Hydra#stub for testing, I found some undocumented behaviors:

(1) The stubs are matched to requests. It's not explicitly written in the README, but it will only stub requests that matches what you declare. (There is no, "stub all" feature that raises an exception if you do not declare a matching stub).

(2) Stubs do not clear after you use them. When stubbing the singleton, Typhoeus::Hydra.hydra you will need a call to #clear_stubs

(3) Stub matching is in Typhoeus::HydraMock#matches?(request) ... it isn't clear whether this is a "public" or "private" API. For my purpose, it was easier to monkeypatch that for a brute-force stubbing.

Feature: Implement a "max filesize" option for requests

As mentioned here: http://groups.google.com/group/typhoeus/browse_frm/thread/856471c70d745011#

Copypasta:
There would be a method to do it with a modification to the library.
Basically, the easy.c would have to have a callback for chunks of
files. It's a non-trivial modification to make requiring changes to
the C section of the library and some additions to the Ruby part.
Someone else had asked about this a while ago for a slightly different
reason: to stream the download to a streaming parser like Yajl for
JSON or Nokogiri::Reader for XML. It's something I'd like to support
at some point.

Typhoeus::Easy responses include the Status-Line in the header_hash

The Easy response includes the Status-Line section of the response in the Headers section, which will include an invalid header in the headers_hash, which looks something like: {"HTTP/1.1 200 OK"=>nil}. Here is a reproducible example: http://gist.github.com/586968

I believe this is due to the curl bindings here: http://github.com/pauldix/typhoeus/blob/master/ext/typhoeus/typhoeus_easy.c#L108

Curl includes the Status-Line in the header data, while Typhoeus treats that as only the header fields.

Windows Support

can you cross compile this with rake-compiler or similar so that we can have native windows versions?

Params hash does not accept symboled keys

The params hash cannot have symbol keys, as they get sorted, and #sort doesn't know what to do with symbols.

Since it's fairly idiomatic in Ruby to use :symbols, I think this should be supported. Will work on this asap.

License?

What license are you using? Maybe you need to add a file? MIT? GPL?

multipart_form_post

Support for multipart_form_post would be cool. I'd love to replace all my curb usage with Typhoeus.

Multi is eating headers

Refer to this gist : http://gist.github.com/425250

the first request will set the header :

[...]

POST / HTTP/1.1
Host: www.google.com
Accept: /
TEST: TEST
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
[...]

In the second request, queued in multi, headers are not set :

[...]

POST / HTTP/1.1
Host: www.google.com
Accept: /
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
[...]

Is it possible to send post data in a single request?

I'm using a rails webservice that reads the the raw post data on the server side using request.raw_post.

I am able to send the data using curl like this:

cat sample.xml | curl -X POST -d @- -u (username):(apikey) https://foo.bar/api/profiles/batch_create -H 'Content-type: text/xml'
 

And it works. I can't seem to find a way to get it to work using this library.

e = Typhoeus::Easy.net
e.verbose = 1
e.headers = AuthorizationHeader.merge({:content_type => 'text/xml'})
e.url = Url
e.method = :post
e.request_body = File.read(file)
e.post_data = File.read(file)
e.perform

Doesn't work. The rails server gets nothing back from 'request.raw_post'

The verbose output looks like

POST /api/profiles/batch_create HTTP/1.1
Host: foo.bar
Accept: */*
Authorization: Basic blahblah

content_type: text/xml
Content-Length: 6471
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Date: Tue, 23 Mar 2010 00:55:18 GMT
< Server: Apache/2.2.12 (Ubuntu)
< X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.11
< X-Runtime: 127
< Cache-Control: no-cache
< Content-Length: 268
< Status: 400
< Connection: close
< Content-Type: application/xml; charset=utf-8
<

It looks like curl is using th 100-continue header, but I don't want that. I want to send it all as a single request. Any way to do that?

Typhoeus does not work on Snow Leopard

The first line of the extconf.rb hard codes Typhoeus to either PPC or 32-bit x86. SL is 64-bit and so the gem install works (because you can compile 32-bit stuff) but the gem fails to load with 64-bit native Ruby.

equivalent to curb's last_effective_url

Typhoeus basically rules and I'd love to use for everything in my app, but i really need to be able to know what the last url the request made after all the redirects it goes through (mainly url shorteners), so I've been using curb in parts. I tried using the typhoeus response location headers but that proved to be problematic. Having it built into the response would be awesome.

Support custom methods

We have a custom PURGE method for sending cache purge requests to Varnish. Typheous converts everything non-standard to a DELETE in Typheous::Easy#method=. Change the line to:

set_option(OPTION_VALUES[:CURLOPT_CUSTOMREQUEST], method.to_s.upcase)

and our purges start working again.

broken response in v0.1.25 (fine in v0.1.24)

environment: Ubuntu 10.04, Ruby 1.8.7 p249

running:
Typhoeus::Request.get("http://www.pauldix.net").body

shows:
"\037\213\b\000\000\000\000\000\000\377\325}\331r\333H\266\340\263\025Q\377\220\305\212\366\322W\340*R\233%\267\274T[u\275\265\245n\267\343\306\rE\022H\222\260@$\214\004D\261\356\364D\377\306D\314\274N\304|\307\374I\177\311\234%\023HR\224%\313\222\253\306]-\211D.'\317~N\236L<\376\361\371\333g\307\037\337\275\020\223b\232\210w\177...

Request: Allow a string for :params

It would be convenient to be able to use a string for :params, as I'm using Typhoeus with dumps of http traffic. The current implementation makes me tear the string apart and potentially futz with the encoding, when really what I would just like to do is :params=>"foo=longparam&bar=thatyoucanjustuse". Thoughts?

Headers are being mangled

In 0.1.28, headers are duped/mangled. Here's what I'm seeing in a Hoptoad notification (header on first line, what it's being set to on the second):

HTTP_USER_AGENT
Typhoeus - http://github.com/pauldix/typhoeus/tree/master, Typhoeus - http://github.com/pauldix/typhoeus/tree/master


HTTP_X_API_TOKEN
cc1892665e521c6692248cffbd7edd17, cc1892665e521c6692248cffbd7edd17

This is with something like:

Typhoeus::Request.get("https://url",
  :headers => {
    "X-API-TOKEN" => "3c0b3b94e163759821a6b4752cc23c5c"
  }
)

Seems something is adding them to an array and joining on ", " when the request is built. The same request works fine with 0.1.27 and with curl on the command line.

Memory leak ?

Hi,

apparently, using blocks and AR is not a good idea with hydra.
I was trying to do something like :

@users.each do |user|
  r = Typhoeus::Request.new("http://localhost", :method => :post, :params => {:user_id => user.id, :user_name, => user.name})
  r.on_complete do |response|
    user.push_to_webservice if response.success? # change state, with something like state machine
  end
  hydra.queue r
end
hydra.run

This will lead to a memory leak, and sometimes, params will get overridden and completely broken.
I'm not sure we can correct this, I mostly create this issue for logging purpose

occasional segfaults

We are experiencing segfaults on a linux server. These are averaging maybe 36 hours apart on a lightly loaded system, just guessing but it looks like once in about 1000 requests through typhoeus.

We can try to gather information for you, but we can't seem to force the issue (we'll try a little harder)

The reality is that we're under a time constraint here. If we can't get this addressed quickly we'll have to drop something else into the critical piece for the time being. Nevertheless we'll do what we can help in any way you can think of. There's a chunk of code that's using typhoeus that is not critical (it doesn't matter if it fails every now and again since we can restart it and no user will ever know the difference)

Here's the first part of the trace information:

/usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.13/lib/typhoeus/multi.rb:20: [BUG] Segmentation fault
ruby 1.9.1p243 (2009-07-16 revision 24175) [x86_64-linux]

-- control frame ----------
c:0090 p:---- s:0441 b:0441 l:000440 d:000440 CFUNC :multi_perform
c:0089 p:0019 s:0438 b:0438 l:000437 d:000437 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.13/lib/typhoeus/multi.rb:20
c:0088 p:0023 s:0435 b:0435 l:000434 d:000434 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.13/lib/typhoeus/hydra.rb:65
c:0087 p:0066 s:0432 b:0432 l:000431 d:000431 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.13/lib/typhoeus/request.rb:97
c:0086 p:0031 s:0426 b:0426 l:000425 d:000425 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/typhoeus-0.1.13/lib/typhoeus/request.rb:106

query params are ignored for post

Hey Paul,

Great library! Definitely the best http library around for Ruby.

I'm having a problem though. You specifically ignore the :params option if the method is :post. This breaks our code that used to work fine with Net::HTTP. I'm not sure if there is something in the HTTP spec that says query params are disallowed for POST, but it seems better to just add them to the url for all methods, as most HTTP servers I'm familiar with make them available for all methods.

What do you think?

Cheers,
Justin

README = WRONGME ;)

The docs indicate that Typhoeus::Request.new(...).response will work, and it does not. (Did it used to?) Naturally, the way it works now is response = T::R::run(...), but the docs should reflect that.

https issues on heroku

For some reason, the first https request on Heroku will succeed, but later requests fail with code = 0. Here's how I'm testing:

gist: http://gist.github.com/278601

This is especially rough for other gems built on top of typhoeus, like raws (a Ruby AWS client) which accesses AWS via a https RESTful interface.

hydra.run() sometimes does not return

I'm having problems with the run() method sometimes never returning when a large amout of requests are queued (more than 2000).

At first I caught a redirection loop coming from one of the urls, so I specified the :max_redirects option of my Typhoeus::Request objects, but the problem came back after a while.

Is there any other similar pitfalls I should look for that could cause this behavior? Note that the urls I use come from various sources I do not control.

I can gdb the thing when it happens, and the code is stuck in select(). I'll definitly get a backtrace tomorrow when the problem re-occurs. Anything else I should get to produce a thorough bug report?

How to get the "true" response time

Is there a way to know the true response time instead of the incremented total time?
Setting max concurrency to 1 solves this but it defeats the point of asynchronous requests.

Any ideas?

Warning feed.rb:232

pauldix-feedzirra-0.0.12/lib/feedzirra/feed.rb:232: warning: multiple values for a block parameter (2 for 1)

expects 2 values

Immediate Response Code 0 after hours of successful operation

After a few hours of successful requests being made by our application Typhoeus will repond with code 0, the response is instant to any subsequent requests yet use of curl, Net::HTTP and wget proves the destination reachable while the app fails this way. The behaviour is like a false timeout and persists until the application is restarted. Attempting to write a test to prove this but due to the sporadic nature it's not simple to recreate.
Using libcurl 7.19.7 and Ruby 1.9.1

Easy and cert

Hi,

Could you explain how to specify options like CURLOPT_SSLCERT in a Easy request ?
I really don't how you can pass custom libcurl options.

Thanks !

extconf.rb

I am on mac and I am using curl (7.21.2) installed via brew. When I install typhoeus, it's compiled using an older version (7.19.7 - maybe it's default for snow).
When I install curb, it uses the newer version correctly, so I grab the extconf from there, put on my typhoeus fork, compile and now I have it installed using 7.21.2

https://github.com/rafaelss/typhoeus/blob/master/ext/typhoeus/extconf.rb (using last line from original extconf.rb)

My think is: curb's extconf uses curl-config to determine what version and such should be used and would be good typhoeus use the same approach.

What you think?

Feature request: expose CURLOPT_CONNECTTIMEOUT

If I understand correctly, Typhoeus request TIMEOUT parameter is for the entire request, starting from the initial connection up to the end of the request.

I see that Curl has two timeout values, CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT, if someone has time to expose CONNECT_TIMEOUT it would be great, as my problem is that when setting the Typhoeus TIMEOUT param too low, large files get truncated, and when setting it too high, too much time is spent on unreachable/problematic hosts.

I might even dig in the code and provide a diff later this week, but being totally new to gems and ruby in general it might take a while to get it right.

force encoding to match response header in Ruby 1.9

It seems that Typhoeus disregards the HTML encoding type and returns a string in the default encoding, which may be invalid. In my code, I work around it by force encoding downloaded strings, but it seems like reading the headers is the right solution.

Support rails caching

Typheous.cache expects a get/set caching API as provided by MemCache. Support Typhoeus.cache = Rails.cache to make Rails caching very simple. Better yet, autodetect Rails.cache (aka RAILS_CACHE) and use it by default. Rails's cache stores use read/write instead of get/set.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.