Class: ActsAsTbackend::CircuitBreaker
- Inherits:
-
Object
- Object
- ActsAsTbackend::CircuitBreaker
- Defined in:
- lib/acts_as_tbackend/circuit_breaker.rb
Overview
A small thread-safe circuit breaker per (host, port). After threshold
consecutive failures it opens for cooldown seconds, then allows a single
half-open probe. Keeps a down daemon from stalling every request thread
(fail-fast) while a shadow write stays non-fatal.
Instance Method Summary collapse
- #allow_request? ⇒ Boolean
-
#initialize(threshold:, cooldown:) ⇒ CircuitBreaker
constructor
A new instance of CircuitBreaker.
- #open? ⇒ Boolean
- #record_failure ⇒ Object
- #record_success ⇒ Object
Constructor Details
#initialize(threshold:, cooldown:) ⇒ CircuitBreaker
Returns a new instance of CircuitBreaker.
9 10 11 12 13 14 15 |
# File 'lib/acts_as_tbackend/circuit_breaker.rb', line 9 def initialize(threshold:, cooldown:) @threshold = threshold @cooldown = cooldown @failures = 0 @opened_at = nil @mutex = Mutex.new end |
Instance Method Details
#allow_request? ⇒ Boolean
17 18 19 20 21 22 23 24 |
# File 'lib/acts_as_tbackend/circuit_breaker.rb', line 17 def allow_request? @mutex.synchronize do return true if @opened_at.nil? return true if (monotonic - @opened_at) >= @cooldown # half-open probe false end end |
#open? ⇒ Boolean
40 41 42 |
# File 'lib/acts_as_tbackend/circuit_breaker.rb', line 40 def open? @mutex.synchronize { !@opened_at.nil? && (monotonic - @opened_at) < @cooldown } end |
#record_failure ⇒ Object
33 34 35 36 37 38 |
# File 'lib/acts_as_tbackend/circuit_breaker.rb', line 33 def record_failure @mutex.synchronize do @failures += 1 @opened_at = monotonic if @failures >= @threshold end end |
#record_success ⇒ Object
26 27 28 29 30 31 |
# File 'lib/acts_as_tbackend/circuit_breaker.rb', line 26 def record_success @mutex.synchronize do @failures = 0 @opened_at = nil end end |