Sha256: cffb4a0f1c4328548aa5bd516fe66942b83a2c1fe9f908c0e2a3b927bcf5224d

Contents?: true

Size: 1.13 KB

Versions: 3

Compression:

Stored size: 1.13 KB

Contents

module EbisuConnection
  class SlaveGroup
    class AllSlavesHasGoneError < StandardError; end

    def initialize(slaves_conf, spec)
      @slaves = slaves_conf.map do |conf|
        Slave.new(conf, spec)
      end

      recalc_roulette
    end

    def sample
      raise AllSlavesHasGoneError if @slaves.blank?
      @slaves[@roulette.sample]
    end

    def remove_connection(connection)
      return unless s = @slaves.detect{|s| s.connection == connection}
      s.disconnect! rescue nil
      @slaves.delete(s)
      raise AllSlavesHasGoneError if @slaves.blank?
      recalc_roulette
      nil
    end

    def all_disconnect!
      @reserve_release = nil
      @slaves.each {|s| s.disconnect!}
    end

    def reserve_release_connection!
      @reserve_release = true
    end

    def reserved_release?
      !!@reserve_release
    end

    private

    def recalc_roulette
      weight_list = @slaves.map {|s| s.weight }

      @roulette = []
      gcd = GreatestCommonDivisor.calc(weight_list)
      weight_list.each_with_index do |w, index|
        weight = w / gcd
        @roulette.concat([index] * weight)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ebisu_connection-0.2.0 lib/ebisu_connection/slave_group.rb
ebisu_connection-0.1.1 lib/ebisu_connection/slave_group.rb
ebisu_connection-0.1.0 lib/ebisu_connection/slave_group.rb