Class: Semian::CircuitBreaker
- Inherits:
-
Object
- Object
- Semian::CircuitBreaker
- Extended by:
- Forwardable
- Defined in:
- lib/semian/circuit_breaker.rb
Overview
:nodoc:
Instance Method Summary collapse
- #acquire ⇒ Object
- #destroy ⇒ Object
-
#initialize(name, exceptions:, success_threshold:, error_threshold:, error_timeout:, implementation:) ⇒ CircuitBreaker
constructor
A new instance of CircuitBreaker.
- #mark_failed(_error) ⇒ Object
- #mark_success ⇒ Object
- #request_allowed? ⇒ Boolean
- #reset ⇒ Object
Constructor Details
#initialize(name, exceptions:, success_threshold:, error_threshold:, error_timeout:, implementation:) ⇒ CircuitBreaker
Returns a new instance of CircuitBreaker.
7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/semian/circuit_breaker.rb', line 7 def initialize(name, exceptions:, success_threshold:, error_threshold:, error_timeout:, implementation:) @name = name.to_sym @success_count_threshold = success_threshold @error_count_threshold = error_threshold @error_timeout = error_timeout @exceptions = exceptions @errors = implementation::SlidingWindow.new(max_size: @error_count_threshold) @successes = implementation::Integer.new @state = implementation::State.new end |
Instance Method Details
#acquire ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/semian/circuit_breaker.rb', line 19 def acquire half_open if open? && error_timeout_expired? raise OpenCircuitError unless request_allowed? result = nil begin result = yield rescue *@exceptions => error mark_failed(error) raise error else mark_success end result end |
#destroy ⇒ Object
64 65 66 67 68 |
# File 'lib/semian/circuit_breaker.rb', line 64 def destroy @errors.destroy @successes.destroy @state.destroy end |
#mark_failed(_error) ⇒ Object
43 44 45 46 47 48 49 50 |
# File 'lib/semian/circuit_breaker.rb', line 43 def mark_failed(_error) push_time(@errors, duration: @error_timeout) if closed? open if error_threshold_reached? elsif half_open? open end end |
#mark_success ⇒ Object
52 53 54 55 56 |
# File 'lib/semian/circuit_breaker.rb', line 52 def mark_success return unless half_open? @successes.increment close if success_threshold_reached? end |
#request_allowed? ⇒ Boolean
36 37 38 39 40 41 |
# File 'lib/semian/circuit_breaker.rb', line 36 def request_allowed? closed? || half_open? || # The circuit breaker is officially open, but it will transition to half-open on the next attempt. (open? && error_timeout_expired?) end |
#reset ⇒ Object
58 59 60 61 62 |
# File 'lib/semian/circuit_breaker.rb', line 58 def reset @errors.clear @successes.reset close end |