-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.go
65 lines (52 loc) · 1.24 KB
/
controller.go
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
60
61
62
63
64
65
package formigo
import (
"context"
"errors"
"sync"
"time"
)
type controller struct {
errorConfig ErrorConfiguration
errorCounter int
mutex sync.Mutex
stopOnce sync.Once
stopFunc context.CancelCauseFunc
}
// Decrease counter after the timeout period specified in the errorConfig of
// the controller.
func (c *controller) decreaseCounterAfterTimeout() {
time.Sleep(c.errorConfig.Period)
c.mutex.Lock()
defer c.mutex.Unlock()
c.errorCounter--
}
// Increases the counter
func (c *controller) increaseCounter() {
// Increase counter
c.mutex.Lock()
defer c.mutex.Unlock()
c.errorCounter++
}
func (c *controller) shouldStop() bool {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.errorCounter > c.errorConfig.Threshold
}
func (c *controller) reportError(err error) {
if shouldIncreaseCounter := c.errorConfig.ReportFunc(err); !shouldIncreaseCounter {
return
}
c.increaseCounter()
go c.decreaseCounterAfterTimeout()
if c.shouldStop() {
c.stopOnce.Do(func() {
c.stopFunc(errors.New("too many errors within the given period"))
})
}
}
func newController(errorConfig ErrorConfiguration, stopFunc context.CancelCauseFunc) *controller {
return &controller{
errorConfig: errorConfig,
stopFunc: stopFunc,
}
}