Class: Chronos::Application::CircuitBreaker

Inherits:
Object
  • Object
show all
Defined in:
lib/chronos/application/circuit_breaker.rb

Overview

Small circuit breaker for retryable transport failures.

Examples:

transport.send_event(event) if breaker.allow_request?

Instance Method Summary collapse

Constructor Details

#initialize(failure_threshold, reset_timeout, clock) ⇒ CircuitBreaker

Returns a new instance of CircuitBreaker.



16
17
18
19
20
21
22
23
24
25
# File 'lib/chronos/application/circuit_breaker.rb', line 16

def initialize(failure_threshold, reset_timeout, clock)
  @failure_threshold = failure_threshold
  @reset_timeout = reset_timeout
  @clock = clock
  @state = :closed
  @failures = 0
  @opened_at = nil
  @probe_in_flight = false
  @mutex = Mutex.new
end

Instance Method Details

#allow_request?Boolean

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
35
36
37
# File 'lib/chronos/application/circuit_breaker.rb', line 27

def allow_request?
  @mutex.synchronize do
    return true if @state == :closed
    return false if @state == :half_open && @probe_in_flight
    return false unless reset_elapsed?

    @state = :half_open
    @probe_in_flight = true
    true
  end
end

#record_failureObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/chronos/application/circuit_breaker.rb', line 48

def record_failure
  @mutex.synchronize do
    @failures += 1
    if @state == :half_open || @failures >= @failure_threshold
      @state = :open
      @opened_at = @clock.call
    end
    @probe_in_flight = false
  end
end

#record_successObject



39
40
41
42
43
44
45
46
# File 'lib/chronos/application/circuit_breaker.rb', line 39

def record_success
  @mutex.synchronize do
    @state = :closed
    @failures = 0
    @opened_at = nil
    @probe_in_flight = false
  end
end

#stateObject



59
60
61
# File 'lib/chronos/application/circuit_breaker.rb', line 59

def state
  @mutex.synchronize { @state }
end