Sha256: 4ccde9c9892b5b0ce2c167f3c5c7e1403d57853fa419e780b408829ba55bddb8

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

require 'rest-core/middleware'

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

class RestCore::EmHttpRequestFiber
  include RestCore::Middleware
  def call env
    f = Fiber.current

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

    client.callback{ respond(f, env, client) }
    client. errback{ respond(f, env, client) }

    if (response = Fiber.yield).kind_of?(::Exception)
      client.close
      raise response
    else
      response
    end
  end

  def respond f, env, client
    f.resume(process(env, client)) if f.alive?
  rescue FiberError
    # whenever timeout, client.close would be called,
    # and then errback would be called. in this case,
    # the fiber is already resumed by the timer
  end

  def process env, client
    result = env.merge(RESPONSE_BODY    => client.response,
                       RESPONSE_STATUS  => client.response_header.status,
                       RESPONSE_HEADERS => client.response_header)
    result[ASYNC].call(result) if result[ASYNC]
    result
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rest-core-1.0.3 lib/rest-core/app/em-http-request-fiber.rb