Class: ResilientReads::ReplicaPool

Inherits:
Object
  • Object
show all
Defined in:
lib/resilient_reads/replica_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeReplicaPool

Returns a new instance of ReplicaPool.



5
6
7
8
9
# File 'lib/resilient_reads/replica_pool.rb', line 5

def initialize
  @replicas = []
  @mutex = Mutex.new
  @rr_index = 0
end

Instance Attribute Details

#replicasObject (readonly)

Returns the value of attribute replicas.



3
4
5
# File 'lib/resilient_reads/replica_pool.rb', line 3

def replicas
  @replicas
end

Instance Method Details

#add(replica) ⇒ Object



11
12
13
# File 'lib/resilient_reads/replica_pool.rb', line 11

def add(replica)
  @mutex.synchronize { @replicas << replica }
end

#any_healthy?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/resilient_reads/replica_pool.rb', line 43

def any_healthy?
  @replicas.any?(&:healthy?)
end

#check_all_health!Object



55
56
57
# File 'lib/resilient_reads/replica_pool.rb', line 55

def check_all_health!
  @replicas.each(&:check_health!)
end

#each(&block) ⇒ Object



65
66
67
# File 'lib/resilient_reads/replica_pool.rb', line 65

def each(&block)
  @replicas.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/resilient_reads/replica_pool.rb', line 19

def empty?
  @replicas.empty?
end

#healthy_countObject



47
48
49
# File 'lib/resilient_reads/replica_pool.rb', line 47

def healthy_count
  @replicas.count(&:healthy?)
end

#mark_unhealthy(replica) ⇒ Object



51
52
53
# File 'lib/resilient_reads/replica_pool.rb', line 51

def mark_unhealthy(replica)
  replica.mark_unhealthy!
end

#next_healthyObject

Select the next healthy replica using the configured strategy. Returns nil when no healthy replica is available.



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

def next_healthy
  @mutex.synchronize do
    healthy = @replicas.select(&:healthy?)
    return nil if healthy.empty?

    case ResilientReads.config.balancing_strategy
    when :round_robin
      idx = @rr_index % healthy.size
      @rr_index += 1
      healthy[idx]
    when :random
      healthy.sample
    else
      healthy.first
    end
  end
end

#release_all_connectionsObject



59
60
61
62
63
# File 'lib/resilient_reads/replica_pool.rb', line 59

def release_all_connections
  @replicas.each do |r|
    r.release_connection rescue nil
  end
end

#sizeObject



15
16
17
# File 'lib/resilient_reads/replica_pool.rb', line 15

def size
  @replicas.size
end