class Fastbeans::Connection

Constants

MAX_RETRIES

Attributes

socket[R]

Public Class Methods

new(host, port) click to toggle source
# File lib/fastbeans/connection.rb, line 10
def initialize(host, port)
  Fastbeans.debug("Connecting to #{host}:#{port}")
  @host, @port = host, port
  begin
    @socket = connect!(@host, @port)
  rescue => e 
    Fastbeans.error(e)
    raise RemoteConnectionDead, e.message
  end
end

Public Instance Methods

call(data, opts) click to toggle source
# File lib/fastbeans/connection.rb, line 43
def call(data, opts)
  retries = 0
  begin
    call_without_retries(data, opts)
  rescue Fastbeans::RemoteConnectionFailed, Fastbeans::ResponseReadTimeout => e
    Fastbeans.debug(e)
    if retries < MAX_RETRIES
      Fastbeans.debug("Retrying (#{retries} out of #{MAX_RETRIES} retries)")
      retries += 1
      begin
        reconnect!
      rescue => e
        raise RemoteConnectionDead, e.message
      end
      retry
    else
      raise RemoteConnectionDead, "#{e.message} (#{retries} retries)"
    end
  end
end
call_without_retries(data, opts) click to toggle source
# File lib/fastbeans/connection.rb, line 64
def call_without_retries(data, opts)
  perform(data, opts)

rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ECONNRESET, MessagePack::MalformedFormatError => e
  disconnect!
  ne = RemoteConnectionFailed.new(e.message)
  ne.orig_exc = e
  raise ne

rescue Exception
  disconnect!
  raise
end
connect!(host, port) click to toggle source
# File lib/fastbeans/connection.rb, line 21
def connect!(host, port)
  @socket = TCPSocket.new(host, port)
  @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
  @socket
end
disconnect!() click to toggle source
# File lib/fastbeans/connection.rb, line 31
def disconnect!
  if @socket
    @socket.close rescue nil
    @socket = nil
  end
end
get_socket() click to toggle source
# File lib/fastbeans/connection.rb, line 27
def get_socket
  @socket || connect!(@host, @port)
end
perform(data, opts) click to toggle source
# File lib/fastbeans/connection.rb, line 85
def perform(data, opts)
  Request.new(self, opts).perform(data)
end
reconnect!() click to toggle source
# File lib/fastbeans/connection.rb, line 38
def reconnect!
  disconnect!
  connect!(@host, @port)
end
with_socket() { |get_socket| ... } click to toggle source
# File lib/fastbeans/connection.rb, line 78
def with_socket
  yield(get_socket)
rescue Exception => anything
  disconnect!
  raise
end