Class: Hiatus::CircuitBreaker

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

Constant Summary collapse

DEFAUTS =
{
  threshold: 5,
  half_open_interval: 5
}
DEFAULT_THRESHOLD =
CountThreshold.new DEFAUTS[:threshold]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(threshold: nil, half_open_interval: nil) ⇒ CircuitBreaker

Returns a new instance of CircuitBreaker.



15
16
17
18
19
20
# File 'lib/hiatus/circuit_breaker.rb', line 15

def initialize(threshold: nil, half_open_interval: nil)
  @threshold = threshold || DEFAULT_THRESHOLD
  @half_open_interval = half_open_interval || DEFAUTS[:half_open_interval]

  @state = :closed
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



13
14
15
# File 'lib/hiatus/circuit_breaker.rb', line 13

def state
  @state
end

Instance Method Details

#call_with_circuit_state_changesObject



34
35
36
37
38
39
# File 'lib/hiatus/circuit_breaker.rb', line 34

def call_with_circuit_state_changes
  @threshold.touch
  yield if block_given?
  @threshold.reset if half_open?
  close
end

#closeObject



62
63
64
65
# File 'lib/hiatus/circuit_breaker.rb', line 62

def close
  @state = :closed
  last_failure_timestamp = nil
end

#closed?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/hiatus/circuit_breaker.rb', line 58

def closed?
  state == :closed
end

#half_open?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/hiatus/circuit_breaker.rb', line 67

def half_open?
  open? && reached_retrial_threshold?
end

#increment_failure_countObject



46
# File 'lib/hiatus/circuit_breaker.rb', line 46

def increment_failure_count; @threshold.increment; end

#increment_failure_count_and_trip_if_threshold_exceededObject



41
42
43
44
# File 'lib/hiatus/circuit_breaker.rb', line 41

def increment_failure_count_and_trip_if_threshold_exceeded
  increment_failure_count
  trip_if_threshold_exceeded
end

#open?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/hiatus/circuit_breaker.rb', line 54

def open?
  state == :open
end

#run(&block) ⇒ Object

Raises:



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/hiatus/circuit_breaker.rb', line 22

def run &block

  raise CircuitBrokenError if open? && !reached_retrial_threshold?

  begin
    call_with_circuit_state_changes &block
  rescue => e
    increment_failure_count_and_trip_if_threshold_exceeded
    raise $!
  end
end

#trip_if_threshold_exceededObject



48
49
50
51
52
# File 'lib/hiatus/circuit_breaker.rb', line 48

def trip_if_threshold_exceeded
  @state = :open if @threshold.reached?

  refresh_last_failure_timestamp
end