Class: Peasant::NodeManager

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/peasant/node_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes) ⇒ NodeManager

Returns a new instance of NodeManager.



7
8
9
10
11
12
# File 'lib/peasant/node_manager.rb', line 7

def initialize nodes
  @nodes = nodes
  @pool = @nodes.clone
  @peers = {}
  @strategy = :roundrobin
end

Instance Attribute Details

#nodesObject

Returns the value of attribute nodes.



5
6
7
# File 'lib/peasant/node_manager.rb', line 5

def nodes
  @nodes
end

#strategyObject

Returns the value of attribute strategy.



5
6
7
# File 'lib/peasant/node_manager.rb', line 5

def strategy
  @strategy
end

Instance Method Details

#each(&block) ⇒ Object



49
50
51
52
53
# File 'lib/peasant/node_manager.rb', line 49

def each &block
  @nodes.each do |node|
    block.call(node)
  end
end

#select {|node| ... } ⇒ Object

Yields:

  • (node)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/peasant/node_manager.rb', line 14

def select
  @pool = @nodes.clone if @pool.empty?

  case @strategy
  when :balanced
    node = @nodes.sort_by{ |b| b.load }.first
  when :roundrobin
    node = @pool.shift
  when :random
    node = @nodes.sample
  when :manual
    node = @pool.first
  else
    raise ArgumentError, "Unknown strategy: #{@strategy}"
  end

  node.on_select_cb.call
  yield node if block_given?
  node
end

#select_for(peer) {|node| ... } ⇒ Object

Yields:

  • (node)


35
36
37
38
39
40
41
42
# File 'lib/peasant/node_manager.rb', line 35

def select_for peer
  peer_info = @peers[peer] ||= PeerInfo.new(peer)
  node = peer_info.node ||= select
  peer_info.inc_requests
  peer_info.reset_node_expiration
  yield node if block_given?
  node
end

#shift_poolObject



44
45
46
47
# File 'lib/peasant/node_manager.rb', line 44

def shift_pool
  @pool = @nodes.clone if @pool.empty?
  @pool.shift
end