Class: Makara::Strategies::RoundRobin

Inherits:
Abstract
  • Object
show all
Defined in:
lib/makara/strategies/round_robin.rb

Instance Attribute Summary

Attributes inherited from Abstract

#pool

Instance Method Summary collapse

Methods inherited from Abstract

#initialize

Constructor Details

This class inherits a constructor from Makara::Strategies::Abstract

Instance Method Details

#connection_added(wrapper) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/makara/strategies/round_robin.rb', line 9

def connection_added(wrapper)
  # the weight results in N references to the connection, not N connections
  wrapper._makara_weight.times{ @weighted_connections << wrapper }

  if should_shuffle?
    # randomize the connections so we don't get peaks and valleys of load
    @weighted_connections.shuffle!
    # then start at a random spot in the list
    @current_idx = rand(@weighted_connections.length)
  end
end

#currentObject



21
22
23
# File 'lib/makara/strategies/round_robin.rb', line 21

def current
  safe_value(@current_idx)
end

#initObject



4
5
6
7
# File 'lib/makara/strategies/round_robin.rb', line 4

def init
  @current_idx = 0
  @weighted_connections = []
end

#nextObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/makara/strategies/round_robin.rb', line 25

def next
  idx = @current_idx
  begin

    idx = next_index(idx)

    # if we've looped all the way around, return our safe value
    return safe_value(idx, true) if idx == @current_idx

  # while our current safe value is dangerous
  end while safe_value(idx).nil?

  # store our current spot and return our safe value
  safe_value(idx, true)
end

#next_index(idx) ⇒ Object

next index within the bounds of the connections array loop around when the end is hit



43
44
45
46
47
# File 'lib/makara/strategies/round_robin.rb', line 43

def next_index(idx)
  idx = idx + 1
  idx = 0 if idx >= @weighted_connections.length
  idx
end

#safe_value(idx, stick = false) ⇒ Object

return the connection if it’s not blacklisted otherwise return nil optionally, store the position and context we’re returning



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/makara/strategies/round_robin.rb', line 53

def safe_value(idx, stick = false)
  con = @weighted_connections[idx]
  return nil unless con
  return nil if con._makara_blacklisted?

  if stick
    @current_idx = idx
  end

  con
end

#should_shuffle?Boolean

stub in test mode to ensure consistency

Returns:

  • (Boolean)


67
68
69
# File 'lib/makara/strategies/round_robin.rb', line 67

def should_shuffle?
  true
end