Class: Raft::Goliath::HttpJsonRpcResponder

Inherits:
Goliath::API
  • Object
show all
Defined in:
lib/raft/goliath.rb

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ HttpJsonRpcResponder

Returns a new instance of HttpJsonRpcResponder.



12
13
14
# File 'lib/raft/goliath.rb', line 12

def initialize(node)
  @node = node
end

Instance Method Details

#append_entries_response(params) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/raft/goliath.rb', line 39

def append_entries_response(params)
  Raft::AppendEntriesRequest.new(
      params['term'],
      params['leader_id'],
      params['prev_log_index'],
      params['prev_log_term'],
      params['entries'],
      params['commit_index'])
  response = @node.handle_append_entries(request)
  [200, {}, {'term' => response.term, 'success' => response.success}]
end

#command_response(params) ⇒ Object



51
52
53
54
55
# File 'lib/raft/goliath.rb', line 51

def command_response(params)
  Raft::CommandRequest.new(params['command'])
  response = @node.handle_command(request)
  [response.success ? 200 : 409, {}, {'success' => response.success}]
end

#error_response(code, message) ⇒ Object



65
66
67
# File 'lib/raft/goliath.rb', line 65

def error_response(code, message)
  [code, {}, {'error' => message}]
end

#handle_errorsObject



57
58
59
60
61
62
63
# File 'lib/raft/goliath.rb', line 57

def handle_errors
  yield
rescue StandardError => se
  error_response(422, se.message)
rescue Exception => e
  error_response(500, e.message)
end

#request_vote_response(params) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/raft/goliath.rb', line 29

def request_vote_response(params)
  request = Raft::RequestVoteRequest.new(
      params['term'],
      params['candidate_id'],
      params['last_log_index'],
      params['last_log_term'])
  response = @node.handle_request_vote(request)
  [200, {}, {'term' => response.term, 'vote_granted' => response.vote_granted}]
end

#response(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/raft/goliath.rb', line 16

def response(env)
  case env['REQUEST_PATH']
  when '/request_vote'
    handle_errors {request_vote_response(env['params'])}
  when '/append_entries'
    handle_errors {append_entries_response(env['params'])}
  when '/command'
    handle_errors {command_response(env['params'])}
  else
    error_response(404, 'not found')
  end
end