Class: Complyance::CircuitBreaker

Inherits:
Object
  • Object
show all
Defined in:
lib/complyance/circuit_breaker.rb

Overview

Circuit Breaker implementation for handling service failures

Constant Summary collapse

STATE_CLOSED =
'CLOSED'
STATE_OPEN =
'OPEN'
STATE_HALF_OPEN =
'HALF_OPEN'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ CircuitBreaker

Initialize circuit breaker

Parameters:

  • config (Hash) (defaults to: {})

    Circuit breaker configuration

Options Hash (config):

  • :failure_threshold (Integer)

    Number of failures before opening circuit

  • :reset_timeout (Integer)

    Timeout in seconds before attempting reset



16
17
18
19
20
21
22
23
24
# File 'lib/complyance/circuit_breaker.rb', line 16

def initialize(config = {})
  @state = STATE_CLOSED
  @failure_count = 0
  @last_failure_time = 0
  @failure_threshold = config[:failure_threshold] || 3
  @reset_timeout = config[:reset_timeout] || 60
  @logger = Logger.new(STDOUT)
  @logger.level = Logger::INFO
end

Instance Attribute Details

#failure_countObject (readonly)

Returns the value of attribute failure_count.



10
11
12
# File 'lib/complyance/circuit_breaker.rb', line 10

def failure_count
  @failure_count
end

#last_failure_timeObject (readonly)

Returns the value of attribute last_failure_time.



10
11
12
# File 'lib/complyance/circuit_breaker.rb', line 10

def last_failure_time
  @last_failure_time
end

#stateObject (readonly)

Returns the value of attribute state.



10
11
12
# File 'lib/complyance/circuit_breaker.rb', line 10

def state
  @state
end

Instance Method Details

#execute(&operation) ⇒ Object

Execute a function with circuit breaker protection

Parameters:

  • operation (Proc)

    Function to execute

Returns:

  • (Object)

    Result of operation

Raises:

  • (RuntimeError)

    If circuit is open



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/complyance/circuit_breaker.rb', line 30

def execute(&operation)
  check_state
  
  begin
    result = operation.call
    record_success
    result
  rescue => e
    record_failure
    raise e
  end
end

#open?Boolean

Check if circuit breaker is currently open

Returns:

  • (Boolean)

    True if open



45
46
47
# File 'lib/complyance/circuit_breaker.rb', line 45

def open?
  @state == STATE_OPEN
end