class Gem::Net::HTTP::Persistent

def self.detect_idle_timeout uri, max = 10

def self.detect_idle_timeout uri, max = 10
  uri = Gem::URI uri unless Gem::URI::Generic === uri
  uri += '/'
  req = Gem::Net::HTTP::Head.new uri.request_uri
  http = new 'net-http-persistent detect_idle_timeout'
  http.connection_for uri do |connection|
    sleep_time = 0
    http = connection.http
    loop do
      response = http.request req
      $stderr.puts "HEAD #{uri} => #{response.code}" if $DEBUG
      unless Gem::Net::HTTPOK === response then
        raise Error, "bad response code #{response.code} detecting idle timeout"
      end
      break if sleep_time >= max
      sleep_time += 1
      $stderr.puts "sleeping #{sleep_time}" if $DEBUG
      sleep sleep_time
    end
  end
rescue
  # ignore StandardErrors, we've probably found the idle timeout.
ensure
  return sleep_time unless $!
end