Class: Poliqarp::Connector

Inherits:
Object
  • Object
show all
Defined in:
lib/poliqarpr/connector.rb

Overview

Author

Aleksander Pohl ([email protected])

License

MIT License

This class hold the TCP connection to the server and is responsible for dispatching synchronous and asynchronous queries and answers.

Constant Summary collapse

ERRORS =

Error messages assigned to error codes (taken from poliqarpd implementation)

{
  1 =>   "Incorrect number of arguments",
  3 =>   "No session opened",
  4 =>   "Cannot create a session for a connection that",
  5 =>   "Not enough memory",
  6 =>   "Invalid session ID",
  7 =>   "Session with this ID is already bound",
  8 =>   "Session user ID does not match the argument",
  10 =>   "Session already has an open corpus",
  12 =>   "System error while opening the corpus",
  13 =>   "No corpus opened",
  14 =>   "Invalid job ID",
  15 =>   "A job is already in progress",
  16 =>   "Incorrect query",
  17 =>   "Invalid result range",
  18 =>   "Incorrect session option",
  19 =>   "Invalid session option value",
  20 =>   "Invalid sorting criteria"
}

Instance Method Summary collapse

Constructor Details

#initialize(debug) ⇒ Connector

Creates new connector



34
35
36
37
38
39
# File 'lib/poliqarpr/connector.rb', line 34

def initialize(debug)
  @message_queue = Queue.new
  @socket_mutex = Mutex.new
  @loop_mutex = Mutex.new
  @debug = debug
end

Instance Method Details

#open(host, port) ⇒ Object

Opens connection with poliqarp server which runs on given host and port.



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/poliqarpr/connector.rb', line 43

def open(host,port)
  @socket_mutex.synchronize {
    @socket = TCPSocket.new(host,port) if @socket.nil?
  }
  running = nil
  @loop_mutex.synchronize {
    running = @loop_running
  }
  main_loop unless running
  @loop_mutex.synchronize {
    @loop_running = true
  }
end

#read_messageObject

Retrives one message from the server. If the message indicates an error, new runtime error containing the error description is returned.



74
75
76
77
78
79
80
81
82
83
# File 'lib/poliqarpr/connector.rb', line 74

def read_message
  message = @message_queue.shift
  if message =~ /^ERR/
    code = message.match(/\d+/)[0].to_i
    raise JobInProgress.new() if code == 15
    raise RuntimeError.new("Poliqarp Error: "+ERRORS[code])
  else
    message
  end
end

#send(message, mode, &handler) ⇒ Object

Sends message to the poliqarp server. Returns the first synchronous answer of the server.

  • message the message to send

  • mode synchronous (+:sync:) or asynchronous (:async)

  • handler the handler of the asynchronous message



62
63
64
65
66
67
68
69
# File 'lib/poliqarpr/connector.rb', line 62

def send(message, mode, &handler)
  puts "send #{mode} #{message}" if @debug
  @socket.puts(message)
  if mode == :async
    @handler = handler
  end
  read_message
end