Class: Async::Background::Web::Stream

Inherits:
Object
  • Object
show all
Includes:
Clock
Defined in:
lib/async/background/web/stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(hub, heartbeat_seconds:, retry_ms:, poll_seconds:, logger: nil) ⇒ Stream

Returns a new instance of Stream.



11
12
13
14
15
16
17
# File 'lib/async/background/web/stream.rb', line 11

def initialize(hub, heartbeat_seconds:, retry_ms:, poll_seconds:, logger: nil)
  @hub = hub
  @heartbeat_seconds = heartbeat_seconds
  @retry_ms = retry_ms
  @poll_seconds = poll_seconds
  @logger = logger
end

Instance Method Details

#eachObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/async/background/web/stream.rb', line 19

def each
  yield "retry: #{@retry_ms}\n\n"

  version, frame = initial_state
  if version.nil?
    yield EventHub::UNAVAILABLE_FRAME
    return
  end

  yield frame
  last_yield = monotonic_now
  unavailable_announced = false

  loop do
    sleep_for_poll

    begin
      new_version = @hub.current_version

      if new_version != version
        version = new_version
        yield @hub.frame_for(version)
        last_yield = monotonic_now
      elsif (monotonic_now - last_yield) >= @heartbeat_seconds
        yield EventHub::HEARTBEAT_FRAME
        last_yield = monotonic_now
      end

      unavailable_announced = false
    rescue ClosedError
      break
    rescue UnavailableError
      unless unavailable_announced
        yield EventHub::UNAVAILABLE_FRAME
        unavailable_announced = true
        last_yield = monotonic_now
      end
    end
  end
rescue Errno::EPIPE, Errno::ECONNRESET, IOError
  nil
rescue StandardError => error
  @logger&.error(
    "[async-background-web] SSE stream terminated: " \
    "#{error.class}: #{error.message}"
  )
  nil
end