Class: Dommy::DeferredResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/deferred_response.rb

Overview

The async-network handoff for fetch / XHR. A __fetch_handler__ (or XHR stub lookup) may return one of these instead of a response entry to answer a request ASYNCHRONOUSLY: the response is produced off the page thread (e.g. by a network worker doing blocking HTTP), and #complete(entry) is called from that thread when it is ready. Delivery is routed through the scheduler's external inbox, so the waiting fetch/XHR is fulfilled on the PAGE thread — single-threaded with the DOM/JS. The worker only ever passes a plain entry Hash (status / headers / body bytes); it never touches Dommy/JS state.

#complete is thread-safe and races cleanly with #on_complete (whichever of register / complete happens last triggers the single delivery).

Instance Method Summary collapse

Constructor Details

#initialize(scheduler) ⇒ DeferredResponse

Returns a new instance of DeferredResponse.



16
17
18
19
20
21
22
23
# File 'lib/dommy/deferred_response.rb', line 16

def initialize(scheduler)
  @scheduler = scheduler
  @mutex = Mutex.new
  @on_complete = nil
  @entry = nil
  @completed = false
  @flushed = false
end

Instance Method Details

#complete(entry) ⇒ Object

Called by the worker thread when the response (or nil) is ready. THREAD-SAFE.



34
35
36
37
38
39
40
# File 'lib/dommy/deferred_response.rb', line 34

def complete(entry)
  @mutex.synchronize do
    @entry = entry
    @completed = true
  end
  flush
end

#on_complete(&block) ⇒ Object

fetch/XHR registers its delivery callback here (invoked on the page thread with the response entry, or nil for a network failure -> a 404-style miss).



27
28
29
30
31
# File 'lib/dommy/deferred_response.rb', line 27

def on_complete(&block)
  @mutex.synchronize { @on_complete = block }
  flush
  self
end