Class: Rubee::WebSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/rubee/websocket/websocket.rb

Class Method Summary collapse

Class Method Details

.call(env, &controller_block) ⇒ Object



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
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
67
68
69
70
# File 'lib/rubee/websocket/websocket.rb', line 12

def call(env, &controller_block)
  unless env['rack.hijack']
    return [500, { 'Content-Type' => 'text/plain' }, ['Hijack not supported']]
  end

  env['rack.hijack'].call
  io = env['rack.hijack_io']

  handshake = ::WebSocket::Handshake::Server.new
  handshake.from_rack(env)
  unless handshake.valid?
    io.write("HTTP/1.1 400 Bad Request\r\n\r\n")
    io.close
    return [-1, {}, []]
  end

  io.write(handshake.to_s)
  incoming = ::WebSocket::Frame::Incoming::Server.new(version: handshake.version)

  outgoing = ->(data) do
    frame = ::WebSocket::Frame::Outgoing::Server.new(
      version: handshake.version,
      type: :text,
      data: data.to_json
    )
    io.write(frame.to_s)
  rescue IOError
    nil
  end

  # --- Listen to incoming data ---
  Thread.new do
    loop do
      data = io.readpartial(1024)
      incoming << data

      while (frame = incoming.next)
        case frame.type
        when :text
          out = controller_out(frame, outgoing, &controller_block)
          outgoing.call(**out)

        when :close
          # Client closed connection
          handle_close(frame, io, handshake)
          break
        end
      end
    end
  rescue EOFError, IOError
    begin
      handle_close(frame, io, handshake)
    rescue
      nil
    end
  end

  [101, handshake.headers, []]
end

.controller_out(frame, io, &block) ⇒ Object



90
91
92
93
94
95
96
97
98
99
# File 'lib/rubee/websocket/websocket.rb', line 90

def controller_out(frame, io, &block)
  payload_hash = payload(frame)
  action  = payload_hash["action"]
  channel = payload_hash["channel"]
  message = payload_hash["message"]
  options = payload_hash.select { |k, _| !["action", "channel", "message"].include?(k) }
  options.merge!(io:)

  block.call(channel:, message:, action:, options:)
end

.handle_close(frame, io, handshake) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rubee/websocket/websocket.rb', line 78

def handle_close(frame, io, handshake)
  payload_hash = payload(frame)
  channel = payload_hash["channel"]
  subcriber = payload_hash["subcriber"]
  ::Rubee::WebSocketConnections.instance.remove("#{channel}:#{subcriber}", io)
  io.write(::WebSocket::Frame::Outgoing::Server.new(
    version: handshake.version,
    type: :close
  ).to_s)
  io.close
end

.payload(frame) ⇒ Object



72
73
74
75
76
# File 'lib/rubee/websocket/websocket.rb', line 72

def payload(frame)
  JSON.parse(frame.data)
rescue
  {}
end