Class: OpenTrace::CircuitBreaker

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

Constant Summary collapse

CLOSED =
:closed
OPEN =
:open
HALF_OPEN =
:half_open

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(failure_threshold:, recovery_timeout:) ⇒ CircuitBreaker

Returns a new instance of CircuitBreaker.



11
12
13
14
15
16
17
18
19
# 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
  @half_open_probe_sent = false
  @mutex             = Mutex.new
end

Instance Attribute Details

#stateObject (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

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/opentrace/circuit_breaker.rb', line 21

def allow_request?
  @mutex.synchronize do
    case @state
    when CLOSED
      true
    when OPEN
      if Time.now - @last_failure_at >= @recovery_timeout
        @state = HALF_OPEN
        @half_open_probe_sent = true
        true
      else
        false
      end
    when HALF_OPEN
      if @half_open_probe_sent
        false
      else
        @half_open_probe_sent = true
        true
      end
    end
  end
end

#record_failureObject



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/opentrace/circuit_breaker.rb', line 53

def record_failure
  @mutex.synchronize do
    @failure_count += 1
    @last_failure_at = Time.now
    if @state == HALF_OPEN
      @half_open_probe_sent = false
      @state = OPEN
    elsif @failure_count >= @failure_threshold
      @state = OPEN
    end
  end
end

#record_successObject



45
46
47
48
49
50
51
# File 'lib/opentrace/circuit_breaker.rb', line 45

def record_success
  @mutex.synchronize do
    @failure_count = 0
    @half_open_probe_sent = false
    @state = CLOSED
  end
end

#reset!Object



66
67
68
69
70
71
72
73
# File 'lib/opentrace/circuit_breaker.rb', line 66

def reset!
  @mutex.synchronize do
    @state = CLOSED
    @failure_count = 0
    @last_failure_at = nil
    @half_open_probe_sent = false
  end
end