forked from aws/aws-dax-go
/
tubepool.go
305 lines (266 loc) · 5.67 KB
/
tubepool.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
package client
import (
"context"
"net"
"os"
"sync"
"time"
)
const network = "tcp"
type tubePool struct {
address string
gate gate
errCh chan error
timeout time.Duration
connectFn func(string, string) (net.Conn, error)
closeTubeImmediately bool
mutex sync.Mutex
closed bool // protected by mutex
top *tube // protected by mutex
lastActive *tube // protected by mutex
waiters chan *tube
}
type tubePoolOptions struct {
maxConcurrentConnAttempts int
timeout time.Duration
}
var defaultTubePoolOptions = tubePoolOptions{10, time.Second * 5}
func newTubePool(address string) *tubePool {
return newTubePoolWithOptions(address, defaultTubePoolOptions)
}
func newTubePoolWithOptions(a string, options tubePoolOptions) *tubePool {
if options.maxConcurrentConnAttempts <= 0 {
options.maxConcurrentConnAttempts = defaultTubePoolOptions.maxConcurrentConnAttempts
}
pool := tubePool{
address: a,
gate: make(gate, options.maxConcurrentConnAttempts),
errCh: make(chan error),
waiters: make(chan *tube),
timeout: options.timeout,
connectFn: connect,
}
return &pool
}
func (p *tubePool) get() (*tube, error) {
ctx := context.Background()
if p.timeout > 0 {
var cancelFn func()
ctx, cancelFn = context.WithTimeout(ctx, p.timeout)
defer cancelFn()
}
return p.getWithContext(ctx, false)
}
func (p *tubePool) getWithContext(ctx context.Context, highPriority bool) (*tube, error) {
for {
p.mutex.Lock()
if p.closed {
p.mutex.Unlock()
return nil, os.ErrClosed
}
// look for idle tubes in stack
if p.top != nil {
tube := p.top
p.top = tube.next
if p.lastActive == tube {
p.lastActive = p.top
}
tube.next = nil
p.mutex.Unlock()
return tube, nil
}
// no tubes in stack, create wait channel
if p.waiters == nil {
p.waiters = make(chan *tube)
}
waitCh := p.waiters
p.mutex.Unlock()
var done chan *tube
if highPriority {
done = make(chan *tube)
}
if p.gate.tryEnter() {
go p.allocAndReleaseGate(done, true)
} else if highPriority {
go p.allocAndReleaseGate(done, false)
}
select {
case tube := <-waitCh:
if tube != nil {
return tube, nil
}
// if channel is closed, continue to look for idle tubes in stack
case tube := <-done:
if tube != nil {
return tube, nil
}
case err := <-p.errCh:
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (p *tubePool) allocAndReleaseGate(done chan *tube, releaseGate bool) {
tube, err := p.alloc()
if releaseGate {
p.gate.exit()
}
if err == nil {
select {
case done <- tube:
default:
p.put(tube)
}
} else {
p.mutex.Lock()
cls := p.closed
p.mutex.Unlock()
if !cls {
select {
case p.errCh <- err:
default:
}
}
}
if done != nil {
close(done)
}
}
func (p *tubePool) put(tube *tube) {
if tube == nil {
return
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.closed {
tube.Close()
}
if p.waiters != nil {
select {
case p.waiters <- tube:
return
default:
close(p.waiters) // unblock future waiters
p.waiters = nil
}
}
tube.next = p.top
p.top = tube
return
}
func (p *tubePool) discard(tube *tube) {
if tube == nil {
return
}
if p.closeTubeImmediately {
tube.Close()
return
}
go func() {
tube.Close()
}()
}
func (p *tubePool) setDeadline(tube *tube, ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
var deadline time.Time
if d, ok := ctx.Deadline(); ok {
deadline = d
}
return tube.setDeadline(deadline)
}
func (p *tubePool) Close() error {
p.mutex.Lock()
defer p.mutex.Unlock()
p.closed = true
t := p.top
for t != nil {
t.Close()
t = t.next
}
p.top = nil
p.lastActive = nil
if p.waiters != nil {
close(p.waiters)
p.waiters = nil
}
close(p.errCh)
// cannot close(p.gate) as send on closed channel will panic. new connections will be closed immediately.
return nil
}
func (p *tubePool) reapIdleConnections() {
p.mutex.Lock()
if p.closed {
p.mutex.Unlock()
return
}
var reapHead *tube
if p.lastActive != nil {
reapHead = p.lastActive.next
p.lastActive.next = nil
}
p.lastActive = p.top
p.mutex.Unlock()
// closing tubes synchronously as this method is expected to be called from a background goroutine
p.closeAll(reapHead)
}
func (p *tubePool) alloc() (*tube, error) {
conn, err := p.connectFn(network, p.address)
if err != nil {
return nil, err
}
tube, err := newTube(conn)
if err != nil {
return nil, err
}
if err = tube.init(); err != nil {
tube.Close()
return nil, err
}
return tube, nil
}
func (p *tubePool) closeAll(head *tube) {
var next *tube
for head != nil {
next = head.next
head.next = nil
head.Close()
head = next
}
}
type gate chan struct{}
func (g gate) tryEnter() bool {
select {
case g <- struct{}{}:
return true
default:
return false
}
}
func (g gate) exit() {
select { // do not block
case <-g:
default:
}
}
func connect(network, address string) (net.Conn, error) {
return net.Dial(network, address)
}
type connectionReaper interface {
reapIdleConnections()
}