/
circuit_state.rb
60 lines (44 loc) · 1.14 KB
/
circuit_state.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require 'aasm'
#
# CircuitState is created individually for each object, and keeps
# track of how the object is doing and whether the object's circuit
# has tripped or not.
#
class CircuitBreaker::CircuitState
include AASM
aasm.state :half_open
aasm.state :open
aasm.state :closed, :enter => :reset_failure_count
aasm.initial_state :closed
#
# Trips the circuit breaker into the open state where it will immediately fail.
#
aasm.event :trip do
transitions :to => :open, :from => [:closed, :half_open]
end
#
# Transitions from an open state to a half_open state.
#
aasm.event :attempt_reset do
transitions :to => :half_open, :from => [:open]
end
#
# Close the circuit from an open or half open state.
#
aasm.event :reset do
transitions :to => :closed, :from => [:open, :half_open]
end
def initialize()
@failure_count = 0
@last_failure_time = nil
end
attr_accessor :last_failure_time
attr_accessor :failure_count
def increment_failure_count
@failure_count = @failure_count + 1
@last_failure_time = Time.now
end
def reset_failure_count
@failure_count = 0
end
end