Class: Ruflet::Rails::Protocol::Endpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/ruflet/rails/protocol/endpoint.rb

Constant Summary collapse

WEBSOCKET_GUID =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

Instance Method Summary collapse

Constructor Details

#initialize(server:, path: "/ws") ⇒ Endpoint

Returns a new instance of Endpoint.



11
12
13
14
# File 'lib/ruflet/rails/protocol/endpoint.rb', line 11

def initialize(server:, path: "/ws")
  @server = server
  @path = path
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/ruflet/rails/protocol/endpoint.rb', line 16

def call(env)
  return not_found unless env["PATH_INFO"] == @path
  return bad_request("Expected WebSocket upgrade") unless websocket_upgrade_request?(env)

  hijack = env["rack.hijack"]
  return bad_request("Rack hijack is required by Ruflet::Rails::Protocol::Endpoint") unless hijack.respond_to?(:call)

  hijack.call
  io = env["rack.hijack_io"]
  return bad_request("Rack did not provide hijacked IO") unless io

  io.sync = true if io.respond_to?(:sync=)
  write_handshake(io, env["HTTP_SEC_WEBSOCKET_KEY"])

  captured_env = env.dup
  Thread.new(io, captured_env) do |socket, ws_env|
    Thread.current.report_on_exception = false if Thread.current.respond_to?(:report_on_exception=)
    Context.with_env(ws_env) do
      @server.handle_upgraded_socket(socket)
    end
  end

  [-1, {}, []]
rescue StandardError => e
  [500, { "content-type" => "text/plain" }, ["Ruflet Rails protocol error: #{e.message}"]]
end