-
Notifications
You must be signed in to change notification settings - Fork 2
/
breaker_box.go
86 lines (74 loc) · 2.09 KB
/
breaker_box.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
package circuit
import "sync"
type BreakerBox struct {
breakers sync.Map
stateChange chan BreakerState
funnel chan BreakerState
}
// NewBreakerBox will return a BreakerBox with all internals properly configured.
// Use this function at all times when creating a new instance.
func NewBreakerBox() *BreakerBox {
stateChange := make(chan BreakerState, 5)
funnel := make(chan BreakerState)
go func(stateChange, funnel chan BreakerState) {
for {
select {
case state := <-funnel:
select {
case stateChange <- state:
default:
// no one's listening, don't block
}
}
}
}(stateChange, funnel)
return &BreakerBox{
breakers: sync.Map{},
stateChange: stateChange,
funnel: funnel,
}
}
// StateChange exposes the breaker breaker state channel of the box
func (bb *BreakerBox) StateChange() <-chan BreakerState {
return bb.stateChange
}
// Load will fetch a circuit breaker by name if it exists
func (bb *BreakerBox) Load(name string) *Breaker {
b, ok := bb.breakers.Load(name)
if !ok {
return nil
}
return b.(*Breaker)
}
// AddBYO will add a Breaker to the box, but the breaker's state changes
// will not be funneled to the box's state change output
func (bb *BreakerBox) AddBYO(b *Breaker) {
bb.breakers.Store(b.name, b)
}
// Create will generate a new circuit breaker with the supplied options and return it.
// If a breaker with the same name already exists in the box, it will be discarded.
func (bb *BreakerBox) Create(opts BreakerOptions) (*Breaker, error) {
if opts.Name == "" {
return nil, UnnamedBreakerError
}
b := NewBreaker(opts)
go func(b *Breaker, bb *BreakerBox) {
for {
select {
case state := <-b.stateChange:
bb.funnel <- state
}
}
}(b, bb)
bb.breakers.Store(b.name, b)
return b, nil
}
// LoadOrCreate will attempt to load a circuit breaker by name. If the breaker doesnt exist, a
// new one with the supplied options will be created and returned.
func (bb *BreakerBox) LoadOrCreate(opts BreakerOptions) (*Breaker, error) {
b, ok := bb.breakers.Load(opts.Name)
if ok {
return b.(*Breaker), nil
}
return bb.Create(opts)
}