Class: CB2::RollingWindow

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

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/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          = Redis.current
end

Instance Attribute Details

#durationObject

Returns the value of attribute duration.



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

def duration
  @duration
end

#redisObject

Returns the value of attribute redis.



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

def redis
  @redis
end

#reenable_afterObject

Returns the value of attribute reenable_after.



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

def reenable_after
  @reenable_after
end

#serviceObject

Returns the value of attribute service.



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

def service
  @service
end

#thresholdObject

Returns the value of attribute threshold.



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

def threshold
  @threshold
end

Instance Method Details

#open!Object



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

def open!
  redis.setex(cache_key, reenable_after, 1)
end

#open?Boolean

Returns:

  • (Boolean)


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

def open?
  redis.exists(cache_key)
end

#processObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/strategies/rolling_window.rb', line 20

def process
  key = "circuit-breaker-count-#{service}"
  t   = Time.now.to_i
  pipeline = redis.pipelined do
    # keep the sorted set clean
    redis.zremrangebyscore(key, "-inf", t - duration)
    # add as a random uuid because sorted sets won't take duplicate items:
    redis.zadd(key, t, SecureRandom.uuid)
    # just count how many errors are left in the set
    redis.zcard(key)
  end
  if pipeline.last >= threshold
    open!
  end
end