-
Notifications
You must be signed in to change notification settings - Fork 33
/
connection_retry_pool.go
144 lines (116 loc) · 2.34 KB
/
connection_retry_pool.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package pep
import (
"sync"
"sync/atomic"
"time"
)
const (
crpIdle uint32 = iota
crpWorking
crpFull
crpStopping
)
type connRetryPool struct {
timeout time.Duration
state *uint32
ch chan *streamConn
count *uint32
c *sync.Cond
m *sync.RWMutex
}
func newConnRetryPool(conns []*streamConn, timeout time.Duration) *connRetryPool {
state := crpIdle
ch := make(chan *streamConn, len(conns))
for _, c := range conns {
ch <- c
}
count := uint32(len(conns))
return &connRetryPool{
timeout: timeout,
state: &state,
ch: ch,
count: &count,
c: sync.NewCond(new(sync.Mutex)),
m: new(sync.RWMutex),
}
}
func (p *connRetryPool) tryStart() {
if atomic.CompareAndSwapUint32(p.state, crpIdle, crpFull) {
go p.worker(p.ch)
}
}
func (p *connRetryPool) stop() {
atomic.StoreUint32(p.state, crpStopping)
p.c.Broadcast()
p.m.Lock()
defer p.m.Unlock()
close(p.ch)
p.ch = nil
}
func (p *connRetryPool) check() bool {
return atomic.LoadUint32(p.state) == crpWorking
}
func (p *connRetryPool) wait() bool {
state := atomic.LoadUint32(p.state)
if p.timeout < 0 {
p.c.L.Lock()
defer p.c.L.Unlock()
for state != crpWorking && state != crpStopping {
p.c.Wait()
state = atomic.LoadUint32(p.state)
}
} else if p.timeout > 0 {
sch := make(chan bool)
done := make(chan bool)
defer close(done)
go func(state uint32) {
p.c.L.Lock()
defer func() {
p.c.L.Unlock()
close(sch)
}()
for state != crpWorking && state != crpStopping {
p.c.Wait()
select {
default:
case <-done:
break
}
state = atomic.LoadUint32(p.state)
}
}(state)
select {
case <-time.After(p.timeout):
case <-sch:
}
state = atomic.LoadUint32(p.state)
}
return state == crpWorking
}
func (p *connRetryPool) put(c *streamConn) {
if c.markDisconnected() {
p.m.RLock()
defer p.m.RUnlock()
if p.ch == nil {
return
}
if atomic.AddUint32(p.count, 1) == uint32(cap(p.ch)) {
atomic.CompareAndSwapUint32(p.state, crpWorking, crpFull)
}
p.ch <- c
}
}
func (p *connRetryPool) worker(ch chan *streamConn) {
for c := range ch {
go p.reconnect(c)
}
}
func (p *connRetryPool) reconnect(c *streamConn) {
if err := c.connect(); err != nil {
return
}
atomic.AddUint32(p.count, ^uint32(0))
if atomic.CompareAndSwapUint32(p.state, crpFull, crpWorking) {
p.c.Broadcast()
}
}