Skip to content

Commit 0a81d5a

Browse files
neildgopherbot
authored andcommitted
http2: add wrapped Transport.RoundTrip
Implement the basic RoundTrip in terms of net/http. For #78508 Change-Id: I0c9948bf12fb351aa0ca63ad91feb4bb6a6a6964 Reviewed-on: https://go-review.googlesource.com/c/net/+/771141 Auto-Submit: Damien Neil <[email protected]> LUCI-TryBot-Result: [email protected] <[email protected]> Reviewed-by: Nicholas Husin <[email protected]> Reviewed-by: Nicholas Husin <[email protected]>
1 parent c930746 commit 0a81d5a

4 files changed

Lines changed: 195 additions & 24 deletions

File tree

‎http2/clientconn_test.go‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,13 @@ func testTestClientConn(t testing.TB) {
5252
req, _ := http.NewRequest("PUT", "https://dummy.tld/", body)
5353
rt := tc.roundTrip(req)
5454

55+
// Note: rt.streamID can give the stream ID, but not when using http2wrap.
56+
streamID := uint32(1)
57+
5558
// tc has a number of methods to check for expected frames sent.
5659
// Here, we look for headers and the request body.
5760
tc.wantHeaders(wantHeader{
58-
streamID: rt.streamID(),
61+
streamID: streamID,
5962
endStream: false,
6063
header: http.Header{
6164
":authority": []string{"dummy.tld"},
@@ -65,15 +68,15 @@ func testTestClientConn(t testing.TB) {
6568
})
6669
// Expect 10 bytes of request body in DATA frames.
6770
tc.wantData(wantData{
68-
streamID: rt.streamID(),
71+
streamID: streamID,
6972
endStream: true,
7073
size: 10,
7174
multiple: true,
7275
})
7376

7477
// tc.writeHeaders sends a HEADERS frame back to the client.
7578
tc.writeHeaders(HeadersFrameParam{
76-
StreamID: rt.streamID(),
79+
StreamID: streamID,
7780
EndHeaders: true,
7881
EndStream: true,
7982
BlockFragment: tc.makeHeaderBlockFragment(
@@ -568,10 +571,6 @@ type testPendingClientConn struct {
568571
}
569572

570573
func newTestTransport(t testing.TB, opts ...any) *testTransport {
571-
if wrappedAPI {
572-
t.Fatal("TODO")
573-
}
574-
575574
tt := &testTransport{
576575
t: t,
577576
li: newSynctestNetListener(),
@@ -594,21 +593,29 @@ func newTestTransport(t testing.TB, opts ...any) *testTransport {
594593
case roundTripXNetHTTP2:
595594
tr = &Transport{
596595
DialTLSContext: func(ctx context.Context, network, address string, tlsConf *tls.Config) (net.Conn, error) {
596+
if tt.useTLS {
597+
return tls.Client(tt.li.newConn(), tlsConf), nil
598+
}
597599
return tt.li.newConn(), nil
598600
},
599-
AllowHTTP: true,
600-
}
601-
case roundTripNetHTTP:
602-
tr1 = &http.Transport{
603-
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
604-
return tt.li.newConn(), nil
605-
},
606-
Protocols: &http.Protocols{},
607601
TLSClientConfig: testTLSClientConfig,
602+
AllowHTTP: true,
608603
}
609-
tr1.Protocols.SetHTTP2(true)
610-
tr1.Protocols.SetUnencryptedHTTP2(true)
611-
t.Cleanup(tr1.CloseIdleConnections)
604+
tr1 = tr.TestTransport()
605+
case roundTripNetHTTP:
606+
tr1 = &http.Transport{}
607+
}
608+
609+
tr1.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
610+
return tt.li.newConn(), nil
611+
}
612+
tr1.TLSClientConfig = testTLSClientConfig
613+
tr1.Protocols = &http.Protocols{}
614+
tr1.Protocols.SetHTTP2(true)
615+
tr1.Protocols.SetUnencryptedHTTP2(true)
616+
t.Cleanup(tr1.CloseIdleConnections)
617+
618+
if tt.mode == roundTripNetHTTP {
612619
var err error
613620
tr, err = ConfigureTransports(tr1)
614621
if err != nil {

‎http2/clientconn_wrap_test.go‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,26 @@ const wrappedAPI = true
2020
type httpClientConn = http.ClientConn
2121

2222
func newTestClientConn(t testing.TB, opts ...any) *testClientConn {
23-
t.Fatal("TODO")
24-
return nil
23+
t.Helper()
24+
tt := newTestTransport(t, opts...)
25+
cc, err := tt.tr1.NewClientConn(t.Context(), "http", "localhost:80")
26+
if err != nil {
27+
t.Fatalf("NewClientConn: %v", err)
28+
}
29+
30+
tc := tt.getConn()
31+
tc.cc1 = cc
32+
return tc
2533
}
2634

2735
func (tr *testTransport) maybeAddNewClientConnHook() {
2836
}
2937

3038
func (tc *testClientConn) doRoundTrip(req *http.Request, f func(streamID uint32)) (*http.Response, error) {
31-
return nil, errors.New("TODO")
39+
tc.t.Helper()
40+
if tc.cc1 == nil {
41+
tc.t.Errorf("RoundTrip on testClientConn with no ClientConn (did you mean to use the testTransport?)")
42+
return nil, errors.New("no ClientConn")
43+
}
44+
return tc.cc1.RoundTrip(req)
3245
}

‎http2/export_wrap_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ package http2
99
import "net/http"
1010

1111
func (t *Transport) TestTransport() *http.Transport {
12-
return nil
12+
t.init()
13+
return t.t1
1314
}
1415

1516
func (s *Server) TestSetNewConnFunc(f func(*ServerConn)) {

‎http2/transport_wrap.go‎

Lines changed: 152 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,31 +10,181 @@ package http2
1010

1111
import (
1212
"context"
13+
"crypto/tls"
14+
"errors"
1315
"net"
1416
"net/http"
17+
"slices"
18+
"sync"
19+
"time"
1520
)
1621

1722
func configureTransport(t1 *http.Transport) error {
23+
// ConfigureTransport is a no-op: The http.Transport already supports HTTP/2.
1824
return nil
1925
}
2026

2127
func configureTransports(t1 *http.Transport) (*Transport, error) {
28+
// ConfigureTransport returns an http2.Transport with a configuration
29+
// linked to the http.Transport's.
2230
tr2 := &Transport{}
31+
tr2.configure(t1)
2332
return tr2, nil
2433
}
2534

35+
// transportConfig is passed to net/http.Transport.RegisterProtocol("http/2", config).
36+
// It provides the net/http.Transport with access to the configuration in the
37+
// x/net/http2.Transport.
38+
type transportConfig struct {
39+
t *Transport
40+
}
41+
42+
// Registered is called by net/http.Transport.RegisterProtocol,
43+
// to let us know that it understands the registration mechanism we're using.
44+
func (t transportConfig) Registered(t1 *http.Transport) {
45+
t.t.t1 = t1
46+
}
47+
48+
func (t transportConfig) DisableCompression() bool {
49+
return t.t.DisableCompression
50+
}
51+
52+
func (t transportConfig) MaxHeaderListSize() int64 {
53+
return int64(t.t.MaxHeaderListSize)
54+
}
55+
56+
func (t transportConfig) IdleConnTimeout() time.Duration {
57+
return t.t.IdleConnTimeout
58+
}
59+
60+
func (t transportConfig) HTTP2Config() http.HTTP2Config {
61+
return http.HTTP2Config{
62+
StrictMaxConcurrentRequests: t.t.StrictMaxConcurrentStreams,
63+
MaxDecoderHeaderTableSize: int(t.t.MaxDecoderHeaderTableSize),
64+
MaxEncoderHeaderTableSize: int(t.t.MaxEncoderHeaderTableSize),
65+
MaxReadFrameSize: int(t.t.MaxReadFrameSize),
66+
SendPingTimeout: t.t.ReadIdleTimeout,
67+
PingTimeout: t.t.PingTimeout,
68+
WriteByteTimeout: t.t.WriteByteTimeout,
69+
CountError: t.t.CountError,
70+
}
71+
}
72+
73+
// ExternalRoundTrip reports whether the Transport wants to take control of the RoundTrip call.
74+
// If the user hasn't configured a custom connection pool, we leave the RoundTrip up to net/http.
75+
func (t transportConfig) ExternalRoundTrip() bool {
76+
return t.t.ConnPool != nil
77+
}
78+
79+
// RoundTrip is used when the http.Transport is passing control of the full
80+
// RoundTrip to us--connection pooling, retries, etc.
81+
//
82+
// This is only used when the http2.Transport has a user-provided ConnPool.
83+
// Any other time, net/http handles everything.
84+
func (t transportConfig) RoundTrip(req *http.Request) (*http.Response, error) {
85+
if t.t.ConnPool == nil {
86+
return nil, http.ErrSkipAltProtocol
87+
}
88+
return t.t.RoundTrip(req)
89+
}
90+
91+
// netConnContextKey passes a net.Conn to http.Transport.NewClientConn.
92+
// See http2.Transport.NewClientConn.
93+
type netConnContextKey struct{}
94+
95+
// ConnFromContext lets the http.Transport fetch a net.Conn out of a context
96+
// passed to NewClientConn. See http2.Transport.NewClientConn.
97+
func (t transportConfig) ConnFromContext(ctx context.Context) net.Conn {
98+
nc, _ := ctx.Value(netConnContextKey{}).(net.Conn)
99+
return nc
100+
}
101+
102+
// http2TransportContextKey marks a RoundTrip as needing its dial handled by the http2.Transport.
103+
// We set this for http2.RoundTrip calls, where the historical behavior is to use the
104+
// http2.Transport's dialer.
105+
type http2TransportContextKey struct{}
106+
107+
// DialFromContext dials a new connection using the http2.Transport's DialTLS/DialTLSContext.
108+
func (t transportConfig) DialFromContext(ctx context.Context, network, address string) (net.Conn, error) {
109+
if ctx.Value(http2TransportContextKey{}) == nil {
110+
// We're being called from a RoundTrip that did not start with an http2.Transport.
111+
// Use the http.Transport's dialer.
112+
return nil, errors.ErrUnsupported
113+
}
114+
115+
tlsConf := t.t.TLSClientConfig
116+
if tlsConf == nil {
117+
tlsConf = &tls.Config{}
118+
} else {
119+
tlsConf = tlsConf.Clone()
120+
}
121+
if !slices.Contains(tlsConf.NextProtos, "h2") {
122+
tlsConf.NextProtos = append([]string{"h2"}, tlsConf.NextProtos...)
123+
}
124+
if tlsConf.ServerName == "" {
125+
host, _, err := net.SplitHostPort(address)
126+
if err == nil {
127+
tlsConf.ServerName = host
128+
}
129+
}
130+
return t.t.dialTLS(ctx, network, address, tlsConf)
131+
}
132+
26133
type transportInternal struct {
134+
initOnce sync.Once
135+
t1 *http.Transport
136+
}
137+
138+
func (t *Transport) init() {
139+
t.initOnce.Do(func() {
140+
if t.t1 != nil {
141+
return
142+
}
143+
t1 := http.DefaultTransport.(*http.Transport).Clone()
144+
t.configure(t1)
145+
})
146+
}
147+
148+
func (t *Transport) configure(t1 *http.Transport) {
149+
t1.RegisterProtocol("http/2", transportConfig{t})
150+
// tr2.t1 is set by transportConfig.Registered.
151+
if t.t1 != t1 {
152+
panic("http2: net/http does not support this version of x/net/http2")
153+
}
27154
}
28155

29156
func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
30-
return nil, nil
157+
t.init()
158+
159+
if req.URL.Scheme == "http" && !t.AllowHTTP {
160+
return nil, errors.New("http2: unencrypted HTTP/2 not enabled")
161+
}
162+
163+
// When the Transport has a user-provided connection pool (unusual, deprecated),
164+
// we need to handle picking a connection, retrys, etc.
165+
if t.ConnPool != nil {
166+
return nil, errors.New("TODO")
167+
}
168+
169+
// Setting this context key lets net/http know that if it is necessary to dial
170+
// a new connection, we should handle the net.Dial.
171+
//
172+
// Both http.Transport and http2.Transport allow the user to provide a custom
173+
// dial function, and historically you only get the dial function from the
174+
// Transport you're calling RoundTrip on.
175+
ctx := context.WithValue(req.Context(), http2TransportContextKey{}, t)
176+
req = req.WithContext(ctx)
177+
178+
return t.t1.RoundTrip(req)
31179
}
32180

33181
func (t *Transport) closeIdleConnections() {
182+
t.init()
183+
t.t1.CloseIdleConnections()
34184
}
35185

36186
func (t *Transport) newUserClientConn(c net.Conn) (*ClientConn, error) {
37-
return nil, nil
187+
return nil, errors.New("TODO")
38188
}
39189

40190
// ClientConn is the state of a single HTTP/2 client connection to an

0 commit comments

Comments
 (0)