class SimpleCircuitBreaker

Constants

VERSION

Attributes

failure_threshold[R]
retry_timeout[R]

Public Class Methods

new(failure_threshold=3, retry_timeout=10) click to toggle source
# File lib/simple_circuit_breaker.rb, line 9
def initialize(failure_threshold=3, retry_timeout=10)
  @failure_threshold = failure_threshold
  @retry_timeout = retry_timeout
  reset!
end

Public Instance Methods

handle(*exceptions, &block) click to toggle source
# File lib/simple_circuit_breaker.rb, line 15
def handle(*exceptions, &block)
  if tripped?
    raise CircuitOpenError, 'Circuit is open'
  else
    execute(exceptions, &block)
  end
end

Protected Instance Methods

execute(exceptions) { || ... } click to toggle source
# File lib/simple_circuit_breaker.rb, line 25
def execute(exceptions, &block)
  result = yield
  reset!
  result
rescue Exception => e
  if exceptions.empty? || exceptions.any? { |exception| e.class <= exception }
    fail!
  end
  raise
end
fail!() click to toggle source
# File lib/simple_circuit_breaker.rb, line 36
def fail!
  @failures += 1
  if @failures >= @failure_threshold
    @state = :open
    @open_time = Time.now
  end
end
reset!() click to toggle source
# File lib/simple_circuit_breaker.rb, line 44
def reset!
  @state = :closed
  @failures = 0
end
timeout_exceeded?() click to toggle source
# File lib/simple_circuit_breaker.rb, line 53
def timeout_exceeded?
  @open_time + @retry_timeout < Time.now
end
tripped?() click to toggle source
# File lib/simple_circuit_breaker.rb, line 49
def tripped?
  @state == :open && !timeout_exceeded?
end