1

I know that current timeouts are currently not supported with Http.rb and Celluloid[1], but is there an interim workaround?

Here's the code I'd like to run:

  def fetch(url, options = {} )
    puts "Request -> #{url}"
    begin
      options = options.merge({ socket_class: Celluloid::IO::TCPSocket,
                                timeout_class: HTTP::Timeout::Global,
                                timeout_options: {
                                  connect_timeout: 1,
                                  read_timeout: 1,
                                  write_timeout: 1
                                  }
                              })
      HTTP.get(url, options)
    rescue HTTP::TimeoutError => e
      [do more stuff]
    end
  end

Its goal is to test a server as being live and healthy. I'd be open to alternatives (e.g. %x(ping <server>)) but these seem less efficient and actually able to get at what I'm looking for.

[1] https://github.com/httprb/http.rb#celluloidio-support

aronchick
  • 6,786
  • 9
  • 48
  • 75

1 Answers1

4

You can set timeout on future calls when you fetch for the request

Here is how to use timeout with Http.rb and Celluloid-io

require 'celluloid/io'
require 'http'
TIMEOUT = 10 # in sec
class HttpFetcher
  include Celluloid::IO

  def fetch(url)
    HTTP.get(url, socket_class: Celluloid::IO::TCPSocket)
  rescue Exception => e
   # error
  end
end

fetcher = HttpFetcher.new

urls = %w(http://www.ruby-lang.org/ http://www.rubygems.org/ http://celluloid.io/)

# Kick off a bunch of future calls to HttpFetcher to grab the URLs in parallel
futures = urls.map { |u| [u, fetcher.future.fetch(u)] }

# Consume the results as they come in
futures.each do |url, future|
  # Wait for HttpFetcher#fetch to complete for this request
  response = future.value(TIMEOUT)
  puts "*** Got #{url}: #{response.inspect}\n\n"
end
Sunda
  • 227
  • 3
  • 3
  • Your `begin / rescue` statement would be safer in `#fetch` otherwise you will still crash the actor, even if you don't crash the main thread... and you'll lose your futures. – digitalextremist Jun 13 '15 at 09:58
  • Dear future reader: http.rb has *removed celluloid support* in 1.0. The above example may or may not work any longer. – amenthes Aug 31 '16 at 15:56