Class: SseRailsEngine::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/sse_rails_engine/manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeManager

Returns a new instance of Manager.



5
6
7
8
9
# File 'lib/sse_rails_engine/manager.rb', line 5

def initialize
  @mutex = Mutex.new
  @connections = {}
  start_heartbeats
end

Instance Attribute Details

#connectionsObject (readonly)

Returns the value of attribute connections.



3
4
5
# File 'lib/sse_rails_engine/manager.rb', line 3

def connections
  @connections
end

Instance Method Details

#open_connection(io) ⇒ Object



33
34
35
36
37
38
# File 'lib/sse_rails_engine/manager.rb', line 33

def open_connection(io)
  Rails.logger.debug "New SSE Client connected: #{io}"
  @mutex.synchronize do
    @connections[io] = ActionController::Live::SSE.new(io)
  end
end

#register(response) ⇒ Object



11
12
13
14
15
16
# File 'lib/sse_rails_engine/manager.rb', line 11

def register(response)
  response.headers['Content-Type'] = 'text/event-stream'
  response.headers['Cache-Control'] = 'no-cache'
  # Perform partial hijack of socket (http://old.blog.phusion.nl/2013/01/23/the-new-rack-socket-hijacking-api/)
  response.headers['rack.hijack'] = ->(io) { SseRailsEngine.manager.open_connection(io) }
end

#send_event(name, data) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sse_rails_engine/manager.rb', line 18

def send_event(name, data)
  @mutex.synchronize do
    @connections.dup.each do |stream, sse|
      begin
        sse.write(data, event: name)
      rescue IOError, Errno::EPIPE, Errno::ETIMEDOUT
        Rails.logger.debug "SSE Client disconnected: #{stream}"
        close_connection(stream)
      rescue => ex
        Rails.logger.error "Failed to send event to SSE: #{stream} (#{name}, #{data} - #{ex.message} (#{ex.class}"
      end
    end
  end
end