-
Notifications
You must be signed in to change notification settings - Fork 565
/
dialer.go
69 lines (63 loc) · 1.5 KB
/
dialer.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
package grpcutil
import (
"fmt"
"sync"
"google.golang.org/grpc"
)
type dialer struct {
opts []grpc.DialOption
// TODO: this is insane for so many reasons
addressToClientConn map[string]*grpc.ClientConn
lock *sync.RWMutex
}
func newDialer(opts ...grpc.DialOption) *dialer {
return &dialer{opts, make(map[string]*grpc.ClientConn), &sync.RWMutex{}}
}
func (d *dialer) Dial(address string) (*grpc.ClientConn, error) {
d.lock.RLock()
clientConn, ok := d.addressToClientConn[address]
d.lock.RUnlock()
if ok && clientConn != nil {
state, err := clientConn.State()
if err != nil {
return nil, err
}
if state != grpc.Shutdown {
return clientConn, nil
}
}
newClientConn, err := grpc.Dial(address, d.opts...)
if err != nil {
return nil, err
}
d.lock.Lock()
defer d.lock.Unlock()
clientConn, ok = d.addressToClientConn[address]
if ok && clientConn != nil {
state, err := clientConn.State()
if err != nil {
return nil, err
}
if state != grpc.Shutdown {
_ = newClientConn.Close()
return clientConn, nil
}
}
d.addressToClientConn[address] = newClientConn
return newClientConn, nil
}
func (d *dialer) Clean() error {
d.lock.Lock()
defer d.lock.Unlock()
var errs []error
for _, clientConn := range d.addressToClientConn {
if err := clientConn.Close(); err != nil && err != grpc.ErrClientConnClosing {
errs = append(errs, err)
}
}
d.addressToClientConn = make(map[string]*grpc.ClientConn)
if len(errs) > 0 {
return fmt.Errorf("%v", errs)
}
return nil
}