Class: Tair::Connection

Inherits:
Object
  • Object
show all
Includes:
Log
Defined in:
lib/tair/connection.rb

Constant Summary collapse

TAIR_CHUNK_SIZE =
1460

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Log

#colorize, included, #log_bytes, #log_time, #logger, #logger_colorize, #tair_bytes_log_file

Constructor Details

#initialize(host, port, opts = {}) ⇒ Connection

Returns a new instance of Connection.



14
15
16
17
18
# File 'lib/tair/connection.rb', line 14

def initialize(host, port, opts={})
  @host, @port = host, port.to_i
  @opts = opts || {}
  @timeout = opts[:timeout] || 10.0
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



11
12
13
# File 'lib/tair/connection.rb', line 11

def host
  @host
end

#portObject

Returns the value of attribute port.



11
12
13
# File 'lib/tair/connection.rb', line 11

def port
  @port
end

#timeoutObject

Returns the value of attribute timeout.



11
12
13
# File 'lib/tair/connection.rb', line 11

def timeout
  @timeout
end

Instance Method Details

#operate(req, &block) ⇒ Object



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
# File 'lib/tair/connection.rb', line 23

def operate(req, &block)

  socket = TCPSocket.new(host, port)
  socket.sendmsg req.encode.to_s

  log_time "transporting data", ::Logger::DEBUG do
    ready = IO.select([socket], nil, nil, timeout)

    if ready
      Tair::Protocol::ResponseHeader.read(socket.recv(12))
      socket.recv(4).tap do |len|
        byte_len = len.unpack('L>').first
        @response = socket.recv(byte_len)
      end
    else
      raise "Socket communications timed out after #{timeout} seconds"
    end
  end

  if block_given?
    return yield(@response)
  else
    return @response
  end

ensure
  socket.close unless socket.closed?
  @response.clear
  @response = nil
end