Class: Fastbeans::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/fastbeans/connection.rb

Constant Summary collapse

MAX_RETRIES =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Connection

Returns a new instance of Connection.



10
11
12
13
14
15
16
17
18
19
# 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

Instance Attribute Details

#socketObject (readonly)

Returns the value of attribute socket.



8
9
10
# File 'lib/fastbeans/connection.rb', line 8

def socket
  @socket
end

Instance Method Details

#call(data, opts) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 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) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# 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) ⇒ Object



21
22
23
24
25
# 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!Object



31
32
33
34
35
36
# File 'lib/fastbeans/connection.rb', line 31

def disconnect!
  if @socket
    @socket.close rescue nil
    @socket = nil
  end
end

#get_socketObject



27
28
29
# File 'lib/fastbeans/connection.rb', line 27

def get_socket
  @socket || connect!(@host, @port)
end

#perform(data, opts) ⇒ Object



85
86
87
# File 'lib/fastbeans/connection.rb', line 85

def perform(data, opts)
  Request.new(self, opts).perform(data)
end

#reconnect!Object



38
39
40
41
# File 'lib/fastbeans/connection.rb', line 38

def reconnect!
  disconnect!
  connect!(@host, @port)
end

#with_socketObject



78
79
80
81
82
83
# File 'lib/fastbeans/connection.rb', line 78

def with_socket
  yield(get_socket)
rescue Exception => anything
  disconnect!
  raise
end