Class: Philiprehberger::Circuit::Breaker

Inherits:
Object
  • Object
show all
Includes:
Backoff, Callbacks, Execution, Metrics
Defined in:
lib/philiprehberger/circuit/breaker.rb

Overview

Circuit breaker with three states: closed, open, half-open

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Callbacks

#on_close, #on_half_open, #on_open, #on_reset

Methods included from Metrics

#metrics

Constructor Details

#initialize(name, **opts) ⇒ Breaker

Returns a new instance of Breaker.

Parameters:

  • name (Symbol, String)

    breaker name

  • threshold (Integer)

    failures before opening

  • timeout (Numeric)

    seconds before trying half-open

  • error_classes (Array<Class>)

    exception classes to count

  • half_open_requests (Integer)

    max probe requests in half-open

  • timeout_strategy (Symbol)

    :fixed or :exponential

  • base_timeout (Numeric)

    base timeout for exponential backoff

  • max_timeout (Numeric)

    max timeout cap for exponential backoff



22
23
24
25
26
27
28
29
# File 'lib/philiprehberger/circuit/breaker.rb', line 22

def initialize(name, **opts)
  @name = name
  @mutex = Mutex.new
  init_core_state(opts)
  init_callbacks
  init_metrics
  init_backoff_config(opts)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

Instance Method Details

#call(fallback: nil, &block) ⇒ Object

Execute a block with circuit protection



32
33
34
# File 'lib/philiprehberger/circuit/breaker.rb', line 32

def call(fallback: nil, &block)
  @mutex.synchronize { handle_state(fallback, &block) }
end

#reset!Object

Force circuit back to closed state



42
43
44
# File 'lib/philiprehberger/circuit/breaker.rb', line 42

def reset!
  @mutex.synchronize { transition_to(CLOSED) }
end

#stateObject

Current circuit state



37
38
39
# File 'lib/philiprehberger/circuit/breaker.rb', line 37

def state
  @mutex.synchronize { @state }
end

#trip!Object

Force circuit to open state (administrative trip)



47
48
49
# File 'lib/philiprehberger/circuit/breaker.rb', line 47

def trip!
  @mutex.synchronize { transition_to(OPEN) }
end