Module: WebFetch::EventMachineHelpers
- Included in:
- Server
- Defined in:
- lib/web_fetch/concerns/event_machine_helpers.rb
Overview
EventMachine layer-specific helpers
Instance Method Summary collapse
- #apply_callbacks(request) ⇒ Object
- #request_async(target) ⇒ Object
- #save_response_time(request) ⇒ Object
- #tick_loop(request, response) ⇒ Object
- #wait_for_response(request, response) ⇒ Object
Instance Method Details
#apply_callbacks(request) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/web_fetch/concerns/event_machine_helpers.rb', line 19 def apply_callbacks(request) request[:deferred].callback do Logger.debug("HTTP fetch complete for uid: #{request[:uid]}") save_response_time(request) request[:succeeded] = true end request[:deferred].errback do Logger.debug("HTTP fetch failed for uid: #{request[:uid]}") save_response_time(request) request[:failed] = true end end |
#request_async(target) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/web_fetch/concerns/event_machine_helpers.rb', line 6 def request_async(target) request = target[:request] target[:start_time] = Time.now.utc 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 |
#save_response_time(request) ⇒ Object
53 54 55 |
# File 'lib/web_fetch/concerns/event_machine_helpers.rb', line 53 def save_response_time(request) request[:response_time] = Time.now.utc - request[:start_time] end |
#tick_loop(request, response) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/web_fetch/concerns/event_machine_helpers.rb', line 37 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
33 34 35 |
# File 'lib/web_fetch/concerns/event_machine_helpers.rb', line 33 def wait_for_response(request, response) tick_loop(request, response) end |