Class: ConsistentHashing::Ring

Inherits:
Object
  • Object
show all
Defined in:
lib/consistent_hashing/ring.rb

Overview

Public: the hash ring containing all configured nodes

Instance Method Summary collapse

Constructor Details

#initialize(nodes = [], replicas = 3) ⇒ Ring

Public: returns a new ring object



11
12
13
14
15
16
# File 'lib/consistent_hashing/ring.rb', line 11

def initialize(nodes = [], replicas = 3)
  @replicas = replicas
  @ring = AVLTree.new

  nodes.each { |node| add(node) }
end

Instance Method Details

#<<(node) ⇒ Object

Public: adds a new node into the hash ring like ‘add` but returns a reference to the ring to be used as a fluent interface



39
40
41
42
# File 'lib/consistent_hashing/ring.rb', line 39

def <<(node)
  add(node)
  self
end

#add(node) ⇒ Object

Public: adds a new node into the hash ring



27
28
29
30
31
32
33
34
# File 'lib/consistent_hashing/ring.rb', line 27

def add(node)
  @replicas.times do |i|
    # generate the key of this (virtual) point in the hash
    key = hash_key(node, i)

    @ring[key] = VirtualPoint.new(node, key)
  end
end

#delete(node) ⇒ Object

Public: removes a node from the hash ring



46
47
48
49
50
51
52
53
54
# File 'lib/consistent_hashing/ring.rb', line 46

def delete(node)
  @replicas.times do |i|
    key = hash_key(node, i)

    @ring.delete key
  end

  self
end

#lengthObject

Public: returns the (virtual) points in the hash ring

Returns: a Fixnum



21
22
23
# File 'lib/consistent_hashing/ring.rb', line 21

def length
  @ring.length
end

#node_for(key) ⇒ Object

Public: gets the node where to store the key

Returns: the node Object



70
71
72
# File 'lib/consistent_hashing/ring.rb', line 70

def node_for(key)
  point_for(key).node
end

#nodesObject

Public: get all nodes in the ring

Returns: an Array of the nodes in the ring



77
78
79
80
# File 'lib/consistent_hashing/ring.rb', line 77

def nodes
  nodes = points.map { |point| point.node }
  nodes.uniq
end

#point_for(key) ⇒ Object

Public: gets the point for an arbitrary key



59
60
61
62
63
64
65
# File 'lib/consistent_hashing/ring.rb', line 59

def point_for(key)
  return nil if @ring.empty?
  key = hash_key(key)
  _, value = @ring.next_gte_pair(key)
  _, value = @ring.minimum_pair unless value
  value
end

#pointsObject

Public: gets all points in the ring

Returns: an Array of the points in the ring



85
86
87
# File 'lib/consistent_hashing/ring.rb', line 85

def points
  @ring.map { |point| point[1] }
end