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
40
41
# File 'lib/makara/strategies/round_robin.rb', line 25

def next
  return safe_value(0, true) if single_one?

  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



45
46
47
48
49
# File 'lib/makara/strategies/round_robin.rb', line 45

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



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

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)


69
70
71
# File 'lib/makara/strategies/round_robin.rb', line 69

def should_shuffle?
  true
end

#single_one?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/makara/strategies/round_robin.rb', line 73

def single_one?
  false
end