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

def initialize(host, port)
  Fastbeans.debug("Connecting to #{host}:#{port}")
  @host, @port = host, port
  @socket = connect!(@host, @port)
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) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fastbeans/connection.rb', line 38

def call(*data)
  retries = 0
  begin
    call_without_retries(data)
  rescue Fastbeans::RemoteConnectionFailed => 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) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/fastbeans/connection.rb', line 59

def call_without_retries(data)
  perform(data)

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



16
17
18
19
20
# File 'lib/fastbeans/connection.rb', line 16

def connect!(host, port)
  @socket = TCPSocket.new(host, port)
  @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
  @socket
end

#disconnect!Object



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

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

#get_socketObject



22
23
24
# File 'lib/fastbeans/connection.rb', line 22

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

#perform(data) ⇒ Object



77
78
79
# File 'lib/fastbeans/connection.rb', line 77

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

#reconnect!Object



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

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

#with_socket {|get_socket| ... } ⇒ Object

Yields:



73
74
75
# File 'lib/fastbeans/connection.rb', line 73

def with_socket
  yield(get_socket)
end