Class: MultiThink::Connection

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

Constant Summary collapse

DEFAULTS =
{
  retries: 10,
  retry_interval: 1,
  conn_timeout: 1
}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



15
16
17
18
19
20
21
22
# File 'lib/multithink/connection.rb', line 15

def initialize(options = {})
  options = DEFAULTS.merge(options)
  @servers = options.fetch(:servers)
  @retries = options.fetch(:retries)
  @retry_interval = options.fetch(:retry_interval)
  @conn_timeout = options.fetch(:conn_timeout)
  connect
end

Instance Method Details

#connectObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/multithink/connection.rb', line 24

def connect
  @tried = 0
  while @tried < @retries do
    @servers.each do |server|
      begin
        #TODO(jpg) make timeout configurable
        Timeout::timeout(@conn_timeout) do
          @conn = r.connect(server)
        end
        return true
      rescue
        sleep @retry_interval
      end
      @tried += 1
    end
  end
  # If we got here we couldn't get a connection. :(
  raise "Error: Reached maximum retries (#{@retries})"
end

#is_connection_error(e) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/multithink/connection.rb', line 54

def is_connection_error(e)
  case e
  when Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::EPIPE,
    Errno::ECONNRESET, Errno::ETIMEDOUT, IOError
    true
  when RethinkDB::RqlRuntimeError
    e.message =~ /cannot perform (read|write): No master available/ ||
    e.message =~ /Error: Connection Closed/
  else
    false
  end
end

#reconnectObject



67
68
69
70
71
72
73
74
75
# File 'lib/multithink/connection.rb', line 67

def reconnect
  begin
    # try fast path first
    @conn.reconnect
  rescue
    # if that fails then try get a new connection
    connect
  end
end

#run(query, *args) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/multithink/connection.rb', line 44

def run(query, *args)
  begin
    query.run(@conn, *args)
  rescue StandardError => e
    if is_connection_error(e)
      retry if reconnect
    end
  end
end