Class: CircuitBreakage::Breaker

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

Overview

A simple circuit breaker implementation. See the main README for usage details.

Direct Known Subclasses

RedisBackedBreaker

Constant Summary collapse

DEFAULT_FAILURE_THRESHOLD =

Number of failures required to trip circuit

5
DEFAULT_DURATION =

Number of seconds the circuit stays tripped

300
DEFAULT_TIMEOUT =

Number of seconds before the call times out

10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(block) ⇒ Breaker

Returns a new instance of Breaker.



18
19
20
21
22
23
24
25
26
# File 'lib/circuit_breakage/breaker.rb', line 18

def initialize(block)
  self.block              = block
  self.failure_threshold  = DEFAULT_FAILURE_THRESHOLD
  self.duration           = DEFAULT_DURATION
  self.timeout            = DEFAULT_TIMEOUT
  self.failure_count      ||= 0
  self.last_failed        ||= Time.at(0)
  self.state              ||= 'closed'
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



11
12
13
# File 'lib/circuit_breakage/breaker.rb', line 11

def block
  @block
end

#durationObject

Returns the value of attribute duration.



12
13
14
# File 'lib/circuit_breakage/breaker.rb', line 12

def duration
  @duration
end

#failure_countObject

Returns the value of attribute failure_count.



11
12
13
# File 'lib/circuit_breakage/breaker.rb', line 11

def failure_count
  @failure_count
end

#failure_thresholdObject

Returns the value of attribute failure_threshold.



12
13
14
# File 'lib/circuit_breakage/breaker.rb', line 12

def failure_threshold
  @failure_threshold
end

#last_failedObject

Returns the value of attribute last_failed.



11
12
13
# File 'lib/circuit_breakage/breaker.rb', line 11

def last_failed
  @last_failed
end

#stateObject

Returns the value of attribute state.



11
12
13
# File 'lib/circuit_breakage/breaker.rb', line 11

def state
  @state
end

#timeoutObject

Returns the value of attribute timeout.



12
13
14
# File 'lib/circuit_breakage/breaker.rb', line 12

def timeout
  @timeout
end

Instance Method Details

#call(*args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/circuit_breakage/breaker.rb', line 28

def call(*args)
  case(state)
  when 'open'
    if time_to_retry?
      do_retry(*args)
    else
      raise CircuitOpen
    end
  when 'closed'
    do_call(*args)
  end
end