Class: OpenC3::JsonDrbRack

Inherits:
Object show all
Defined in:
lib/openc3/io/json_drb_rack.rb

Overview

JsonDrbRack implements a rack application that can be served by a webserver to process OpenC3 json_drb requests via http.

Instance Method Summary collapse

Constructor Details

#initialize(drb) ⇒ JsonDrbRack



31
32
33
# File 'lib/openc3/io/json_drb_rack.rb', line 31

def initialize(drb)
  @drb = drb
end

Instance Method Details

#call(env) ⇒ Integer, ...

Handles a request.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/openc3/io/json_drb_rack.rb', line 40

def call(env)
  request = Rack::Request.new(env)

  if request.post?
    request_headers = Hash[*request.env.select { |k, v| k.start_with? 'HTTP_' }.sort.flatten]
    request_data = request.body.read
    status, content_type, body = handle_post(request_data, request_headers)
  else
    status       = 405
    content_type = "text/plain"
    body         = "Request not allowed"
  end

  return status, { 'Content-Type' => content_type }, [body]
end

#handle_post(request_data, request_headers) ⇒ Integer, String

Handles an http post.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/openc3/io/json_drb_rack.rb', line 62

def handle_post(request_data, request_headers)
  response_data, error_code = @drb.process_request(
    request_data: request_data,
    request_headers: request_headers,
    start_time: Time.now.sys
  )

  # Convert json error code into html status code
  # see http://www.jsonrpc.org/historical/json-rpc-over-http.html#errors
  if error_code
    case error_code
    when JsonRpcError::ErrorCode::PARSE_ERROR      then status = 500 # Internal server error
    when JsonRpcError::ErrorCode::INVALID_REQUEST  then status = 400 # Bad request
    when JsonRpcError::ErrorCode::METHOD_NOT_FOUND then status = 404 # Not found
    when JsonRpcError::ErrorCode::INVALID_PARAMS   then status = 500 # Internal server error
    when JsonRpcError::ErrorCode::INTERNAL_ERROR   then status = 500 # Internal server error
    else status = 500 # Internal server error
    end
  else
    status = 200 # OK
  end

  return status, "application/json-rpc", response_data
end