-
Notifications
You must be signed in to change notification settings - Fork 795
/
short_pool.go
101 lines (86 loc) · 2.51 KB
/
short_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
/*
* Copyright 2021 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 connpool
import (
"context"
"fmt"
"net"
"github.com/cloudwego/kitex/pkg/remote"
"github.com/cloudwego/kitex/pkg/utils"
)
var _ remote.ConnPool = &ShortPool{}
type shortConn struct {
net.Conn
closed bool
}
// Close closes the connection.
func (sc *shortConn) Close() error {
if !sc.closed {
sc.closed = true
return sc.Conn.Close()
}
return nil
}
// RawConn returns the underlying net.Conn.
func (sc *shortConn) RawConn() net.Conn {
if sc.closed {
return nil
}
return sc.Conn
}
// ShortPool is the conn pool for short connections.
type ShortPool struct {
serviceName string
reporter Reporter
}
// NewShortPool timeout is connection timeout.
func NewShortPool(serviceName string) *ShortPool {
return &ShortPool{
serviceName: serviceName,
reporter: &DummyReporter{},
}
}
// Get return a PoolConn instance which implement net.Conn interface.
func (p *ShortPool) Get(ctx context.Context, network, address string, opt remote.ConnOption) (net.Conn, error) {
conn, err := opt.Dialer.DialTimeout(network, address, opt.ConnectTimeout)
addr := utils.NewNetAddr(network, address)
if err != nil {
p.reporter.ConnFailed(Short, p.serviceName, addr)
return nil, fmt.Errorf("dial connection err: %s, addr: %s", err, addr)
}
p.reporter.ConnSucceed(Short, p.serviceName, addr)
return &shortConn{Conn: conn}, nil
}
func (p *ShortPool) release(conn net.Conn) error {
return conn.Close()
}
// Put implements the ConnPool interface.
func (p *ShortPool) Put(conn net.Conn) error {
return p.release(conn)
}
// Discard implements the ConnPool interface.
func (p *ShortPool) Discard(conn net.Conn) error {
return p.release(conn)
}
// Close is to release resource of ConnPool, it is executed when client is closed.
// ShortPool do nothing
func (p *ShortPool) Close() error {
return nil
}
// EnableReporter enable reporter for short connection pool.
func (p *ShortPool) EnableReporter() {
p.reporter = GetCommonReporter()
}