Class: Hedra::CircuitBreaker
- Inherits:
-
Object
- Object
- Hedra::CircuitBreaker
- Defined in:
- lib/hedra/circuit_breaker.rb
Overview
Circuit breaker pattern to prevent cascading failures
Constant Summary collapse
- FAILURE_THRESHOLD =
5- TIMEOUT_SECONDS =
60- HALF_OPEN_ATTEMPTS =
3
Instance Attribute Summary collapse
-
#failure_count ⇒ Object
readonly
Returns the value of attribute failure_count.
-
#last_failure_time ⇒ Object
readonly
Returns the value of attribute last_failure_time.
-
#state ⇒ Object
readonly
Returns the value of attribute state.
Instance Method Summary collapse
- #call ⇒ Object
- #closed? ⇒ Boolean
- #half_open? ⇒ Boolean
-
#initialize(failure_threshold: FAILURE_THRESHOLD, timeout: TIMEOUT_SECONDS) ⇒ CircuitBreaker
constructor
A new instance of CircuitBreaker.
- #open? ⇒ Boolean
Constructor Details
#initialize(failure_threshold: FAILURE_THRESHOLD, timeout: TIMEOUT_SECONDS) ⇒ CircuitBreaker
Returns a new instance of CircuitBreaker.
12 13 14 15 16 17 18 19 |
# File 'lib/hedra/circuit_breaker.rb', line 12 def initialize(failure_threshold: FAILURE_THRESHOLD, timeout: TIMEOUT_SECONDS) @failure_threshold = failure_threshold @timeout = timeout @failure_count = 0 @last_failure_time = nil @state = :closed @half_open_attempts = 0 end |
Instance Attribute Details
#failure_count ⇒ Object (readonly)
Returns the value of attribute failure_count.
10 11 12 |
# File 'lib/hedra/circuit_breaker.rb', line 10 def failure_count @failure_count end |
#last_failure_time ⇒ Object (readonly)
Returns the value of attribute last_failure_time.
10 11 12 |
# File 'lib/hedra/circuit_breaker.rb', line 10 def last_failure_time @last_failure_time end |
#state ⇒ Object (readonly)
Returns the value of attribute state.
10 11 12 |
# File 'lib/hedra/circuit_breaker.rb', line 10 def state @state end |
Instance Method Details
#call ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/hedra/circuit_breaker.rb', line 21 def call raise CircuitOpenError, 'Circuit breaker is open' if open? && !should_attempt_reset? if open? && should_attempt_reset? @state = :half_open @half_open_attempts = 0 end begin result = yield on_success result rescue StandardError => e on_failure raise e end end |
#closed? ⇒ Boolean
43 44 45 |
# File 'lib/hedra/circuit_breaker.rb', line 43 def closed? @state == :closed end |
#half_open? ⇒ Boolean
47 48 49 |
# File 'lib/hedra/circuit_breaker.rb', line 47 def half_open? @state == :half_open end |
#open? ⇒ Boolean
39 40 41 |
# File 'lib/hedra/circuit_breaker.rb', line 39 def open? @state == :open end |