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: an alias for ‘add`



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

def <<(node)
  add(node)
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



44
45
46
47
48
49
50
# File 'lib/consistent_hashing/ring.rb', line 44

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

    @ring.delete key
  end
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



66
67
68
# File 'lib/consistent_hashing/ring.rb', line 66

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



73
74
75
76
# File 'lib/consistent_hashing/ring.rb', line 73

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

#point_for(key) ⇒ Object

Public: gets the point for an arbitrary key



55
56
57
58
59
60
61
# File 'lib/consistent_hashing/ring.rb', line 55

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



81
82
83
# File 'lib/consistent_hashing/ring.rb', line 81

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