Class: Alchemrest::CircuitBreaker

Inherits:
Object
  • Object
show all
Extended by:
Memosa
Defined in:
lib/alchemrest/circuit_breaker.rb

Defined Under Namespace

Classes: RequestFailed

Constant Summary collapse

DEFAULTS =
{
  # number of seconds the circuit stays open once we pass the error threshold
  sleep_window: 90,
  # length of interval (in seconds) over which it calculates the error rate
  time_window: 60,
  # number of requests within `time_window` seconds before it calculates
  # error rates (checked on failures)
  volume_threshold: 5,
  # exceeding this rate will open the circuit (checked on failures)
  error_threshold: 50,
  disabled_when: nil,
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ CircuitBreaker

Returns a new instance of CircuitBreaker.



30
31
32
# File 'lib/alchemrest/circuit_breaker.rb', line 30

def initialize(args)
  super(**DEFAULTS, **args)
end

Instance Method Details

#enabled?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/alchemrest/circuit_breaker.rb', line 34

def enabled?
  !service_name.nil? && (disabled_when.nil? || !disabled_when.call)
end

#monitor!(result:) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/alchemrest/circuit_breaker.rb', line 42

def monitor!(result:)
  return unless enabled?

  outcome = circuit_box.run(exception: false) do
    raise RequestFailed if request_failed?(result:)

    :success
  end

  outcome || :failure
end

#open?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/alchemrest/circuit_breaker.rb', line 38

def open?
  enabled? && circuit_box.open?
end