Class: RailsFailover::Redis::Connector

Inherits:
Redis::Client::Connector
  • Object
show all
Defined in:
lib/rails_failover/redis/connector.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Connector

Returns a new instance of Connector.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rails_failover/redis/connector.rb', line 8

def initialize(options)
  original_driver = options[:driver]
  options[:primary_host] = options[:host]
  options[:primary_port] = options[:port]

  options[:driver] = Class.new(options[:driver]) do
    def self.connect(options)
      is_primary =
        (options[:host] == options[:primary_host]) &&
          (options[:port] == options[:primary_port])
      super(options).tap { |conn| conn.rails_failover_role = is_primary ? PRIMARY : REPLICA }
    rescue ::Redis::TimeoutError,
           SocketError,
           Errno::EADDRNOTAVAIL,
           Errno::ECONNREFUSED,
           Errno::EHOSTDOWN,
           Errno::EHOSTUNREACH,
           Errno::ENETUNREACH,
           Errno::ENOENT,
           Errno::ETIMEDOUT,
           Errno::EINVAL => e
      Handler.instance.verify_primary(options) if is_primary
      raise e
    end

    attr_accessor :rails_failover_role

    def shutdown_socket
      @sock&.shutdown
    rescue Errno::ENOTCONN
    end
  end

  options[:original_driver] = original_driver
  options.delete(:connector)
  options[:id] ||= "#{options[:host]}:#{options[:port]}"
  @replica_options = replica_options(options)
  @options = options.dup
end

Instance Method Details

#check(client) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/rails_failover/redis/connector.rb', line 52

def check(client)
  Handler.instance.register_client(client)
  expected_role = Handler.instance.primary_down?(@options) ? REPLICA : PRIMARY
  if client.connection.rails_failover_role != expected_role
    raise ::Redis::CannotConnectError, "Opened with unexpected failover role"
  end
end

#on_disconnect(client) ⇒ Object



60
61
62
# File 'lib/rails_failover/redis/connector.rb', line 60

def on_disconnect(client)
  Handler.instance.deregister_client(client)
end

#resolveObject



48
49
50
# File 'lib/rails_failover/redis/connector.rb', line 48

def resolve
  Handler.instance.primary_down?(@options) ? @replica_options : @options
end