Module: WebFetch::EventMachineHelpers

Included in:
Server
Defined in:
lib/web_fetch/event_machine_helpers.rb

Overview

EventMachine layer-specific helpers

Instance Method Summary collapse

Instance Method Details

#apply_callbacks(request) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/web_fetch/event_machine_helpers.rb', line 17

def apply_callbacks(request)
  request[:deferred].callback do
    Logger.debug("HTTP fetch complete for uid: #{request[:uid]}")
    request[:succeeded] = true
  end

  request[:deferred].errback do
    Logger.debug("HTTP fetch failed for uid: #{request[:uid]}")
    request[:failed] = true
  end
end

#request_async(request) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/web_fetch/event_machine_helpers.rb', line 6

def request_async(request)
  async_request = EM::HttpRequest.new(request[:url])
  method = request.fetch(:method, 'GET').downcase.to_sym
  async_request.public_send(
    method,
    head: request[:headers],
    query: request.fetch(:query, {}),
    body: request.fetch(:body, nil)
  )
end

#tick_loop(request, response) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/web_fetch/event_machine_helpers.rb', line 33

def tick_loop(request, response)
  # XXX There may be a much nicer way to wait for an async task to complete
  # before returning a response but I couldn't figure it out, so I used
  # EM.tick_loop which effectively does the same as a Twisted deferred
  # callback chain, just much more explicitly.
  EM.tick_loop do
    if request[:succeeded]
      succeed(request, response)
      :stop
    elsif request[:failed]
      fail_(request, response)
      :stop
    end
  end
end

#wait_for_response(request, response) ⇒ Object



29
30
31
# File 'lib/web_fetch/event_machine_helpers.rb', line 29

def wait_for_response(request, response)
  tick_loop(request, response)
end