-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclipper_cb.go
110 lines (89 loc) · 1.57 KB
/
clipper_cb.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package clipper
import (
"fmt"
"log"
"sync"
"time"
)
const maxFailures = 5
const defaultTimeout = 10
type Status int
type Clipper struct {
Name string
Failures int64
open bool
openedAt int64
statistics circuitStats
mutex *sync.Mutex
}
var clippers map[string]*Clipper
func newClipper(c *Configs) *Clipper {
if clippers == nil {
clippers = make(map[string]*Clipper)
}
return &Clipper{
Name: c.Name,
mutex: &sync.Mutex{},
}
}
type Configs struct {
Name string
MaxDurationInSec int
}
func setClipper(cfg *Configs) *Clipper {
c := newClipper(cfg)
clippers[cfg.Name] = c
return c
}
func getClipperWithName(name string) *Clipper {
if name == "" {
return nil
}
cb, _ok := clippers[name]
if !_ok {
return nil
}
return cb
}
func getClipper(cfg *Configs) *Clipper {
if cfg == nil {
randName := randStr()
log.Println("empty config with name: " + randName)
log.Println(fmt.Sprintf("default timeout: %d", defaultTimeout))
cfg = &Configs{
Name: randName,
MaxDurationInSec: defaultTimeout,
}
}
cb, _ok := clippers[cfg.Name]
if !_ok {
return setClipper(cfg)
}
return cb
}
func (c *Clipper) update(err error) {
if err != nil {
c.Failures++
if c.Failures >= maxFailures {
c.open = true
c.openedAt = time.Now().Unix()
c.statistics.numOfOpenings++
return
}
}
c.open = false
c.Failures = 0
}
func (c *Clipper) isOpen() bool {
if c.open {
now := time.Now().Unix()
// 3 minutes
if (now - c.openedAt) > 180 {
c.open = false
return false
} else {
return true
}
}
return false
}