Fix time processing, more docs
Evan Huus
9 years ago
25 | 25 | lock sync.RWMutex |
26 | 26 | state state |
27 | 27 | errors, successes int |
28 | lastError time.Time | |
28 | 29 | } |
29 | 30 | |
30 | // New constructs a new circuit-breaker. | |
31 | // New constructs a new circuit-breaker that starts closed. | |
32 | // From closed, the breaker opens if "errorThreshold" errors are seen | |
33 | // without an error-free period of at least "timeout". From open, the | |
34 | // breaker half-closes after "timeout". From half-open, the breaker closes | |
35 | // after "successThreshold" consecutive successes, or opens on a single error. | |
31 | 36 | func New(errorThreshold, successThreshold int, timeout time.Duration) *Breaker { |
32 | 37 | return &Breaker{ |
33 | 38 | errorThreshold: errorThreshold, |
38 | 43 | |
39 | 44 | // Run will either return BreakerOpen immediately if the circuit-breaker is |
40 | 45 | // already open, or it will run the given function and pass along its return |
41 | // value. | |
46 | // value. It is safe to call Run concurrently on the same Breaker. | |
42 | 47 | func (b *Breaker) Run(x func() error) error { |
43 | 48 | b.lock.RLock() |
44 | 49 | state := b.state |
57 | 62 | return x() |
58 | 63 | }() |
59 | 64 | |
65 | b.processResult(result, panicValue) | |
66 | ||
67 | if panicValue != nil { | |
68 | // as close as Go lets us come to a "rethrow" although unfortunately | |
69 | // we lose the original panicing location | |
70 | panic(panicValue) | |
71 | } | |
72 | ||
73 | return result | |
74 | } | |
75 | ||
76 | func (b *Breaker) processResult(result error, panicValue interface{}) { | |
60 | 77 | b.lock.Lock() |
61 | 78 | defer b.lock.Unlock() |
62 | 79 | |
68 | 85 | } |
69 | 86 | } |
70 | 87 | } else { |
88 | if b.errors > 0 { | |
89 | expiry := b.lastError //time.Add mutates, so take a copy | |
90 | expiry.Add(b.timeout) | |
91 | if time.Now().After(expiry) { | |
92 | b.errors = 0 | |
93 | } | |
94 | } | |
95 | ||
71 | 96 | switch b.state { |
72 | 97 | case closed: |
73 | 98 | b.errors++ |
74 | 99 | if b.errors == b.errorThreshold { |
75 | 100 | b.openBreaker() |
101 | } else { | |
102 | b.lastError = time.Now() | |
76 | 103 | } |
77 | 104 | case halfOpen: |
78 | 105 | b.openBreaker() |
79 | 106 | } |
80 | 107 | } |
81 | ||
82 | if panicValue != nil { | |
83 | // as close as Go lets us come to a "rethrow" although unfortunately | |
84 | // we lose the original panicing location | |
85 | panic(panicValue) | |
86 | } | |
87 | ||
88 | return result | |
89 | 108 | } |
90 | 109 | |
91 | 110 | func (b *Breaker) openBreaker() { |