Class: AnyCable::HTTRPC::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/anycable/httrpc/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(token: AnyCable.config.http_rpc_secret) ⇒ Server

Returns a new instance of Server.



6
7
8
9
10
11
12
13
# File 'lib/anycable/httrpc/server.rb', line 6

def initialize(token: AnyCable.config.http_rpc_secret)
  if !token
    token = AnyCable.config.http_rpc_secret!
    AnyCable.logger.info("AnyCable HTTP RPC created with authorization key inferred from the application secret")
  end

  @token = token
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/anycable/httrpc/server.rb', line 15

def call(env)
  if env["REQUEST_METHOD"] != "POST"
    return [404, {}, ["Not found"]]
  end

  if token && env["HTTP_AUTHORIZATION"] != "Bearer #{token}"
    return [401, {}, ["Unauthorized"]]
  end

  rpc_command = env["PATH_INFO"].sub(%r{^/}, "").to_sym

  # check if command is supported and return 404 if not
  return [404, {}, ["Not found"]] unless AnyCable.rpc_handler.supported?(rpc_command)

  # read request body and it's empty, return 422
  # rack.input is optional starting in Rack 3.1
  request_body = env["rack.input"]&.read
  return [422, {}, ["Empty request body"]] if request_body.nil? || request_body.empty?

  payload =
    case rpc_command
    when :connect then AnyCable::ConnectionRequest.decode_json(request_body)
    when :disconnect then AnyCable::DisconnectRequest.decode_json(request_body)
    when :command then AnyCable::CommandMessage.decode_json(request_body)
    end

  return [422, {}, ["Invalid request body"]] if payload.nil?

  response = AnyCable.rpc_handler.handle(rpc_command, payload, build_meta(env))

  [200, {}, [response.to_json({format_enums_as_integers: true, preserve_proto_fieldnames: true})]]
rescue JSON::ParserError, ArgumentError => e
  [422, {}, ["Invalid request body: #{e.message}"]]
end