Class: Paraspec::MsgpackServer

Inherits:
Object
  • Object
show all
Includes:
MsgpackHelpers
Defined in:
lib/paraspec/msgpack_server.rb

Instance Method Summary collapse

Methods included from MsgpackHelpers

#packer, #unpacker

Constructor Details

#initialize(master) ⇒ MsgpackServer

Returns a new instance of MsgpackServer.



9
10
11
12
# File 'lib/paraspec/msgpack_server.rb', line 9

def initialize(master)
  @master = master
  @lock = Mutex.new
end

Instance Method Details

#process_request(s, obj) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/paraspec/msgpack_server.rb', line 42

def process_request(s, obj)
  result = nil
  time = Benchmark.realtime do
    action = obj['action'].gsub('-', '_')
    payload = obj['payload']
    if payload
      payload = IpcHash.new.merge(payload)
      args = [payload]
    else
      args = []
    end

    Paraspec.logger.debug_ipc("SrvReq:#{obj['id']} #{obj}")
    result = @master.send(action, *args)

    pk = packer(s)
    resp = {result: result}
    Paraspec.logger.debug_ipc("SrvRes:#{obj['id']} #{resp}")
    if payload && payload['_noret']
      # Requester does not want a response.
      # We return a hash here because deserializer expects a hash.
      # Always returning `resp` is problematic because it can
      # be non-serializable.
      pk.write({})
    else
      pk.write(resp)
    end
    pk.flush
    s.flush
  end
  Paraspec.logger.debug_perf("SrvReq:#{obj['id']} #{obj['action']}: #{result} #{'%.3f msec' % (time*1000)}")
end

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/paraspec/msgpack_server.rb', line 14

def run
  @socket = ::TCPServer.new('127.0.0.1', Paraspec::Ipc.master_app_port)
  begin
    while true
      s = @socket.accept_nonblock
      run_processing_thread(s)
    end
  rescue Errno::EAGAIN
    unless @master.stop?
      sleep 0.2
      retry
    end
  end
end

#run_processing_thread(s) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/paraspec/msgpack_server.rb', line 29

def run_processing_thread(s)
  Thread.new do
    u = unpacker(s)
    u.each do |obj|
      # Apparently this block may be run concurrently, which we are not
      # equipped for.
      @lock.synchronize do
        process_request(s, obj)
      end
    end
  end
end