Class: ActiveRecord::Turntable::Algorithm::HashSlotAlgorithm
- Defined in:
- lib/active_record/turntable/algorithm/hash_slot_algorithm.rb
Constant Summary collapse
- DEFAULT_HASH_FUNC =
->(key) { Zlib.crc32(key.to_s) }
Instance Attribute Summary collapse
-
#hash_func ⇒ Object
readonly
Returns the value of attribute hash_func.
Instance Method Summary collapse
- #choose(shard_maps, key) ⇒ Object
- #choose_index(shard_maps, key) ⇒ Object
-
#initialize(config = {}) ⇒ HashSlotAlgorithm
constructor
A new instance of HashSlotAlgorithm.
- #shard_weights(shard_maps, current_sequence_value) ⇒ Object
- #slot_for_key(key, max) ⇒ Object
Constructor Details
#initialize(config = {}) ⇒ HashSlotAlgorithm
Returns a new instance of HashSlotAlgorithm.
9 10 11 12 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 9 def initialize(config = {}) super @hash_func = @config[:hash_func] || DEFAULT_HASH_FUNC end |
Instance Attribute Details
#hash_func ⇒ Object (readonly)
Returns the value of attribute hash_func.
7 8 9 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 7 def hash_func @hash_func end |
Instance Method Details
#choose(shard_maps, key) ⇒ Object
14 15 16 17 18 19 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 14 def choose(shard_maps, key) slot = slot_for_key(key, shard_maps.last.range.max) shard_map = shard_maps.bsearch { |shard| slot <= shard.range.max } raise ActiveRecord::Turntable::CannotSpecifyShardError, "cannot specify shard for key:#{key}" unless shard_map shard_map.shard end |
#choose_index(shard_maps, key) ⇒ Object
21 22 23 24 25 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 21 def choose_index(shard_maps, key) slot = slot_for_key(key, shard_maps.last.range.max) (0...shard_maps.size).bsearch { |idx| slot <= shard_maps[idx].range.max } or raise ActiveRecord::Turntable::CannotSpecifyShardError, "cannot specify shard for key:#{key}" end |
#shard_weights(shard_maps, current_sequence_value) ⇒ Object
31 32 33 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 31 def shard_weights(shard_maps, current_sequence_value) shard_maps.map { |shard_map| [shard_map.shard, shard_map.range.size] }.to_h end |
#slot_for_key(key, max) ⇒ Object
27 28 29 |
# File 'lib/active_record/turntable/algorithm/hash_slot_algorithm.rb', line 27 def slot_for_key(key, max) hash_func.call(key) % (max + 1) end |