-
Notifications
You must be signed in to change notification settings - Fork 16
/
client.go
2595 lines (2318 loc) · 68.2 KB
/
client.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2022 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.
*
* Copyright 2017 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package http2
import (
"bufio"
"bytes"
"container/list"
"context"
"crypto/rand"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/cloudwego/hertz/pkg/app/client/retry"
"github.com/cloudwego/hertz/pkg/common/bytebufferpool"
"github.com/cloudwego/hertz/pkg/common/compress"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/network"
"github.com/cloudwego/hertz/pkg/network/dialer"
"github.com/cloudwego/hertz/pkg/protocol"
"github.com/cloudwego/hertz/pkg/protocol/client"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/hertz-contrib/http2/config"
"github.com/hertz-contrib/http2/hpack"
"github.com/hertz-contrib/http2/internal/bytesconv"
"github.com/hertz-contrib/http2/internal/bytestr"
"github.com/hertz-contrib/http2/internal/nocopy"
"golang.org/x/net/http/httpguts"
)
const (
// transportDefaultConnFlow is how many connection-level flow control
// tokens we give the server at start-up, past the default 64k.
transportDefaultConnFlow = 1 << 30
// transportDefaultStreamFlow is how many stream-level flow
// control tokens we announce to the peer, and how many bytes
// we buffer per stream.
transportDefaultStreamFlow = 4 << 20
// transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
// a stream-level WINDOW_UPDATE for at a time.
transportDefaultStreamMinRefresh = 4 << 10
// initialMaxConcurrentStreams is a connections maxConcurrentStreams until
// it's received servers initial SETTINGS frame, which corresponds with the
// spec's minimum recommended value.
initialMaxConcurrentStreams = 100
// defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
// if the server doesn't include one in its initial SETTINGS frame.
defaultMaxConcurrentStreams = 1000
)
var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
type missingBody struct{}
func (missingBody) Close() error { return nil }
func (missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
// HostClient balances http requests among hosts listed in Addr.
//
// HostClient may be used for balancing load among multiple upstream hosts.
// While multiple addresses passed to HostClient.Addr may be used for balancing
// load among them, it would be better using LBClient instead, since HostClient
// may unevenly balance load among upstream hosts.
//
// It is forbidden copying HostClient instances. Create new instances instead.
//
// It is safe calling HostClient methods from concurrently running goroutines.
type HostClient struct {
noCopy nocopy.NoCopy //lint:ignore U1000 until noCopy is used
*config.ClientConfig
// Comma-separated list of upstream HTTP server host addresses,
// which are passed to Dial in a round-robin manner.
//
// Each address may contain port if default dialer is used.
// For example,
//
// - foobar.com:80
// - foobar.com:443
// - foobar.com:8080
Addr string
IsTLS bool
lck sync.Mutex
conns list.List
addrsLock sync.Mutex
addrs []string
addrIdx uint32
tlsConfigMap map[string]*tls.Config
tlsConfigMapLock sync.Mutex
}
func (hc *HostClient) SetDynamicConfig(dc *client.DynamicConfig) {
hc.Addr = dc.Addr
hc.IsTLS = dc.IsTLS
}
// Get returns the status code and body of url.
//
// The contents of dst will be replaced by the body and returned, if the dst
// is too small a new slice will be allocated.
//
// The function follows redirects. Use Do* for manually handling redirects.
func (hc *HostClient) Get(ctx context.Context, dst []byte, url string) (statusCode int, body []byte, err error) {
return client.GetURL(ctx, dst, url, hc)
}
func canRetryError(err error) bool {
if err == errClientConnUnusable || err == errClientConnGotGoAway {
return true
}
if se, ok := err.(StreamError); ok {
if se.Code == ErrCodeProtocol && se.Cause == errFromPeer {
// See golang/go#47635, golang/go#42777
return true
}
return se.Code == ErrCodeRefusedStream
}
return false
}
func defaultRetryIf(req *protocol.Request, resp *protocol.Response, err error) bool {
if !canRetryError(err) {
return false
}
// If the Body is nil (or http.NoBody), it's safe to reuse
// this request and its Body.
if req.BodyStream() == protocol.NoBody && len(req.Body()) == 0 {
return true
}
// The Request.Body can't reset back to the beginning, but we
// don't seem to have started to read from it yet, so reuse
// the request directly.
if err == errClientConnUnusable {
return true
}
return false
}
func (hc *HostClient) Do(ctx context.Context, req *protocol.Request, rsp *protocol.Response) error {
if !bytes.Equal(req.URI().Scheme(), bytestr.StrHTTPS) && !hc.AllowHTTP {
return errors.New("http2: unsupported scheme")
}
var (
err error
attempts uint = 0
maxAttempts uint = 1
isRequestRetryable client.RetryIfFunc = defaultRetryIf
)
retryCfg := hc.ClientConfig.RetryConfig
if retryCfg != nil {
maxAttempts = retryCfg.MaxAttemptTimes
}
if hc.ClientConfig.RetryIf != nil {
isRequestRetryable = hc.ClientConfig.RetryIf
}
for {
var cc *clientConn
cc, err = hc.acquireConn()
if err != nil {
hlog.SystemLogger().Errorf("HTTP2: transport failed to get client conn for %s: %v", hc.Addr, err)
return err
}
err = cc.RoundTrip(ctx, req, rsp)
if err == nil {
return nil
}
attempts++
if attempts >= maxAttempts {
break
}
// Check whether this request should be retried
if !isRequestRetryable(req, rsp, err) {
break
}
wait := retry.Delay(attempts, err, retryCfg)
// Retry after wait time
time.Sleep(wait)
}
return err
}
func (cc *clientConn) RoundTrip(ctx context.Context, req *protocol.Request, rsp *protocol.Response) error {
cs := &clientStream{
cc: cc,
ctx: ctx,
isHead: bytes.Equal(req.Method(), bytestr.StrHead),
reqBodyContentLength: actualContentLength(req),
reqBody: req.BodyStream(),
peerClosed: make(chan struct{}),
abort: make(chan struct{}),
respHeaderRecv: make(chan struct{}),
donec: make(chan struct{}),
res: rsp,
}
if cs.reqBody == protocol.NoBody && len(req.Body()) > 0 {
cs.reqBody = bytes.NewReader(req.Body())
}
go cs.doRequest(req)
waitDone := func() error {
select {
case <-cs.donec:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
handleResponseHeaders := func() error {
res := cs.res
res.Header.SetProtocol(consts.HTTP20)
if res.StatusCode() > 299 {
// On error or status code 3xx, 4xx, 5xx, etc abort any
// ongoing write, assuming that the server doesn't care
// about our request body. If the server replied with 1xx or
// 2xx, however, then assume the server DOES potentially
// want our body (e.g. full-duplex streaming:
// golang.org/issue/13444). If it turns out the server
// doesn't, they'll RST_STREAM us soon enough. This is a
// heuristic to avoid adding knobs to Transport. Hopefully
// we can keep it.
cs.abortRequestBodyWrite()
}
if res.BodyStream() == noBody && actualContentLength(req) == 0 {
// If there isn't a request or response body still being
// written, then wait for the stream to be closed before
// RoundTrip returns.
if err := waitDone(); err != nil {
return err
}
}
return nil
}
for {
select {
case <-cs.respHeaderRecv:
return handleResponseHeaders()
case <-cs.abort:
select {
case <-cs.respHeaderRecv:
// If both cs.respHeaderRecv and cs.abort are signaling,
// pick respHeaderRecv. The server probably wrote the
// response and immediately reset the stream.
// golang.org/issue/49645
return handleResponseHeaders()
default:
waitDone()
return cs.abortErr
}
case <-ctx.Done():
err := ctx.Err()
cs.abortStream(err)
return err
}
}
}
func (hc *HostClient) onConnectionDropped(c *clientConn) {
hc.lck.Lock()
defer hc.lck.Unlock()
for e := hc.conns.Front(); e != nil; e = e.Next() {
if e.Value.(*clientConn) == c {
hc.conns.Remove(e)
break
}
}
}
func (hc *HostClient) createConn() (*clientConn, *list.Element, error) {
conn, err := hc.dialHostHard()
if hc.ReadTimeout != 0 {
conn.SetReadTimeout(hc.ReadTimeout)
}
if hc.WriteTimeout != 0 {
conn.SetWriteTimeout(hc.WriteTimeout)
}
if err != nil {
return nil, nil, err
}
c, err := hc.newClientConn(conn, false)
if err != nil {
return nil, nil, err
}
return c, hc.conns.PushFront(c), nil
}
func (hc *HostClient) acquireConn() (*clientConn, error) {
var c *clientConn
var err error
hc.lck.Lock()
defer hc.lck.Unlock()
var next *list.Element
for e := hc.conns.Front(); c == nil; e = next {
if e != nil {
c = e.Value.(*clientConn)
} else {
c, e, err = hc.createConn()
if err != nil {
return nil, err
}
}
if !c.ReserveNewRequest() {
c = nil
next = e.Next()
}
if c != nil && c.closed {
next = e.Next()
hc.conns.Remove(e)
c = nil
}
}
return c, nil
}
func (hc *HostClient) dialHostHard() (conn network.Conn, err error) {
hc.addrsLock.Lock()
n := len(hc.addrs)
hc.addrsLock.Unlock()
if n == 0 {
// It looks like c.addrs isn't initialized yet.
n = 1
}
timeout := hc.DialTimeout
deadline := time.Now().Add(timeout)
for n > 0 {
addr := hc.nextAddr()
tlsConfig := hc.cachedTLSConfig(addr)
conn, err = dialAddr(addr, hc.Dialer, tlsConfig, timeout, hc.IsTLS)
if err == nil {
return conn, nil
}
if time.Since(deadline) >= 0 {
break
}
n--
}
return nil, err
}
func dialAddr(addr string, dial network.Dialer, tlsConfig *tls.Config, timeout time.Duration, isTLS bool) (network.Conn, error) {
var conn network.Conn
var err error
if dial == nil {
hlog.SystemLogger().Warnf("HTTP2: no dialer specified, trying to use default dialer")
dial = dialer.DefaultDialer()
}
conn, err = dial.DialConnection("tcp", addr, timeout, tlsConfig)
if err != nil {
return nil, err
}
if conn == nil {
panic("HERTZ: dial.DialConnection returned (nil, nil)")
}
if dial == nil && isTLS {
p, ok := reflect.ValueOf(conn).Interface().(network.ConnTLSer)
if !ok {
return nil, fmt.Errorf("http2: unexpected connection %p; want TLSConn", p)
}
err = p.Handshake()
if err != nil {
return nil, err
}
if p.ConnectionState().NegotiatedProtocol != NextProtoTLS {
return nil, fmt.Errorf("http2: unexpected ALPN protocol %p; want %q", p, NextProtoTLS)
}
}
return conn, nil
}
func (hc *HostClient) cachedTLSConfig(addr string) *tls.Config {
if !hc.IsTLS {
return nil
}
cfgAddr := addr
hc.tlsConfigMapLock.Lock()
if hc.tlsConfigMap == nil {
hc.tlsConfigMap = make(map[string]*tls.Config)
}
cfg := hc.tlsConfigMap[cfgAddr]
if cfg == nil {
cfg = newClientTLSConfig(hc.TLSConfig, cfgAddr)
hc.tlsConfigMap[cfgAddr] = cfg
}
hc.tlsConfigMapLock.Unlock()
return cfg
}
func (hc *HostClient) CloseIdleConnections() {
hc.lck.Lock()
defer hc.lck.Unlock()
for e := hc.conns.Front(); e != nil; e = e.Next() {
c := e.Value.(*clientConn)
c.closeIfIdle()
}
}
func (hc *HostClient) ShouldRemove() bool {
return hc.ConnectionCount() == 0
}
func (hc *HostClient) ConnectionCount() int {
hc.lck.Lock()
defer hc.lck.Unlock()
return hc.conns.Len()
}
func strSliceContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}
func newClientTLSConfig(c *tls.Config, addr string) *tls.Config {
if c == nil {
c = &tls.Config{
MinVersion: tls.VersionTLS12,
}
} else {
c = c.Clone()
}
if len(c.ServerName) == 0 {
serverName := tlsServerName(addr)
if serverName == "*" {
c.InsecureSkipVerify = true
} else {
c.ServerName = serverName
}
}
if !strSliceContains(c.NextProtos, NextProtoTLS) {
c.NextProtos = append([]string{NextProtoTLS}, c.NextProtos...)
}
return c
}
func tlsServerName(addr string) string {
if !strings.Contains(addr, ":") {
return addr
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return "*"
}
return host
}
func (hc *HostClient) nextAddr() string {
hc.addrsLock.Lock()
if hc.addrs == nil {
hc.addrs = strings.Split(hc.Addr, ",")
}
addr := hc.addrs[0]
if len(hc.addrs) > 1 {
addr = hc.addrs[hc.addrIdx%uint32(len(hc.addrs))]
hc.addrIdx++
}
hc.addrsLock.Unlock()
return addr
}
func (hc *HostClient) newClientConn(c network.Conn, singleUse bool) (*clientConn, error) {
cc := &clientConn{}
cc.tconn = c
cc.createdTime = time.Now()
cc.readerDone = make(chan struct{})
cc.nextStreamID = 1
cc.maxFrameSize = 16 << 10 // spec default
cc.initialWindowSize = 65535 // spec default
cc.maxConcurrentStreams = initialMaxConcurrentStreams // "infinite", per spec. Use a smaller value until we have received server settings.
cc.peerMaxHeaderListSize = 0xffffffffffffffff // "infinite", per spec. Use 2^64-1 instead.
cc.streams = make(map[uint32]*clientStream)
cc.singleUse = singleUse
cc.wantSettingsAck = true
cc.pings = make(map[[8]byte]chan struct{})
cc.reqHeaderMu = make(chan struct{}, 1)
cc.hc = hc
if d := hc.MaxIdleConnDuration; d != 0 {
cc.idleTimeout = d
cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
}
if VerboseLogs {
hlog.SystemLogger().Infof("HTTP2: host client creating client conn %p to %v", cc, c.RemoteAddr())
}
cc.cond = sync.NewCond(&cc.mu)
cc.flow.add(int32(initialWindowSize))
// TODO: adjust this writer size to account for frame size +
// MTU + crypto/tls record padding.
cc.bw = bufio.NewWriter(stickyErrWriter{
conn: c,
timeout: hc.WriteByteTimeout,
err: &cc.werr,
})
cc.br = bufio.NewReader(c)
cc.fr = NewFramer(cc.bw, c)
cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
cc.fr.MaxHeaderListSize = hc.MaxHeaderListSize
// TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
// henc in response to SETTINGS frames?
cc.henc = hpack.NewEncoder(&cc.hbuf)
if hc.AllowHTTP {
cc.nextStreamID = 3
}
initialSettings := []Setting{
{ID: SettingEnablePush, Val: 0},
{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
}
if max := hc.MaxHeaderListSize; max != 0 {
initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
}
cc.bw.Write(clientPreface)
cc.fr.WriteSettings(initialSettings...)
cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
cc.bw.Flush()
if cc.werr != nil {
cc.Close()
return nil, cc.werr
}
go cc.readLoop()
return cc, nil
}
// clientConn is the state of a single HTTP/2 client connection to an
// HTTP/2 server.
type clientConn struct {
tconn network.Conn
hc *HostClient
// readLoop goroutine fields:
readerDone chan struct{} // closed on error
readerErr error // set before readerDone is closed
idleTimeout time.Duration // or 0 for never
idleTimer *time.Timer
mu sync.Mutex // guards following
cond *sync.Cond // hold mu; broadcast on flow/closed changes
flow flow // our conn-level flow control quota (cs.flow is per stream)
inflow flow // peer's conn-level flow control
doNotReuse bool // whether conn is marked to not be reused for any future requests
closing bool
closed bool
seenSettings bool // true if we've seen a settings frame, false otherwise
wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
goAwayDebug string // goAway frame's debug data, retained as a string
streams map[uint32]*clientStream // client-initiated
streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip
nextStreamID uint32
pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
pings map[[8]byte]chan struct{} // in flight ping data to notification channel
br *bufio.Reader
lastActive time.Time
lastIdle time.Time // time last idle
createdTime time.Time
// Settings from peer: (also guarded by wmu)
maxFrameSize uint32
maxConcurrentStreams uint32
peerMaxHeaderListSize uint64
initialWindowSize uint32
// reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
// Write to reqHeaderMu to lock it, read from it to unlock.
// Lock reqmu BEFORE mu or wmu.
reqHeaderMu chan struct{}
// wmu is held while writing.
// Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
// Only acquire both at the same time when changing peer settings.
wmu sync.Mutex
bw *bufio.Writer
fr *Framer
werr error // first write error that has occurred
hbuf bytes.Buffer // HPACK encoder writes into this
henc *hpack.Encoder
singleUse bool
// PingTimeout is the timeout after which the connection will be closed
// if a response to Ping is not received.
// Defaults to 15s.
PingTimeout time.Duration
// WriteByteTimeout is the timeout after which the connection will be
// closed no data can be written to it. The timeout begins when data is
// available to write, and is extended whenever any bytes are written.
WriteByteTimeout time.Duration
// ReadIdleTimeout is the timeout after which a health check using ping
// frame will be carried out if no frame is received on the connection.
// Note that a ping response will is considered a received frame, so if
// there is no other traffic on the connection, the health check will
// be performed every ReadIdleTimeout interval.
// If zero, no health check is performed.
ReadIdleTimeout time.Duration
}
// clientStream is the state for a single HTTP/2 stream. One of these
// is created for each Transport.RoundTrip call.
type clientStream struct {
cc *clientConn
// Fields of Request that we may access even after the response body is closed.
ctx context.Context
ID uint32
bufPipe pipe // buffered pipe with the flow-controlled response payload
requestedGzip bool
isHead bool
abortOnce sync.Once
abort chan struct{} // closed to signal stream should end immediately
abortErr error // set if abort is closed
peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
donec chan struct{} // closed after the stream is in the closed state
on100 chan struct{} // buffered; written to if a 100 is received
respHeaderRecv chan struct{} // closed when headers are received
res *protocol.Response // set if respHeaderRecv is closed
flow flow // guarded by cc.mu
inflow flow // guarded by cc.mu
bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
readErr error // sticky read error; owned by transportResponseBody.Read
reqBody io.Reader
reqBodyContentLength int64 // -1 means unknown
reqBodyClosed bool // body has been closed; guarded by cc.mu
// owned by writeRequest:
sentEndStream bool // sent an END_STREAM flag to the peer
sentHeaders bool
// owned by clientConnReadLoop:
firstByte bool // got the first response byte
pastHeaders bool // got first MetaHeadersFrame (actual headers)
pastTrailers bool // got optional second MetaHeadersFrame (trailers)
num1xx uint8 // number of 1xx responses seen
readClosed bool // peer sent an END_STREAM flag
readAborted bool // read loop reset the stream
trailer []hpack.HeaderField
}
var got1xxFuncForTests func(int, *protocol.ResponseHeader) error
// get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
// if any. It returns nil if not set or if the Go version is too old.
func (cs *clientStream) get1xxTraceFunc() func(int, *protocol.ResponseHeader) error {
if fn := got1xxFuncForTests; fn != nil {
return fn
}
return nil
}
func (cs *clientStream) abortStream(err error) {
cs.cc.mu.Lock()
defer cs.cc.mu.Unlock()
cs.abortStreamLocked(err)
}
func (cs *clientStream) abortStreamLocked(err error) {
cs.abortOnce.Do(func() {
cs.abortErr = err
close(cs.abort)
})
if cs.reqBody != nil && !cs.reqBodyClosed {
if bsc, ok := cs.reqBody.(io.Closer); ok {
bsc.Close()
}
cs.reqBodyClosed = true
}
// TODO: Clean up tests where cs.cc.cond is nil.
if cs.cc.cond != nil {
// Wake up writeRequestBody if it is waiting on flow control.
cs.cc.cond.Broadcast()
}
}
func (cs *clientStream) abortRequestBodyWrite() {
cc := cs.cc
cc.mu.Lock()
defer cc.mu.Unlock()
if cs.reqBody != nil && !cs.reqBodyClosed {
if bsc, ok := cs.reqBody.(io.Closer); ok {
bsc.Close()
}
cs.reqBodyClosed = true
cc.cond.Broadcast()
}
}
func (cs *clientStream) copyTrailer() {
for _, hf := range cs.trailer {
key := canonicalHeader(hf.Name)
cs.res.Header.Trailer().UpdateArgBytes(bytesconv.S2b(key), bytesconv.S2b(hf.Value))
}
}
type stickyErrWriter struct {
conn net.Conn
timeout time.Duration
err *error
}
func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
if *sew.err != nil {
return 0, *sew.err
}
for {
if sew.timeout != 0 {
sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
}
nn, err := sew.conn.Write(p[n:])
n += nn
if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
// Keep extending the deadline so long as we're making progress.
continue
}
if sew.timeout != 0 {
sew.conn.SetWriteDeadline(time.Time{})
}
*sew.err = err
return n, err
}
}
func (cc *clientConn) healthCheck() {
pingTimeout := cc.hc.PingTimeout
// We don't need to periodically ping in the health check, because the readLoop of ClientConn will
// trigger the healthCheck again if there is no frame received.
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
defer cancel()
err := cc.Ping(ctx)
if err != nil {
cc.closeForLostPing()
cc.hc.onConnectionDropped(cc)
return
}
}
// SetDoNotReuse marks cc as not reusable for future HTTP requests.
func (cc *clientConn) SetDoNotReuse() {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.doNotReuse = true
}
func (cc *clientConn) setGoAway(f *GoAwayFrame) {
cc.mu.Lock()
defer cc.mu.Unlock()
old := cc.goAway
cc.goAway = f
// Merge the previous and current GoAway error frames.
if cc.goAwayDebug == "" {
cc.goAwayDebug = string(f.DebugData())
}
if old != nil && old.ErrCode != ErrCodeNo {
cc.goAway.ErrCode = old.ErrCode
}
last := f.LastStreamID
for streamID, cs := range cc.streams {
if streamID > last {
cs.abortStreamLocked(errClientConnGotGoAway)
}
}
}
// CanTakeNewRequest reports whether the connection can take a new request,
// meaning it has not been closed or received or sent a GOAWAY.
//
// If the caller is going to immediately make a new request on this
// connection, use ReserveNewRequest instead.
func (cc *clientConn) CanTakeNewRequest() bool {
cc.mu.Lock()
defer cc.mu.Unlock()
return cc.canTakeNewRequestLocked()
}
// ReserveNewRequest is like CanTakeNewRequest but also reserves a
// concurrent stream in cc. The reservation is decremented on the
// next call to RoundTrip.
func (cc *clientConn) ReserveNewRequest() bool {
cc.mu.Lock()
defer cc.mu.Unlock()
if st := cc.idleStateLocked(); !st.canTakeNewRequest {
return false
}
cc.streamsReserved++
return true
}
// ClientConnState describes the state of a ClientConn.
type ClientConnState struct {
// Closed is whether the connection is closed.
Closed bool
// Closing is whether the connection is in the process of
// closing. It may be closing due to shutdown, being a
// single-use connection, being marked as DoNotReuse, or
// having received a GOAWAY frame.
Closing bool
// StreamsActive is how many streams are active.
StreamsActive int
// StreamsReserved is how many streams have been reserved via
// ClientConn.ReserveNewRequest.
StreamsReserved int
// StreamsPending is how many requests have been sent in excess
// of the peer's advertised MaxConcurrentStreams setting and
// are waiting for other streams to complete.
StreamsPending int
// MaxConcurrentStreams is how many concurrent streams the
// peer advertised as acceptable. Zero means no SETTINGS
// frame has been received yet.
MaxConcurrentStreams uint32
// LastIdle, if non-zero, is when the connection last
// transitioned to idle state.
LastIdle time.Time
}
// State returns a snapshot of cc's state.
func (cc *clientConn) State() ClientConnState {
cc.wmu.Lock()
maxConcurrent := cc.maxConcurrentStreams
if !cc.seenSettings {
maxConcurrent = 0
}
cc.wmu.Unlock()
cc.mu.Lock()
defer cc.mu.Unlock()
return ClientConnState{
Closed: cc.closed,
Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
StreamsActive: len(cc.streams),
StreamsReserved: cc.streamsReserved,
StreamsPending: cc.pendingRequests,
LastIdle: cc.lastIdle,
MaxConcurrentStreams: maxConcurrent,
}
}
// clientConnIdleState describes the suitability of a client
// connection to initiate a new RoundTrip request.
type clientConnIdleState struct {
canTakeNewRequest bool
}
func (cc *clientConn) idleStateLocked() (st clientConnIdleState) {
if cc.singleUse && cc.nextStreamID > 1 {
return
}
var maxConcurrentOkay bool
if cc.hc.StrictMaxConcurrentStreams {
// We'll tell the caller we can take a new request to
// prevent the caller from dialing a new TCP
// connection, but then we'll block later before
// writing it.
maxConcurrentOkay = true
} else {
maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
}
st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
!cc.doNotReuse &&
int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
!cc.tooIdleLocked()
return
}
func (cc *clientConn) canTakeNewRequestLocked() bool {
st := cc.idleStateLocked()
return st.canTakeNewRequest
}
// tooIdleLocked reports whether this connection has been been sitting idle
// for too much wall time.
func (cc *clientConn) tooIdleLocked() bool {
// The Round(0) strips the monontonic clock reading so the
// times are compared based on their wall time. We don't want
// to reuse a connection that's been sitting idle during
// VM/laptop suspend if monotonic time was also frozen.
return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
}
// onIdleTimeout is called from a time.AfterFunc goroutine. It will
// only be called when we're idle, but because we're coming from a new
// goroutine, there could be a new request coming in at the same time,
// so this simply calls the synchronized closeIfIdle to shut down this
// connection. The timer could just call closeIfIdle, but this is more
// clear.
func (cc *clientConn) onIdleTimeout() {
cc.closeIfIdle()
}
func (cc *clientConn) closeIfIdle() {
cc.mu.Lock()
if len(cc.streams) > 0 || cc.streamsReserved > 0 {
cc.mu.Unlock()
return
}
cc.closed = true
nextID := cc.nextStreamID
// TODO: do clients send GOAWAY too? maybe? Just Close:
cc.mu.Unlock()
if VerboseLogs {
hlog.SystemLogger().Infof("HTTP2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
}
cc.tconn.Close()
}
var shutdownEnterWaitStateHook = func() {}
// Shutdown gracefully closes the client connection, waiting for running streams to complete.
func (cc *clientConn) Shutdown(ctx context.Context) error {