Sha256: 0575a5829b4a90bd83f5a521747d48136257bea7d786a9e8a471e0b072c74021

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

require 'em-http-request'
require 'restclient/payload'

require 'rest-core/engine/future/future'
require 'rest-core/middleware'

class RestCore::EmHttpRequest
  include RestCore::Middleware
  def call env, &k
    future = Future.create(env, k, env[ASYNC])

    # eventmachine is not thread-safe, so...
    # https://github.com/igrigorik/em-http-request/issues/190#issuecomment-16995528
    ::EventMachine.schedule{ request(future, env) }

    env.merge(RESPONSE_BODY    => future.proxy_body,
              RESPONSE_STATUS  => future.proxy_status,
              RESPONSE_HEADERS => future.proxy_headers,
              FUTURE           => future)
  end

  def close client
    (client.instance_variable_get(:@callbacks)||[]).clear
    (client.instance_variable_get(:@errbacks )||[]).clear
    client.close
  end

  def request future, env
    payload = ::RestClient::Payload.generate(env[REQUEST_PAYLOAD])
    client  = ::EventMachine::HttpRequest.new(request_uri(env)).send(
                 env[REQUEST_METHOD],
                 :body => payload && payload.read,
                 :head => payload && payload.headers.
                                               merge(env[REQUEST_HEADERS]))

    client.callback{
      future.on_load(client.response,
                     client.response_header.status,
                     client.response_header)}

    client.errback{
      close(client)
      future.on_error(client.error)}

    env[TIMER].on_timeout{
      close(client)
      future.on_error(env[TIMER].error)
    } if env[TIMER]
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rest-core-2.0.4 lib/rest-core/engine/em-http-request.rb