Sha256: 51cb26a3873230b51462ae58606afa8e3af450cd883727b2fc470e7e8b208bbd

Contents?: true

Size: 1.41 KB

Versions: 12

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

require_relative '../errors'
require_relative 'node_key'

class Redis
  class Cluster
    # Load and hashify slot info for Redis Cluster Client
    module SlotLoader
      module_function

      def load(nodes)
        info = {}

        nodes.each do |node|
          info = fetch_slot_info(node)
          info.empty? ? next : break
        end

        return info unless info.empty?

        raise CannotConnectError, 'Redis client could not connect to any cluster nodes'
      end

      def fetch_slot_info(node)
        hash_with_default_arr = Hash.new { |h, k| h[k] = [] }
        node.call(%i[cluster slots])
            .flat_map { |arr| parse_slot_info(arr, default_ip: node.host) }
            .each_with_object(hash_with_default_arr) { |arr, h| h[arr[0]] << arr[1] }
      rescue CannotConnectError, ConnectionError, CommandError
        {} # can retry on another node
      end

      def parse_slot_info(arr, default_ip:)
        first_slot, last_slot = arr[0..1]
        slot_range = (first_slot..last_slot).freeze
        arr[2..-1].map { |addr| [stringify_node_key(addr, default_ip), slot_range] }
      end

      def stringify_node_key(arr, default_ip)
        ip, port = arr
        ip = default_ip if ip.empty? # When cluster is down
        NodeKey.build_from_host_port(ip, port)
      end

      private_class_method :fetch_slot_info, :parse_slot_info, :stringify_node_key
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
redis-4.6.0 lib/redis/cluster/slot_loader.rb
redis-4.5.1 lib/redis/cluster/slot_loader.rb
redis-4.5.0 lib/redis/cluster/slot_loader.rb
redis-4.4.0 lib/redis/cluster/slot_loader.rb
redis-4.3.1 lib/redis/cluster/slot_loader.rb
redis-4.3.0 lib/redis/cluster/slot_loader.rb
redis-4.2.5 lib/redis/cluster/slot_loader.rb
redis-4.2.4 lib/redis/cluster/slot_loader.rb
redis-4.2.3 lib/redis/cluster/slot_loader.rb
redis-4.2.2 lib/redis/cluster/slot_loader.rb
redis-4.2.1 lib/redis/cluster/slot_loader.rb
redis-4.2.0 lib/redis/cluster/slot_loader.rb