Class: OpenTrace::CircuitBreaker
- Inherits:
-
Object
- Object
- OpenTrace::CircuitBreaker
- Defined in:
- lib/opentrace/circuit_breaker.rb
Constant Summary collapse
- CLOSED =
:closed- OPEN =
:open- HALF_OPEN =
:half_open
Instance Attribute Summary collapse
-
#state ⇒ Object
readonly
Returns the value of attribute state.
Instance Method Summary collapse
- #allow_request? ⇒ Boolean
-
#initialize(failure_threshold:, recovery_timeout:) ⇒ CircuitBreaker
constructor
A new instance of CircuitBreaker.
- #record_failure ⇒ Object
- #record_success ⇒ Object
- #reset! ⇒ Object
Constructor Details
#initialize(failure_threshold:, recovery_timeout:) ⇒ CircuitBreaker
Returns a new instance of CircuitBreaker.
11 12 13 14 15 16 17 18 |
# File 'lib/opentrace/circuit_breaker.rb', line 11 def initialize(failure_threshold:, recovery_timeout:) @failure_threshold = failure_threshold @recovery_timeout = recovery_timeout @state = CLOSED @failure_count = 0 @last_failure_at = nil @mutex = Mutex.new end |
Instance Attribute Details
#state ⇒ Object (readonly)
Returns the value of attribute state.
9 10 11 |
# File 'lib/opentrace/circuit_breaker.rb', line 9 def state @state end |
Instance Method Details
#allow_request? ⇒ Boolean
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/opentrace/circuit_breaker.rb', line 20 def allow_request? @mutex.synchronize do case @state when CLOSED true when OPEN if Time.now - @last_failure_at >= @recovery_timeout @state = HALF_OPEN true else false end when HALF_OPEN false end end end |
#record_failure ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/opentrace/circuit_breaker.rb', line 45 def record_failure @mutex.synchronize do @failure_count += 1 @last_failure_at = Time.now @state = OPEN if @failure_count >= @failure_threshold end end |
#record_success ⇒ Object
38 39 40 41 42 43 |
# File 'lib/opentrace/circuit_breaker.rb', line 38 def record_success @mutex.synchronize do @failure_count = 0 @state = CLOSED end end |
#reset! ⇒ Object
53 54 55 56 57 58 59 |
# File 'lib/opentrace/circuit_breaker.rb', line 53 def reset! @mutex.synchronize do @state = CLOSED @failure_count = 0 @last_failure_at = nil end end |