-
Notifications
You must be signed in to change notification settings - Fork 85
/
client_transport_stream.go
218 lines (195 loc) · 6.54 KB
/
client_transport_stream.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
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package transport
import (
"context"
"sync"
"trpc.group/trpc-go/trpc-go/codec"
"trpc.group/trpc-go/trpc-go/errs"
"trpc.group/trpc-go/trpc-go/pool/multiplexed"
)
const (
defaultMaxConcurrentStreams = 1000
defaultMaxIdleConnsPerHost = 2
)
// DefaultClientStreamTransport is the default client stream transport.
var DefaultClientStreamTransport = NewClientStreamTransport()
// NewClientStreamTransport creates a new ClientStreamTransport.
func NewClientStreamTransport(opts ...ClientStreamTransportOption) ClientStreamTransport {
options := &cstOptions{
maxConcurrentStreams: defaultMaxConcurrentStreams,
maxIdleConnsPerHost: defaultMaxIdleConnsPerHost,
}
for _, opt := range opts {
opt(options)
}
t := &clientStreamTransport{
// Map streamID to connection. On the client side, ensure that the streamID is
// incremented and unique, otherwise the map of addr must be added.
streamIDToConn: make(map[uint32]multiplexed.MuxConn),
m: &sync.RWMutex{},
multiplexedPool: multiplexed.New(
multiplexed.WithMaxVirConnsPerConn(options.maxConcurrentStreams),
multiplexed.WithMaxIdleConnsPerHost(options.maxIdleConnsPerHost),
),
}
return t
}
// cstOptions is the client stream transport options.
type cstOptions struct {
maxConcurrentStreams int
maxIdleConnsPerHost int
}
// ClientStreamTransportOption sets properties of ClientStreamTransport.
type ClientStreamTransportOption func(*cstOptions)
// WithMaxConcurrentStreams sets the maximum concurrent streams in each TCP connection.
func WithMaxConcurrentStreams(n int) ClientStreamTransportOption {
return func(opts *cstOptions) {
opts.maxConcurrentStreams = n
}
}
// WithMaxIdleConnsPerHost sets the maximum idle connections per host.
func WithMaxIdleConnsPerHost(n int) ClientStreamTransportOption {
return func(opts *cstOptions) {
opts.maxIdleConnsPerHost = n
}
}
// clientStreamTransport keeps compatibility with the original client transport.
type clientStreamTransport struct {
streamIDToConn map[uint32]multiplexed.MuxConn
m *sync.RWMutex
multiplexedPool multiplexed.Pool
}
// Init inits clientStreamTransport. It gets a connection from the multiplexing pool. A stream is
// corresponding to a virtual connection, which provides the interface for the stream.
func (c *clientStreamTransport) Init(ctx context.Context, roundTripOpts ...RoundTripOption) error {
opts, err := c.getOptions(ctx, roundTripOpts...)
if err != nil {
return err
}
// If ctx has been canceled or timeout, just return.
if ctx.Err() == context.Canceled {
return errs.NewFrameError(errs.RetClientCanceled,
"client canceled before tcp dial: "+ctx.Err().Error())
}
if ctx.Err() == context.DeadlineExceeded {
return errs.NewFrameError(errs.RetClientTimeout,
"client timeout before tcp dial: "+ctx.Err().Error())
}
msg := opts.Msg
streamID := msg.StreamID()
getOpts := multiplexed.NewGetOptions()
getOpts.WithVID(streamID)
fp, ok := opts.FramerBuilder.(multiplexed.FrameParser)
if !ok {
return errs.NewFrameError(errs.RetClientConnectFail,
"frame builder does not implement multiplexed.FrameParser")
}
getOpts.WithFrameParser(fp)
getOpts.WithDialTLS(opts.TLSCertFile, opts.TLSKeyFile, opts.CACertFile, opts.TLSServerName)
getOpts.WithLocalAddr(opts.LocalAddr)
conn, err := opts.Multiplexed.GetMuxConn(ctx, opts.Network, opts.Address, getOpts)
if err != nil {
return errs.NewFrameError(errs.RetClientConnectFail,
"tcp client transport multiplexd pool: "+err.Error())
}
msg.WithRemoteAddr(conn.RemoteAddr())
msg.WithLocalAddr(conn.LocalAddr())
c.m.Lock()
c.streamIDToConn[streamID] = conn
c.m.Unlock()
return nil
}
// Send sends stream data and provides interface for stream.
func (c *clientStreamTransport) Send(ctx context.Context, req []byte, roundTripOpts ...RoundTripOption) error {
msg := codec.Message(ctx)
streamID := msg.StreamID()
// StreamID is uniquely generated by stream client.
c.m.RLock()
cc := c.streamIDToConn[streamID]
c.m.RUnlock()
if cc == nil {
return errs.NewFrameError(errs.RetServerSystemErr, "Connection is Closed")
}
if err := cc.Write(req); err != nil {
return err
}
return nil
}
// Recv receives stream data and provides interface for stream.
func (c *clientStreamTransport) Recv(ctx context.Context, roundTripOpts ...RoundTripOption) ([]byte, error) {
cc, err := c.getConnect(ctx, roundTripOpts...)
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
if ctx.Err() == context.Canceled {
return nil, errs.NewFrameError(errs.RetClientCanceled,
"tcp client transport canceled before Write: "+ctx.Err().Error())
}
if ctx.Err() == context.DeadlineExceeded {
return nil, errs.NewFrameError(errs.RetClientTimeout,
"tcp client transport timeout before Write: "+ctx.Err().Error())
}
default:
}
return cc.Read()
}
// Close closes connections and cleans up.
func (c *clientStreamTransport) Close(ctx context.Context) {
msg := codec.Message(ctx)
streamID := msg.StreamID()
c.m.Lock()
defer c.m.Unlock()
if conn, ok := c.streamIDToConn[streamID]; ok {
conn.Close()
delete(c.streamIDToConn, streamID)
}
}
// getOptions inits RoundTripOptions and does some basic check.
func (c *clientStreamTransport) getOptions(ctx context.Context,
roundTripOpts ...RoundTripOption) (*RoundTripOptions, error) {
opts := &RoundTripOptions{
Multiplexed: c.multiplexedPool,
}
// use roundTripOpts to modify opts.
for _, o := range roundTripOpts {
o(opts)
}
if opts.Multiplexed == nil {
return nil, errs.NewFrameError(errs.RetClientConnectFail,
"tcp client transport: multiplexd pool empty")
}
if opts.FramerBuilder == nil {
return nil, errs.NewFrameError(errs.RetClientConnectFail,
"tcp client transport: framer builder empty")
}
if opts.Msg == nil {
return nil, errs.NewFrameError(errs.RetClientConnectFail,
"tcp client transport: message empty")
}
return opts, nil
}
func (c *clientStreamTransport) getConnect(ctx context.Context,
roundTripOpts ...RoundTripOption) (multiplexed.MuxConn, error) {
msg := codec.Message(ctx)
streamID := msg.StreamID()
c.m.RLock()
cc := c.streamIDToConn[streamID]
c.m.RUnlock()
if cc == nil {
return nil, errs.NewFrameError(errs.RetServerSystemErr, "Stream is not inited yet")
}
return cc, nil
}