Class: Rack::BertRpc::Server

Inherits:
Object
  • Object
show all
Includes:
Encoding
Defined in:
lib/rack/bert_rpc/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Encoding

#error_response, #noreply_response, #read_rpc, #reply_response

Constructor Details

#initialize(logger = nil) ⇒ Server

Returns a new instance of Server.



12
13
14
15
# File 'lib/rack/bert_rpc/server.rb', line 12

def initialize(logger = nil)
  @logger = logger
  @mods = {}
end

Instance Attribute Details

#modsObject (readonly)

Returns the value of attribute mods.



10
11
12
# File 'lib/rack/bert_rpc/server.rb', line 10

def mods
  @mods
end

Instance Method Details

#dispatch(mod, fun, args) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/rack/bert_rpc/server.rb', line 58

def dispatch(mod, fun, args)
  if mods[mod].nil?
    raise(ServerError.new("No such module '#{mod}'"))
  end

  mods[mod].call_fun(fun, args)
end

#expose(sym, mod) ⇒ Object



17
18
19
# File 'lib/rack/bert_rpc/server.rb', line 17

def expose(sym, mod)
  mods[sym] = Mod.new(mod)
end

#handle(input) ⇒ Object



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
# File 'lib/rack/bert_rpc/server.rb', line 21

def handle(input)
  rpc = read_rpc(input)
  if rpc.nil?
    @logger.error("Invalid rpc request received: '#{input.inspect}'")
    return error_response(:server, "Invalid request: unrecognized")
  end

  if rpc.size == 4 && rpc[0] == :call
    begin
      @logger.debug("RPC Call: '#{rpc.inspect}'")
      resp = dispatch(*rpc[1..3])
      reply_response(resp)
    rescue ServerError => e
      @logger.error("Server error encountered on call: '#{e.inspect}'")
      error_response(:server, e)
    rescue Object => e
      @logger.info("error encountered on call: '#{e.inspect}'")
      error_response(:user, e)
    end
  elsif rpc.size == 4 && rpc[0] == :cast
    begin
      @logger.debug("RPC Call: '#{rpc.inspect}'")
      dispatch(*rpc[1..3])
      noreply_response
    rescue ServerError => e
      @logger.error("Server error encountered on cast: '#{e.inspect}'")
      error_response(:server, e)
    rescue Object => e
      @logger.debug("error encountered on cast: '#{e.inspect}'")
      noreply_response
    end
  else
    @logger.fatal("Unexpected error: '#{e.inspect}'")
    error_response(:server, "Invalid request: #{rpc.inspect}")
  end
end