Class: CB2::RollingWindow

Inherits:
Object
  • Object
show all
Defined in:
lib/cb2/strategies/rolling_window.rb

Direct Known Subclasses

Percentage

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ RollingWindow

Returns a new instance of RollingWindow.



4
5
6
7
8
9
10
# File 'lib/cb2/strategies/rolling_window.rb', line 4

def initialize(options)
  @service        = options.fetch(:service)
  @duration       = options.fetch(:duration)
  @threshold      = options.fetch(:threshold)
  @reenable_after = options.fetch(:reenable_after)
  @redis          = options[:redis] || Redis.new
end

Instance Attribute Details

#durationObject

Returns the value of attribute duration.



2
3
4
# File 'lib/cb2/strategies/rolling_window.rb', line 2

def duration
  @duration
end

#redisObject

Returns the value of attribute redis.



2
3
4
# File 'lib/cb2/strategies/rolling_window.rb', line 2

def redis
  @redis
end

#reenable_afterObject

Returns the value of attribute reenable_after.



2
3
4
# File 'lib/cb2/strategies/rolling_window.rb', line 2

def reenable_after
  @reenable_after
end

#serviceObject

Returns the value of attribute service.



2
3
4
# File 'lib/cb2/strategies/rolling_window.rb', line 2

def service
  @service
end

#thresholdObject

Returns the value of attribute threshold.



2
3
4
# File 'lib/cb2/strategies/rolling_window.rb', line 2

def threshold
  @threshold
end

Instance Method Details

#errorObject



31
32
33
34
35
36
# File 'lib/cb2/strategies/rolling_window.rb', line 31

def error
  count = increment_rolling_window(key("error"))
  if half_open? || should_open?(count)
    trip!
  end
end

#half_open?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/cb2/strategies/rolling_window.rb', line 17

def half_open?
  last_open && last_open.to_i < (Time.now.to_i - reenable_after)
end

#key(id = nil) ⇒ Object

generate a key to use in redis



49
50
51
52
# File 'lib/cb2/strategies/rolling_window.rb', line 49

def key(id=nil)
  postfix = id ? "-#{id}" : ""
  "cb2-#{service}#{postfix}"
end

#last_openObject



21
22
23
# File 'lib/cb2/strategies/rolling_window.rb', line 21

def last_open
  @last_open ||= redis.get(key)
end

#open?Boolean

Returns:

  • (Boolean)


12
13
14
15
# File 'lib/cb2/strategies/rolling_window.rb', line 12

def open?
  @last_open = nil # always fetch the latest value from redis here
  last_open && last_open.to_i > (Time.now.to_i - reenable_after)
end

#reset!Object



38
39
40
41
# File 'lib/cb2/strategies/rolling_window.rb', line 38

def reset!
  @last_open = nil
  redis.del(key)
end

#successObject



25
26
27
28
29
# File 'lib/cb2/strategies/rolling_window.rb', line 25

def success
  if half_open?
    reset!
  end
end

#trip!Object



43
44
45
46
# File 'lib/cb2/strategies/rolling_window.rb', line 43

def trip!
  @last_open = Time.now.to_i
  redis.set(key, @last_open)
end