Class: Mata::Broadcaster

Inherits:
Object
  • Object
show all
Defined in:
lib/mata/broadcaster.rb

Instance Method Summary collapse

Constructor Details

#initializeBroadcaster

Returns a new instance of Broadcaster.



5
6
7
8
9
# File 'lib/mata/broadcaster.rb', line 5

def initialize
  @clients = []
  @clients_mutex = Mutex.new
  @cleanup_thread = cleanup_periodically
end

Instance Method Details

#broadcast_to_all(files) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mata/broadcaster.rb', line 51

def broadcast_to_all(files)
  clients_copy = @clients_mutex.synchronize { @clients.dup }
  return if clients_copy.empty?

  files.each do |file|
    event_data = {type: "reload"}
    message = "data: #{event_data.to_json}\n\n"

    clients_copy.each do |stream|
      stream << message
    rescue
      @clients_mutex.synchronize { @clients.delete(stream) }
    end
  end
end

#deliver_payloadObject



42
43
44
45
46
47
48
49
# File 'lib/mata/broadcaster.rb', line 42

def deliver_payload
  idiomorph_js = File.read(File.join(__dir__, "idiomorph.min.js"))
  client_js = File.read(File.join(__dir__, "client.js"))

  script = "#{idiomorph_js}\n\n#{client_js}"

  [200, {"content-type" => "application/javascript"}, [script]]
end

#establish_contact(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mata/broadcaster.rb', line 11

def establish_contact(env)
  if env["REQUEST_METHOD"] != "GET"
    return [405, {}, []]
  end

  headers = {
    "content-type" => "text/event-stream",
    "cache-control" => "no-cache",
    "connection" => "keep-alive",
    "access-control-allow-origin" => "*"
  }

  [200, headers, proc { |stream|
    @clients_mutex.synchronize do
      @clients << stream
    end

    begin
      stream << "data: {\"type\":\"connected\"}\n\n"

      Thread.new do
        loop { sleep 30 }
      rescue
        @clients_mutex.synchronize { @clients.delete(stream) }
      end
    rescue
      @clients_mutex.synchronize { @clients.delete(stream) }
    end
  }]
end

#stand_downObject



67
68
69
70
71
# File 'lib/mata/broadcaster.rb', line 67

def stand_down
  @cleanup_thread&.kill

  @clients_mutex.synchronize { @clients.clear }
end