Class: Cachext::Breaker::WithKey

Inherits:
Object
  • Object
show all
Defined in:
lib/cachext/breaker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, key) ⇒ WithKey

Returns a new instance of WithKey.



18
19
20
21
# File 'lib/cachext/breaker.rb', line 18

def initialize(config, key)
  @config = config
  @key = key
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



16
17
18
# File 'lib/cachext/breaker.rb', line 16

def config
  @config
end

#keyObject (readonly)

Returns the value of attribute key.



16
17
18
# File 'lib/cachext/breaker.rb', line 16

def key
  @key
end

Instance Method Details

#check_healthObject



30
31
32
33
34
35
36
37
38
# File 'lib/cachext/breaker.rb', line 30

def check_health
  if half_open?
    if health_check >= config.failure_threshold
      reset!
    else
      increment_health_check
    end
  end
end

#half_open?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/cachext/breaker.rb', line 50

def half_open?
  state == :half_open
end

#health_checkObject



73
74
75
# File 'lib/cachext/breaker.rb', line 73

def health_check
  lock_redis.get(key_str(:health_check)).to_i
end

#increment_failureObject



23
24
25
26
27
28
# File 'lib/cachext/breaker.rb', line 23

def increment_failure
  lock_redis.pipelined do
    lock_redis.set key_str(:last_failure), Time.now.to_f
    lock_redis.incr key_str(:monitor)
  end
end

#increment_health_checkObject



77
78
79
# File 'lib/cachext/breaker.rb', line 77

def increment_health_check
  lock_redis.incr key_str(:health_check)
end

#key_str(name) ⇒ Object



81
82
83
# File 'lib/cachext/breaker.rb', line 81

def key_str(name)
  "cachext:#{name}:#{key.raw.map(&:to_s).join(":")}"
end

#last_failureObject



68
69
70
71
# File 'lib/cachext/breaker.rb', line 68

def last_failure
  lf = lock_redis.get key_str(:last_failure)
  lf.nil? ? nil : lf.to_f
end

#lock_redisObject



85
86
87
# File 'lib/cachext/breaker.rb', line 85

def lock_redis
  config.lock_redis
end

#monitorObject



64
65
66
# File 'lib/cachext/breaker.rb', line 64

def monitor
  lock_redis.get(key_str(:monitor)).to_i
end

#open?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/cachext/breaker.rb', line 46

def open?
  state == :open
end

#reset!Object



40
41
42
43
44
# File 'lib/cachext/breaker.rb', line 40

def reset!
  lock_redis.del key_str(:monitor),
            key_str(:health_check),
            key_str(:last_failure)
end

#stateObject



54
55
56
57
58
59
60
61
62
# File 'lib/cachext/breaker.rb', line 54

def state
  if (lf = last_failure) && (lf + config.breaker_timeout < Time.now.to_f)
    :half_open
  elsif monitor >= config.failure_threshold
    :open
  else
    :close
  end
end