Sha256: 4b840531630ec2a993c01407afaff8a46a2a6df5bfed30df2ee0e6ad1fd9fa68

Contents?: true

Size: 805 Bytes

Versions: 3

Compression:

Stored size: 805 Bytes

Contents

module Aggro
  # Public: Computes which nodes are responsible for a given aggregate ID.
  class NodeList
    DEFAULT_REPLICATION_FACTOR = 3

    attr_reader :state

    def add(node)
      hash_ring << node

      update_state
    end

    def nodes_for(id, replication_factor = default_replication_factor)
      nodes
        .cycle
        .take(nodes.index(hash_ring.node_for(id)) + replication_factor)
        .last(replication_factor)
    end

    def nodes
      hash_ring.nodes.sort_by(&:id)
    end

    private

    def default_replication_factor
      [nodes.length, DEFAULT_REPLICATION_FACTOR].min
    end

    def hash_ring
      @hash_ring ||= ConsistentHashing::Ring.new
    end

    def update_state
      @state = Digest::MD5.hexdigest(nodes.map(&:to_s).join)[0..16].hex
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
aggro-0.0.4 lib/aggro/node_list.rb
aggro-0.0.3 lib/aggro/node_list.rb
aggro-0.0.2 lib/aggro/node_list.rb