package http2
import (
"context"
"crypto/tls"
"errors"
"math"
"net"
"net/http"
"net/http/httptrace"
"slices"
"sync"
"time"
)
func configureTransport(t1 *http .Transport ) error {
_ , err := configureTransports (t1 )
return err
}
func configureTransports(t1 *http .Transport ) (*Transport , error ) {
tr2 := &Transport {}
tr2 .configure (t1 )
if t1 .TLSClientConfig == nil {
t1 .TLSClientConfig = &tls .Config {}
}
if t1 .Protocols == nil {
t1 .Protocols = new (http .Protocols )
t1 .Protocols .SetHTTP1 (true )
}
t1 .Protocols .SetHTTP2 (true )
return tr2 , nil
}
type transportConfig struct {
t *Transport
}
func (t transportConfig ) Registered (t1 *http .Transport ) {
t .t .lazyt1 = t1
}
func (t transportConfig ) GetClientConnStateFunc (f func (*http .ClientConn ) any ) {
t .t .getCCState = f
}
func (t transportConfig ) DisableCompression () bool {
return t .t .DisableCompression
}
func (t transportConfig ) MaxHeaderListSize () int64 {
return int64 (t .t .MaxHeaderListSize )
}
func (t transportConfig ) IdleConnTimeout () time .Duration {
return t .t .IdleConnTimeout
}
func (t transportConfig ) HTTP2Config () http .HTTP2Config {
return http .HTTP2Config {
StrictMaxConcurrentRequests : t .t .StrictMaxConcurrentStreams ,
MaxDecoderHeaderTableSize : int (t .t .MaxDecoderHeaderTableSize ),
MaxEncoderHeaderTableSize : int (t .t .MaxEncoderHeaderTableSize ),
MaxReadFrameSize : int (t .t .MaxReadFrameSize ),
SendPingTimeout : t .t .ReadIdleTimeout ,
PingTimeout : t .t .PingTimeout ,
WriteByteTimeout : t .t .WriteByteTimeout ,
CountError : t .t .CountError ,
}
}
func (t transportConfig ) ExternalRoundTrip () bool {
return t .t .ConnPool != nil
}
func (t transportConfig ) RoundTrip (req *http .Request ) (*http .Response , error ) {
if t .t .ConnPool == nil {
return nil , http .ErrSkipAltProtocol
}
return t .t .RoundTrip (req )
}
type netConnContextKey struct {}
func (t transportConfig ) ConnFromContext (ctx context .Context ) net .Conn {
nc , _ := ctx .Value (netConnContextKey {}).(net .Conn )
return nc
}
type http2TransportContextKey struct {}
func (t transportConfig ) DialFromContext (ctx context .Context , network , address string ) (net .Conn , error ) {
dial , _ := ctx .Value (http2TransportContextKey {}).(*transportRoundTripState )
if dial == nil {
return nil , errors .ErrUnsupported
}
return t .t .dialForRoundTrip (ctx , dial , network , address )
}
type transportInternal struct {
initOnce sync .Once
lazyt1 *http .Transport
getCCState func (*http .ClientConn ) any
dialMu sync .Mutex
dials map [string ]*transportDialState
}
type transportDialState struct {
dialc chan struct {}
dialErr error
rtdonec chan struct {}
}
func (t *Transport ) init () *http .Transport {
t .initOnce .Do (func () {
if t .lazyt1 != nil {
return
}
t1 := &http .Transport {}
t .configure (t1 )
})
return t .lazyt1
}
func (t *Transport ) configure (t1 *http .Transport ) {
t1 .RegisterProtocol ("http/2" , transportConfig {t })
if t .lazyt1 != t1 {
panic ("http2: net/http does not support this version of x/net/http2" )
}
}
type transportRoundTripState struct {
mu sync .Mutex
rtdone bool
rtdonec chan struct {}
gotconnc chan struct {}
}
func (dial *transportRoundTripState ) startDial () (gotconnc chan struct {}, done bool ) {
dial .mu .Lock ()
defer dial .mu .Unlock ()
if dial .rtdone {
return nil , true
}
if dial .rtdonec == nil {
dial .rtdonec = make (chan struct {})
}
dial .gotconnc = make (chan struct {})
return dial .gotconnc , false
}
func (dial *transportRoundTripState ) gotConn () {
dial .mu .Lock ()
defer dial .mu .Unlock ()
if dial .gotconnc != nil {
close (dial .gotconnc )
dial .gotconnc = nil
}
}
func (dial *transportRoundTripState ) roundTripDone () {
dial .mu .Lock ()
defer dial .mu .Unlock ()
dial .rtdone = true
if dial .rtdonec != nil {
close (dial .rtdonec )
}
}
func (t *Transport ) roundTripOpt (req *http .Request , opt RoundTripOpt ) (*http .Response , error ) {
t1 := t .init ()
if req .URL .Scheme == "http" && !t .AllowHTTP {
return nil , errors .New ("http2: unencrypted HTTP/2 not enabled" )
}
if t .ConnPool != nil {
return t .roundTripViaPool (req , opt , t .ConnPool )
}
dial := &transportRoundTripState {}
defer dial .roundTripDone ()
ctx := context .WithValue (req .Context (), http2TransportContextKey {}, dial )
ctx = httptrace .WithClientTrace (ctx , &httptrace .ClientTrace {
GotConn : func (httptrace .GotConnInfo ) {
dial .gotConn ()
},
})
req = req .WithContext (ctx )
return t1 .RoundTrip (req )
}
var errCoalescedDialAbandoned = errors .New ("http2: abandoned coalesced dial" )
const coalescedDialRetryTimeout = 50 * time .Millisecond
func (t *Transport ) dialForRoundTrip (ctx context .Context , dial *transportRoundTripState , network , address string ) (net .Conn , error ) {
gotconnc , rtdone := dial .startDial ()
if rtdone {
return nil , errCoalescedDialAbandoned
}
var state *transportDialState
for {
t .dialMu .Lock ()
if t .dials == nil {
t .dials = make (map [string ]*transportDialState )
}
leader := t .dials [address ]
if leader == nil {
state = &transportDialState {
dialc : make (chan struct {}),
rtdonec : dial .rtdonec ,
}
t .dials [address ] = state
}
t .dialMu .Unlock ()
if leader == nil {
break
}
var (
done = false
leaderdialc = leader .dialc
leaderrtdonec = leader .rtdonec
timerc <-chan time .Time
)
for !done {
if leaderdialc == nil && leaderrtdonec == nil && timerc == nil {
timerc = time .After (coalescedDialRetryTimeout )
}
select {
case <- leaderdialc :
if leader .dialErr != nil {
return nil , leader .dialErr
}
leaderdialc = nil
case <- leaderrtdonec :
leaderrtdonec = nil
case <- timerc :
done = true
case <- dial .rtdonec :
return nil , errCoalescedDialAbandoned
case <- gotconnc :
return nil , errCoalescedDialAbandoned
case <- ctx .Done ():
return nil , ctx .Err ()
}
}
}
tlsConf := t .TLSClientConfig
if tlsConf == nil {
tlsConf = &tls .Config {}
} else {
tlsConf = tlsConf .Clone ()
}
if !slices .Contains (tlsConf .NextProtos , "h2" ) {
tlsConf .NextProtos = append ([]string {"h2" }, tlsConf .NextProtos ...)
}
if tlsConf .ServerName == "" {
host , _ , err := net .SplitHostPort (address )
if err == nil {
tlsConf .ServerName = host
}
}
nc , err := t .dialTLS (ctx , network , address , tlsConf )
t .dialMu .Lock ()
delete (t .dials , address )
t .dialMu .Unlock ()
state .dialErr = err
close (state .dialc )
return nc , err
}
func (t *Transport ) closeIdleConnections () {
t1 := t .init ()
t1 .CloseIdleConnections ()
}
func (t *Transport ) newUserClientConn (c net .Conn ) (*ClientConn , error ) {
t1 := t .init ()
ctx := context .WithValue (context .Background (), netConnContextKey {}, c )
nhcc , err := t1 .NewClientConn (ctx , "http/2" , "" )
if err != nil {
return nil , err
}
cc := &ClientConn {cc : nhcc , tr : t , tconn : c }
nhcc .SetStateHook (cc .stateHook )
return cc , nil
}
type ClientConn struct {
cc *http .ClientConn
tconn net .Conn
tr *Transport
doNotReuse bool
mu sync .Mutex
closing bool
closed bool
roundTrips int
reserved int
starting int
pending int
maxConcurrent int
lastIdle time .Time
shutdownc chan struct {}
atomicReused uint32
}
func (cc *ClientConn ) roundTrip (req *http .Request ) (*http .Response , error ) {
haveReservation , err := func () (bool , error ) {
cc .mu .Lock ()
defer cc .mu .Unlock ()
if cc .doNotReuse {
return false , errClientConnUnusable
}
cc .starting ++
cc .roundTrips ++
if cc .reserved == 0 {
return false , nil
}
cc .reserved --
return true , nil
}()
if err != nil {
return nil , err
}
if !haveReservation && cc .cc .Reserve () != nil {
cc .mu .Lock ()
cc .pending ++
cc .mu .Unlock ()
}
resp , err := cc .cc .RoundTrip (req )
cc .mu .Lock ()
cc .starting --
if cc .pending > 0 {
cc .pending --
}
cc .updateStateLocked ()
cc .mu .Unlock ()
return resp , err
}
func (cc *ClientConn ) canTakeNewRequest () bool {
return cc .cc .Available () > 0 && !cc .doNotReuse
}
func (cc *ClientConn ) close () error {
return cc .cc .Close ()
}
func (cc *ClientConn ) ping (ctx context .Context ) error {
_ , err := cc .cc .RoundTrip ((&http .Request {
Method : ":ping" ,
}).WithContext (ctx ))
return err
}
func (cc *ClientConn ) reserveNewRequest () bool {
if err := cc .cc .Reserve (); err != nil {
return false
}
reserved := true
cc .mu .Lock ()
if cc .doNotReuse {
reserved = false
} else {
cc .reserved ++
}
cc .mu .Unlock ()
if !reserved {
cc .cc .Release ()
}
return reserved
}
func (cc *ClientConn ) setDoNotReuse () {
cc .mu .Lock ()
defer cc .mu .Unlock ()
cc .doNotReuse = true
cc .closing = true
}
func (cc *ClientConn ) shutdown (ctx context .Context ) error {
cc .mu .Lock ()
inFlight := cc .cc .InFlight () + cc .starting
if inFlight > 0 && cc .shutdownc == nil {
cc .shutdownc = make (chan struct {})
}
shutdownc := cc .shutdownc
cc .mu .Unlock ()
if shutdownc != nil {
select {
case <- shutdownc :
case <- ctx .Done ():
return ctx .Err ()
}
}
cc .cc .Close ()
return nil
}
func (cc *ClientConn ) state () ClientConnState {
cc .mu .Lock ()
defer cc .mu .Unlock ()
cc .updateStateLocked ()
var gotStats bool
var streamsActive int
if cc .tr .getCCState != nil {
stats , ok := cc .tr .getCCState (cc .cc ).(interface {
StreamsActive () int
MaxConcurrentStreams () int
})
if ok {
gotStats = true
streamsActive = stats .StreamsActive ()
cc .maxConcurrent = stats .MaxConcurrentStreams ()
}
}
if !gotStats {
streamsActive = cc .cc .InFlight () - cc .reserved
if !cc .closed {
cc .maxConcurrent = cc .cc .Available () + cc .cc .InFlight ()
}
}
return ClientConnState {
Closed : cc .closed ,
Closing : cc .closing ,
StreamsActive : streamsActive ,
StreamsReserved : cc .reserved ,
StreamsPending : cc .pending ,
MaxConcurrentStreams : uint32 (min (int64 (cc .maxConcurrent ), math .MaxUint32 )),
LastIdle : cc .lastIdle ,
}
}
func (cc *ClientConn ) stateHook (*http .ClientConn ) {
cc .mu .Lock ()
defer cc .mu .Unlock ()
cc .updateStateLocked ()
}
func (cc *ClientConn ) updateStateLocked () {
if cc .cc .Err () != nil && !cc .closed {
cc .closing = true
cc .closed = true
if cc .tr .ConnPool != nil {
go cc .tr .ConnPool .MarkDead (cc )
}
}
if cc .cc .InFlight () == 0 && cc .roundTrips > 0 && cc .starting == 0 {
cc .lastIdle = time .Now ()
}
if cc .shutdownc != nil && cc .cc .InFlight ()+cc .starting == 0 {
close (cc .shutdownc )
cc .shutdownc = nil
}
}
func (cc *ClientConn ) stopIdleTimer () {}
func traceGotConn(req *http .Request , cc *ClientConn , reused bool ) {
trace := httptrace .ContextClientTrace (req .Context ())
if trace == nil || trace .GotConn == nil {
return
}
ci := httptrace .GotConnInfo {Conn : cc .tconn }
ci .Reused = reused
trace .GotConn (ci )
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .