Sha256: 80142520af808cf6cb14fd7950d6a347b3552961ee759ffdb9f32f1c7cba64a1

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

require "concurrent"
require 'active_support/deprecation'
require "ebisu_connection/replica_group"

module EbisuConnection
  class ConnectionManager < FreshConnection::AbstractConnectionManager
    def initialize(replica_group = "replica")
      super
      @replicas = Concurrent::Map.new
    end

    def replica_connection
      replicas.sample.connection
    end

    def slave_connection
      ActiveSupport::Deprecation.warn(
        "'slave_connection' is deprecated and will removed from version 2.4.0. use 'replica_connection' insted."
      )

      replica_connection
    end

    def put_aside!
      return if check_own_connection

      ConfFile.if_modify do
        reserve_release_all_connection
        check_own_connection
      end
    end

    def clear_all_connections!
      @replicas.each_value do |s|
        s.all_disconnect!
      end

      @replicas.clear
      ConfFile.conf_clear!
    end

    def recovery?
      replicas.recovery_connection?
    end

    private

    def check_own_connection
      s = @replicas[current_thread_id]

      if s && s.reserved_release?
        s.all_disconnect!
        @replicas.delete(current_thread_id)
        true
      else
        false
      end
    end

    def reserve_release_all_connection
      @replicas.each_value do |s|
        s.reserve_release_connection!
      end
      ConfFile.conf_clear!
    end

    def replicas
      @replicas.fetch_or_store(current_thread_id) do |_|
        get_replicas
      end
    end

    def get_replicas
      ReplicaGroup.new(replica_conf, replica_group)
    end

    def replica_conf
      ConfFile.replica_conf(replica_group)
    end

    def current_thread_id
      Thread.current.object_id
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ebisu_connection-2.3.0 lib/ebisu_connection/connection_manager.rb