gateway: a vendor thinking for minutes is not pinged into GOAWAY too_many_pings
zdevoz (Discord, Windows, 0.1.3249): gemini-4-argon at effort high
through Antigravity waited ~235s for its first byte and then failed with
"http2: server sent GOAWAY and closed the connection; LastStreamID=3,
ErrCode=ENHANCE_YOUR_CALM, debug=\"too_many_pings\"". magpie logged a 502
and sent the whole turn again, so one turn took 421s.
Cause: the gateway's transports used Go's HTTP/2 health check
(netproxy.HTTP2Health, SendPingTimeout 10s). Go's client resets its
read-idle timer on every frame it reads, the ping's own ACK included
(h2_bundle.go readLoop / healthCheck), so a silent connection is pinged
every 10s for as long as the silence lasts, about 24 pings in four
minutes. Google's front end holds clients to gRPC's ping policy
(keepalive.md: a ping within MIN_RECV_PING_INTERVAL_WITHOUT_DATA, 5
minutes, of the last with no HEADERS or DATA sent between is a strike;
past MAX_PING_STRIKES, 2, the server sends GOAWAY ENHANCE_YOUR_CALM
"too_many_pings").
Fix: netproxy.CalmHTTP2 gives the gateway's vendor transports
(vendorTransport, so upstreamTransport and each Dispatch clone) an
HTTP/2 health check of magpie's own, on x/net/http2 with a ConnPool that
never dials (net/http dials through the proxy and hands the connection
over in TLSNextProto). The first ping of a silence still goes at
PingAfter (10s) and a lost one still drops the connection after
PingWait, in Go's words ("http2: client connection lost", which lostPing
reads), so #2843 and #4936 are found as fast as before. A silence starts
at the vendor's last HEADERS/DATA/CONTINUATION frame (read from the
frame headers as they come) or at the request handed to the connection.
After an answered ping the next waits PingAgain, 5 minutes, so a 4-minute
silence has one ping. A Dispatch clone gets its own pool (Clone copies
TLSNextProto, not RegisterProtocol), and t.CloseIdleConnections reaches
the calm pool through net/http's altProto lookup, so the proxy-move and
region drops (#4523, #5182) still close the connections.
uploadTransport stays on Go's HTTP/2 with no ping (#3909), and
http.DefaultTransport keeps HTTP2Health: its requests are short, and it
is cloned at 8 sites that would share one calm pool across proxies.
Retry after a GOAWAY: the retry the reporter saw is still made. With the
pings gone it should not be needed. When a GOAWAY does come, the
connection can't take a new request and the pool drops it, so the next
try dials anew (TestTryAfterGoawayDialsAnew).
Tests (no network):
- TestLongSilenceIsNotPingedIntoGoaway: a raw x/net Framer HTTP/2 vendor
that enforces gRPC's ping policy (minimum gap scaled to 600ms, GOAWAY
ENHANCE_YOUR_CALM too_many_pings past 2 strikes) and answers after a
2.5s silence, reached through upstreamTransport with pings scaled to
100ms/1s/1s.
- TestTryAfterGoawayDialsAnew.
- TestRequestOnAHoledConnectionFailsAtThePing now runs for HTTP2Health
and CalmHTTP2, and the calm run must fail with "client connection lost".
- TestCalmFindsAPathDeadLaterInTheSilence: a path that dies after the
first ping was answered is found at the PingAgain ping.
- TestCalmIdleConnectionsCloseAndClonesKeepTheirOwn.
Run (mote, Go 1.26.8):
- go vet -tags nogui ./internal/netproxy ./internal/gateway, plus
GOOS=windows and GOOS=linux vet; gofmt -l clean.
- go test -race -count=1 ./internal/netproxy: ok.
- go test -count=1 -run
"H2|HTTP2|Silent|Upload|Uplink|Region|Proxy|Goaway|LongSilence|Unsent|Replay|Fresh|LargeBody|Codex|Antigravity|CodeAssist"
./internal/gateway: ok (131s).
- win-run (xiaomi-gpu, Windows 11): go test ./internal/netproxy ok, and
the gateway's Goaway/LongSilence/SilentHTTP2/Unsent/Upload/LargeBody
tests ok.
- Again at the pushed head, rebased on 784113472: vet, gofmt,
./internal/netproxy and the gateway subset above (with TokenWall and
Fallback, which the rebase brought in): ok.
- The full go test -timeout 45m ./... runs after the push under the
suite lock; any red is filed as an issue with its output.
Broken by hand:
- vendorTransport back on HTTP2Health: TestLongSilenceIsNotPingedIntoGoaway
red in 0.46s with the reporter's exact error: "http2: server sent GOAWAY
and closed the connection; LastStreamID=1, ErrCode=ENHANCE_YOUR_CALM,
debug=\"too_many_pings\"" (4 pings, 1 GOAWAY).
- watch with PingAgain = 1h: TestCalmFindsAPathDeadLaterInTheSilence red
(context deadline at 20s).
- watch with PingAfter = 1h: TestRequestOnAHoledConnectionFailsAtThePing/
CalmHTTP2 red (20s, the dead path not found).
- Dispatch not re-calming its clones: base's request went on the clone's
connection, red.
- calmPool.CloseIdleConnections a no-op: the idle connection never
closed, red.
Not tried: a real Antigravity or Google request (no real account was
used, and Google's exact tolerance is unknown: the report suggests about
22 pings at 10s). Not tried with a real proxy between. Go 1.27 moves
x/net's Transport onto net/http's (transport_wrap.go); ConnPool is still
honoured there, but this has not been run on it.
Reported-by: zdevoz (Discord)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -116,7 +116,7 @@ func closedUnsentClient(t *testing.T) *http.Client {
|
||||
was := unsentAgain
|
||||
unsentAgain = []time.Duration{5 * time.Millisecond, 5 * time.Millisecond}
|
||||
t.Cleanup(func() { unsentAgain = was })
|
||||
tr := vendorTransport(time.Minute)
|
||||
tr := plainVendorTransport(time.Minute)
|
||||
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
var h1 http.Protocols
|
||||
h1.SetHTTP1(true)
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/hpack"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
)
|
||||
|
||||
// pingPolicyVendor is an HTTP/2 vendor that answers each request after a
|
||||
// silence, and holds its clients to gRPC's ping policy, as Google's front
|
||||
// end does (grpc keepalive.md, chttp2's ping abuse policy): a ping that
|
||||
// comes within minGap of the last one, with no HEADERS or DATA sent
|
||||
// between, is a strike, and past two strikes the connection ends with
|
||||
// GOAWAY ENHANCE_YOUR_CALM "too_many_pings".
|
||||
type pingPolicyVendor struct {
|
||||
ln net.Listener
|
||||
cert *x509.Certificate
|
||||
silence time.Duration
|
||||
minGap time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
conns int
|
||||
pings []time.Time
|
||||
goaways int
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func newPingPolicyVendor(t *testing.T, silence, minGap time.Duration) *pingPolicyVendor {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "127.0.0.1"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1").To4()},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := &pingPolicyVendor{ln: ln, cert: cert, silence: silence, minGap: minGap}
|
||||
conf := &tls.Config{
|
||||
Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}},
|
||||
NextProtos: []string{"h2"},
|
||||
}
|
||||
var open []net.Conn
|
||||
v.wg.Add(1)
|
||||
go func() {
|
||||
defer v.wg.Done()
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
v.mu.Lock()
|
||||
v.conns++
|
||||
open = append(open, c)
|
||||
v.mu.Unlock()
|
||||
v.wg.Add(1)
|
||||
go func() {
|
||||
defer v.wg.Done()
|
||||
defer c.Close()
|
||||
v.serve(tls.Server(c, conf))
|
||||
}()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
ln.Close()
|
||||
v.mu.Lock()
|
||||
for _, c := range open {
|
||||
c.Close()
|
||||
}
|
||||
v.mu.Unlock()
|
||||
v.wg.Wait()
|
||||
})
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *pingPolicyVendor) Addr() string { return v.ln.Addr().String() }
|
||||
|
||||
func (v *pingPolicyVendor) serve(c *tls.Conn) {
|
||||
preface := make([]byte, len(http2.ClientPreface))
|
||||
if _, err := io.ReadFull(c, preface); err != nil || string(preface) != http2.ClientPreface {
|
||||
return
|
||||
}
|
||||
fr := http2.NewFramer(c, c)
|
||||
var wmu sync.Mutex
|
||||
write := func(f func() error) error {
|
||||
wmu.Lock()
|
||||
defer wmu.Unlock()
|
||||
return f()
|
||||
}
|
||||
if write(func() error { return fr.WriteSettings() }) != nil {
|
||||
return
|
||||
}
|
||||
// the policy's state: chttp2 resets both when it sends HEADERS or DATA
|
||||
var pmu sync.Mutex
|
||||
var lastPing time.Time
|
||||
strikes := 0
|
||||
var lastStream uint32
|
||||
for {
|
||||
f, err := fr.ReadFrame()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch f := f.(type) {
|
||||
case *http2.SettingsFrame:
|
||||
if !f.IsAck() {
|
||||
write(fr.WriteSettingsAck)
|
||||
}
|
||||
case *http2.PingFrame:
|
||||
if f.IsAck() {
|
||||
continue
|
||||
}
|
||||
now := time.Now()
|
||||
v.mu.Lock()
|
||||
v.pings = append(v.pings, now)
|
||||
v.mu.Unlock()
|
||||
pmu.Lock()
|
||||
if !lastPing.IsZero() && now.Sub(lastPing) < v.minGap {
|
||||
strikes++
|
||||
}
|
||||
lastPing = now
|
||||
calm := strikes > 2
|
||||
last := lastStream
|
||||
pmu.Unlock()
|
||||
if calm {
|
||||
v.mu.Lock()
|
||||
v.goaways++
|
||||
v.mu.Unlock()
|
||||
write(func() error {
|
||||
return fr.WriteGoAway(last, http2.ErrCodeEnhanceYourCalm, []byte("too_many_pings"))
|
||||
})
|
||||
// the in-flight stream is not answered: GFE closes it
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
return
|
||||
}
|
||||
data := f.Data
|
||||
write(func() error { return fr.WritePing(true, data) })
|
||||
case *http2.HeadersFrame:
|
||||
id := f.StreamID
|
||||
pmu.Lock()
|
||||
lastStream = id
|
||||
pmu.Unlock()
|
||||
v.mu.Lock()
|
||||
silence := v.silence
|
||||
v.mu.Unlock()
|
||||
go func() {
|
||||
time.Sleep(silence)
|
||||
var hb bytes.Buffer
|
||||
enc := hpack.NewEncoder(&hb)
|
||||
enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
|
||||
enc.WriteField(hpack.HeaderField{Name: "content-type", Value: "text/plain"})
|
||||
pmu.Lock()
|
||||
strikes, lastPing = 0, time.Time{}
|
||||
pmu.Unlock()
|
||||
write(func() error {
|
||||
if err := fr.WriteHeaders(http2.HeadersFrameParam{StreamID: id, BlockFragment: hb.Bytes(), EndHeaders: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
return fr.WriteData(id, true, []byte("thought it through"))
|
||||
})
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// policyPings has the gateway's transports, made after it, trust vendor,
|
||||
// and ping as the real ones do with the times scaled down: a silence's
|
||||
// first ping after 100ms (PingAfter, 10s), the next 1s on (PingAgain,
|
||||
// 5 minutes), against a vendor whose minimum gap is 600ms (gRPC's 5
|
||||
// minutes): room on both sides of it.
|
||||
func policyPings(t *testing.T, vendor *pingPolicyVendor) {
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(vendor.cert)
|
||||
wasTLS := upstreamTLS
|
||||
wasAfter, wasWait, wasAgain := netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain
|
||||
upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"}
|
||||
netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain = 100*time.Millisecond, time.Second, time.Second
|
||||
t.Cleanup(func() {
|
||||
upstreamTLS = wasTLS
|
||||
netproxy.PingAfter, netproxy.PingWait, netproxy.PingAgain = wasAfter, wasWait, wasAgain
|
||||
})
|
||||
}
|
||||
|
||||
// zdevoz (Discord): gemini-4-argon through Antigravity thought for about
|
||||
// four minutes before its first byte, and Google ended the connection:
|
||||
// "http2: server sent GOAWAY and closed the connection; LastStreamID=3,
|
||||
// ErrCode=ENHANCE_YOUR_CALM, debug=\"too_many_pings\"". The turn was lost
|
||||
// at ~235s and sent again from the start. Go's HTTP/2 health check pinged
|
||||
// the silent connection every PingAfter (its ping's own answer restarts
|
||||
// the clock), 24 pings in four minutes; Google's front end takes pings
|
||||
// that close together with nothing sent between as abuse. Now a silence
|
||||
// gets its first ping at PingAfter, and the next PingAgain later, so the
|
||||
// vendor thinking for 2.5 (scaled) minutes answers on the first try.
|
||||
func TestLongSilenceIsNotPingedIntoGoaway(t *testing.T) {
|
||||
fresh(t)
|
||||
vendor := newPingPolicyVendor(t, 2500*time.Millisecond, 600*time.Millisecond)
|
||||
policyPings(t, vendor)
|
||||
s := New()
|
||||
t.Cleanup(s.client.CloseIdleConnections)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://"+vendor.Addr()+"/v1internal:streamGenerateContent?alt=sse", strings.NewReader(`{"request":{}}`))
|
||||
began := time.Now()
|
||||
res, err := s.client.Do(req)
|
||||
took := time.Since(began)
|
||||
vendor.mu.Lock()
|
||||
pings := append([]time.Time(nil), vendor.pings...)
|
||||
goaways, conns := vendor.goaways, vendor.conns
|
||||
vendor.mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatalf("the turn failed after %v, %d pings, %d GOAWAYs: %v", took, len(pings), goaways, err)
|
||||
}
|
||||
b, err := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if err != nil || string(b) != "thought it through" {
|
||||
t.Fatalf("the turn's answer: %q, %v", b, err)
|
||||
}
|
||||
if goaways != 0 || conns != 1 {
|
||||
t.Fatalf("%d GOAWAYs over %d connections; want the turn answered on its one connection", goaways, conns)
|
||||
}
|
||||
// a silence is still pinged, from PingAfter on, so a dead path is
|
||||
// found as soon as before (#4936)
|
||||
if len(pings) == 0 {
|
||||
t.Fatal("the silent connection was never pinged")
|
||||
}
|
||||
if len(pings) > 4 {
|
||||
t.Fatalf("%d pings in a %v silence; want one at PingAfter and one each PingAgain", len(pings), vendor.silence)
|
||||
}
|
||||
if d := pings[0].Sub(began); d > time.Second {
|
||||
t.Fatalf("the first ping came %v into the silence; want it about PingAfter (100ms) in", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A GOAWAY ends the connection it came on, and the try sent again goes out
|
||||
// on a new one, never the connection that refused it.
|
||||
func TestTryAfterGoawayDialsAnew(t *testing.T) {
|
||||
fresh(t)
|
||||
// a vendor whose minimum gap is longer than PingAgain: the third ping
|
||||
// of a silence ends the connection
|
||||
vendor := newPingPolicyVendor(t, 2500*time.Millisecond, 5*time.Second)
|
||||
policyPings(t, vendor)
|
||||
netproxy.PingAgain = 300 * time.Millisecond
|
||||
tr := vendorTransport(time.Minute)
|
||||
t.Cleanup(tr.CloseIdleConnections)
|
||||
cl := &http.Client{Transport: tr}
|
||||
ask := func() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+vendor.Addr()+"/turn", strings.NewReader("{}"))
|
||||
res, err := cl.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
_, err = io.ReadAll(res.Body)
|
||||
return err
|
||||
}
|
||||
err := ask()
|
||||
if err == nil || !strings.Contains(err.Error(), "too_many_pings") {
|
||||
t.Fatalf("the turn on a vendor that refuses the pings: %v; want its GOAWAY", err)
|
||||
}
|
||||
vendor.mu.Lock()
|
||||
vendor.silence = 0
|
||||
vendor.mu.Unlock()
|
||||
if err := ask(); err != nil {
|
||||
t.Fatalf("the try after the GOAWAY: %v", err)
|
||||
}
|
||||
vendor.mu.Lock()
|
||||
conns := vendor.conns
|
||||
vendor.mu.Unlock()
|
||||
if conns != 2 {
|
||||
t.Fatalf("%d connections dialled; want the try after the GOAWAY on a new one", conns)
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,16 @@ var uploadStall = time.Minute
|
||||
|
||||
// vendorTransport is a transport to the vendors that gives one wait to
|
||||
// begin answering, none for 0: the request's context then bounds it.
|
||||
// A silent HTTP/2 connection is pinged and dropped (#2843), by a health
|
||||
// check that doesn't ping a vendor still thinking into ending the
|
||||
// connection (netproxy.CalmHTTP2).
|
||||
func vendorTransport(wait time.Duration) *http.Transport {
|
||||
t := plainVendorTransport(wait)
|
||||
netproxy.CalmHTTP2(t)
|
||||
return t
|
||||
}
|
||||
|
||||
func plainVendorTransport(wait time.Duration) *http.Transport {
|
||||
return &http.Transport{
|
||||
Proxy: netproxy.Func,
|
||||
ResponseHeaderTimeout: wait,
|
||||
@@ -74,8 +83,6 @@ func vendorTransport(wait time.Duration) *http.Transport {
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSClientConfig: upstreamTLS,
|
||||
// a silent HTTP/2 connection is pinged and dropped (#2843)
|
||||
HTTP2: netproxy.HTTP2Health(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +94,7 @@ func vendorTransport(wait time.Duration) *http.Transport {
|
||||
// write that moves no bytes ends the connection (WriteByteTimeout), and a
|
||||
// vendor that never begins answering is ended by the response header wait.
|
||||
func uploadTransport(wait time.Duration) *http.Transport {
|
||||
t := vendorTransport(wait)
|
||||
t := plainVendorTransport(wait)
|
||||
t.HTTP2 = &http.HTTP2Config{WriteByteTimeout: uploadStall}
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
// PingAgain is how long a connection still silent after its first health
|
||||
// ping waits for the next (CalmHTTP2): gRPC's servers, Google's among
|
||||
// them, count a ping that comes sooner after the last, with nothing sent
|
||||
// between, as a strike, and end the connection at the third.
|
||||
var PingAgain = 5 * time.Minute
|
||||
|
||||
// CalmHTTP2 has t, a transport to the vendors, speak HTTP/2 with a health
|
||||
// check of magpie's own instead of Go's (HTTP2Health). Go's pings a
|
||||
// connection each time it has read no frame for PingAfter, and the ping's
|
||||
// own answer is a frame, so a vendor silent for minutes before a turn's
|
||||
// first byte is pinged every 10s for all of them. Google's front end
|
||||
// counts the pings it gets while it has sent nothing and ends the
|
||||
// connection: GOAWAY ENHANCE_YOUR_CALM "too_many_pings" after about four
|
||||
// minutes of gemini thinking through Antigravity, and the turn was lost
|
||||
// and sent again (zdevoz on Discord). gRPC's servers, Google's among them,
|
||||
// take a ping as abuse when it comes within 5 minutes of the last one
|
||||
// with no HEADERS or DATA sent between (keepalive.md:
|
||||
// GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS).
|
||||
//
|
||||
// Here the first ping of a silence still goes out PingAfter into it, so a
|
||||
// connection whose path died before or as a request went out is found as
|
||||
// soon as before (#2843, #4936), and dropped when no answer comes within
|
||||
// PingWait. A silence starts at the vendor's last HEADERS or DATA, or at a
|
||||
// request handed to the connection. A ping answered shows the path alive,
|
||||
// and the next waits PingAgain: a 4-minute wait for a first byte has one
|
||||
// ping, not twenty-four. A path that dies later in a long wait is found at
|
||||
// the next ping, or by the request's own wait for its answer.
|
||||
//
|
||||
// t's settings are read now: CalmHTTP2 is called once t is set up, and a
|
||||
// clone of t is calmed again with its own connections (Dispatch).
|
||||
func CalmHTTP2(t *http.Transport) error {
|
||||
if _, ok := calmed.Load(t); ok {
|
||||
return nil
|
||||
}
|
||||
p := &calmPool{conns: map[string][]*calmConn{}}
|
||||
// set before anything clones t: a clone (or a first request) has
|
||||
// net/http settle t's HTTP/2 once, and it takes the "https" protocol's
|
||||
// one field as the HTTP/2 transport whose idle connections it closes
|
||||
// with its own (CloseIdleConnections)
|
||||
if t.TLSClientConfig == nil {
|
||||
t.TLSClientConfig = &tls.Config{}
|
||||
} else {
|
||||
t.TLSClientConfig = t.TLSClientConfig.Clone()
|
||||
}
|
||||
t.TLSClientConfig.NextProtos = []string{"h2", "http/1.1"}
|
||||
t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
|
||||
"h2": func(authority string, c *tls.Conn) http.RoundTripper {
|
||||
if err := p.add(authority, c); err != nil {
|
||||
go c.Close()
|
||||
return erringRoundTripper{err}
|
||||
}
|
||||
return p.t2
|
||||
},
|
||||
}
|
||||
t.RegisterProtocol("https", calmAlt{Pool: p})
|
||||
|
||||
// x/net's HTTP/2 reads its settings (ResponseHeaderTimeout,
|
||||
// IdleConnTimeout, DisableCompression…) from the transport it was
|
||||
// configured on; this copy is that and never dials
|
||||
conf := t.Clone()
|
||||
conf.TLSNextProto = nil
|
||||
if t.HTTP2 != nil {
|
||||
h := *t.HTTP2
|
||||
h.SendPingTimeout, h.PingTimeout = 0, 0
|
||||
conf.HTTP2 = &h
|
||||
}
|
||||
t2, err := http2.ConfigureTransports(conf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t2.ReadIdleTimeout, t2.PingTimeout = 0, 0
|
||||
t2.ConnPool = p
|
||||
p.t2 = t2
|
||||
calmed.Store(t, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// calmed is every transport CalmHTTP2 set up, so a clone is set up anew.
|
||||
var calmed sync.Map // *http.Transport -> *calmPool
|
||||
|
||||
func isCalm(t *http.Transport) bool {
|
||||
_, ok := calmed.Load(t)
|
||||
return ok
|
||||
}
|
||||
|
||||
// calmAlt is a calmed transport's https protocol: a request goes on a
|
||||
// kept HTTP/2 connection, or back to net/http to dial one.
|
||||
type calmAlt struct{ Pool *calmPool }
|
||||
|
||||
func (a calmAlt) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
res, err := a.Pool.t2.RoundTrip(req)
|
||||
if noCachedConn(err) {
|
||||
return nil, http.ErrSkipAltProtocol
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func noCachedConn(err error) bool {
|
||||
var n interface{ IsHTTP2NoCachedConnError() }
|
||||
return err != nil && errors.As(err, &n)
|
||||
}
|
||||
|
||||
type erringRoundTripper struct{ err error }
|
||||
|
||||
func (e erringRoundTripper) RoundTripErr() error { return e.err }
|
||||
func (e erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, e.err }
|
||||
|
||||
// calmPool keeps a calmed transport's HTTP/2 connections, by host:port.
|
||||
// It never dials: net/http does, through the transport's proxy, and hands
|
||||
// the connection over (TLSNextProto).
|
||||
type calmPool struct {
|
||||
t2 *http2.Transport
|
||||
mu sync.Mutex
|
||||
conns map[string][]*calmConn
|
||||
}
|
||||
|
||||
type calmConn struct {
|
||||
cc *http2.ClientConn
|
||||
w *watchedConn
|
||||
}
|
||||
|
||||
func (p *calmPool) add(authority string, c *tls.Conn) error {
|
||||
// net/http hands a connection over for a request
|
||||
now := time.Now()
|
||||
w := &watchedConn{Conn: c, read: now, ask: now}
|
||||
cc, err := p.t2.NewClientConn(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.conns[authority] = append(p.conns[authority], &calmConn{cc: cc, w: w})
|
||||
p.mu.Unlock()
|
||||
go watch(cc, w, PingAfter, PingWait, PingAgain)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *calmPool) GetClientConn(req *http.Request, addr string) (*http2.ClientConn, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
kept := p.conns[addr][:0]
|
||||
var got *calmConn
|
||||
for _, c := range p.conns[addr] {
|
||||
if c.cc.State().Closed {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, c)
|
||||
if got == nil && c.cc.ReserveNewRequest() {
|
||||
got = c
|
||||
}
|
||||
}
|
||||
p.conns[addr] = kept
|
||||
if got == nil {
|
||||
return nil, http2.ErrNoCachedConn
|
||||
}
|
||||
got.w.asked()
|
||||
return got.cc, nil
|
||||
}
|
||||
|
||||
func (p *calmPool) MarkDead(cc *http2.ClientConn) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
for addr, cs := range p.conns {
|
||||
for i, c := range cs {
|
||||
if c.cc == cc {
|
||||
p.conns[addr] = append(cs[:i:i], cs[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CloseIdleConnections shuts every connection no request is on; one a
|
||||
// request takes meanwhile is let finish it.
|
||||
func (p *calmPool) CloseIdleConnections() {
|
||||
p.mu.Lock()
|
||||
var idle []*http2.ClientConn
|
||||
for addr, cs := range p.conns {
|
||||
kept := cs[:0]
|
||||
for _, c := range cs {
|
||||
s := c.cc.State()
|
||||
if s.StreamsActive == 0 && s.StreamsReserved == 0 && s.StreamsPending == 0 {
|
||||
idle = append(idle, c.cc)
|
||||
continue
|
||||
}
|
||||
kept = append(kept, c)
|
||||
}
|
||||
p.conns[addr] = kept
|
||||
}
|
||||
p.mu.Unlock()
|
||||
for _, cc := range idle {
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
if cc.Shutdown(ctx) != nil {
|
||||
cc.Close()
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// errLostPing is a connection's end when its health ping went unanswered,
|
||||
// in Go's own words for it (closeForLostPing), which lostPing reads.
|
||||
var errLostPing = errors.New("http2: client connection lost")
|
||||
|
||||
// watch is a calmed connection's health check (CalmHTTP2), until the
|
||||
// connection closes.
|
||||
func watch(cc *http2.ClientConn, w *watchedConn, after, wait, again time.Duration) {
|
||||
tick := time.NewTicker(max(after/10, time.Millisecond))
|
||||
defer tick.Stop()
|
||||
var pinged time.Time
|
||||
for range tick.C {
|
||||
if cc.State().Closed || w.isLost() {
|
||||
return
|
||||
}
|
||||
read, fresh := w.times()
|
||||
now := time.Now()
|
||||
var due time.Time
|
||||
if pinged.Before(fresh) {
|
||||
// the first ping of a silence
|
||||
due = later(read, fresh).Add(after)
|
||||
} else {
|
||||
due = pinged.Add(again)
|
||||
}
|
||||
if now.Before(due) {
|
||||
continue
|
||||
}
|
||||
pinged = now
|
||||
ctx, cancel := context.WithTimeout(context.Background(), wait)
|
||||
err := cc.Ping(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if !cc.State().Closed {
|
||||
w.lose()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func later(a, b time.Time) time.Time {
|
||||
if a.After(b) {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// watchedConn is a calmed HTTP/2 connection's TLS connection, which notes
|
||||
// when a frame came, and when the vendor last sent HEADERS or DATA.
|
||||
type watchedConn struct {
|
||||
*tls.Conn
|
||||
mu sync.Mutex
|
||||
read time.Time // the last bytes read
|
||||
spoke time.Time // the last HEADERS, CONTINUATION or DATA frame read
|
||||
ask time.Time // the last request handed the connection
|
||||
scan frameScan
|
||||
lost bool
|
||||
}
|
||||
|
||||
func (w *watchedConn) Read(b []byte) (int, error) {
|
||||
n, err := w.Conn.Read(b)
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if n > 0 {
|
||||
now := time.Now()
|
||||
w.read = now
|
||||
if w.scan.spoke(b[:n]) {
|
||||
w.spoke = now
|
||||
}
|
||||
}
|
||||
if err != nil && w.lost {
|
||||
err = errLostPing
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *watchedConn) asked() {
|
||||
w.mu.Lock()
|
||||
w.ask = time.Now()
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
// times is when bytes last came, and when the silence began: the
|
||||
// vendor's last HEADERS or DATA, or the last request, whichever is later.
|
||||
func (w *watchedConn) times() (read, fresh time.Time) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.read, later(w.spoke, w.ask)
|
||||
}
|
||||
|
||||
func (w *watchedConn) lose() {
|
||||
w.mu.Lock()
|
||||
w.lost = true
|
||||
w.mu.Unlock()
|
||||
w.Conn.NetConn().Close()
|
||||
}
|
||||
|
||||
func (w *watchedConn) isLost() bool {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.lost
|
||||
}
|
||||
|
||||
// frameScan follows HTTP/2 frames through the bytes read, by their
|
||||
// 9-byte headers (RFC 9113 4.1).
|
||||
type frameScan struct {
|
||||
head [9]byte
|
||||
have int // header bytes held
|
||||
left int // payload bytes still to come
|
||||
}
|
||||
|
||||
// spoke says a HEADERS (1), CONTINUATION (9) or DATA (0) frame began in b.
|
||||
func (s *frameScan) spoke(b []byte) bool {
|
||||
saw := false
|
||||
for len(b) > 0 {
|
||||
if s.left > 0 {
|
||||
n := min(s.left, len(b))
|
||||
s.left -= n
|
||||
b = b[n:]
|
||||
continue
|
||||
}
|
||||
n := copy(s.head[s.have:], b)
|
||||
s.have += n
|
||||
b = b[n:]
|
||||
if s.have < len(s.head) {
|
||||
break
|
||||
}
|
||||
s.have = 0
|
||||
s.left = int(s.head[0])<<16 | int(s.head[1])<<8 | int(s.head[2])
|
||||
switch s.head[3] {
|
||||
case 0, 1, 9:
|
||||
saw = true
|
||||
}
|
||||
}
|
||||
return saw
|
||||
}
|
||||
|
||||
var _ net.Conn = (*watchedConn)(nil)
|
||||
@@ -0,0 +1,229 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// hushPipe passes bytes between a client and to until hushed: then it
|
||||
// goes on taking what either side writes and passes none of it, as a
|
||||
// tunnel whose far side died does.
|
||||
type hushPipe struct {
|
||||
ln net.Listener
|
||||
hushed atomic.Bool
|
||||
mu sync.Mutex
|
||||
conns []net.Conn
|
||||
dials int
|
||||
}
|
||||
|
||||
func newHushPipe(t *testing.T, to string) *hushPipe {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &hushPipe{ln: ln}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
a, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b, err := net.Dial("tcp", to)
|
||||
if err != nil {
|
||||
a.Close()
|
||||
continue
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.conns = append(p.conns, a, b)
|
||||
p.dials++
|
||||
p.mu.Unlock()
|
||||
pump := func(dst, src net.Conn) {
|
||||
defer wg.Done()
|
||||
buf := make([]byte, 32<<10)
|
||||
for {
|
||||
n, err := src.Read(buf)
|
||||
if n > 0 && !p.hushed.Load() {
|
||||
if _, err := dst.Write(buf[:n]); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
wg.Add(2)
|
||||
go pump(a, b)
|
||||
go pump(b, a)
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
ln.Close()
|
||||
p.mu.Lock()
|
||||
for _, c := range p.conns {
|
||||
c.Close()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
wg.Wait()
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *hushPipe) Addr() string { return p.ln.Addr().String() }
|
||||
|
||||
// slowH2 is an HTTP/2 vendor that answers after wait, and counts the
|
||||
// connections it has open.
|
||||
func slowH2(t *testing.T, wait time.Duration) (*httptest.Server, *atomic.Int32) {
|
||||
t.Helper()
|
||||
var open atomic.Int32
|
||||
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Conn", r.RemoteAddr)
|
||||
io.WriteString(w, r.Proto)
|
||||
}))
|
||||
srv.EnableHTTP2 = true
|
||||
srv.Config.ConnState = func(_ net.Conn, s http.ConnState) {
|
||||
switch s {
|
||||
case http.StateNew:
|
||||
open.Add(1)
|
||||
case http.StateClosed, http.StateHijacked:
|
||||
open.Add(-1)
|
||||
}
|
||||
}
|
||||
srv.StartTLS()
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, &open
|
||||
}
|
||||
|
||||
func calmTransport(t *testing.T) *http.Transport {
|
||||
t.Helper()
|
||||
tr := &http.Transport{ForceAttemptHTTP2: true, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
|
||||
if err := CalmHTTP2(tr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(tr.CloseIdleConnections)
|
||||
return tr
|
||||
}
|
||||
|
||||
func calmAsk(rt http.RoundTripper, ctx context.Context, url string) (string, error) {
|
||||
got, _, err := calmAskOn(rt, ctx, url)
|
||||
return got, err
|
||||
}
|
||||
|
||||
// calmAskOn is calmAsk, and the connection the answer came on, as the
|
||||
// vendor saw its far end.
|
||||
func calmAskOn(rt http.RoundTripper, ctx context.Context, url string) (string, string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
res, err := rt.RoundTrip(req)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, err := io.ReadAll(res.Body)
|
||||
return string(b), res.Header.Get("X-Conn"), err
|
||||
}
|
||||
|
||||
// A path that dies after the first ping of a long silence was answered is
|
||||
// found at the next one, PingAgain on, and the request on it fails in
|
||||
// Go's words for a lost ping, which the gateway's lostPing reads.
|
||||
func TestCalmFindsAPathDeadLaterInTheSilence(t *testing.T) {
|
||||
scalePings(t, 100*time.Millisecond, 300*time.Millisecond, 800*time.Millisecond)
|
||||
srv, _ := slowH2(t, 30*time.Second)
|
||||
pipe := newHushPipe(t, srv.Listener.Addr().String())
|
||||
tr := calmTransport(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
go func() {
|
||||
// after the first ping (100ms) and its answer
|
||||
time.Sleep(450 * time.Millisecond)
|
||||
pipe.hushed.Store(true)
|
||||
}()
|
||||
began := time.Now()
|
||||
_, err := calmAsk(tr, ctx, "https://"+pipe.Addr()+"/turn")
|
||||
took := time.Since(began)
|
||||
if err == nil {
|
||||
t.Fatal("the turn on a dead path was answered")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "http2: client connection lost") {
|
||||
t.Fatalf("the turn failed with %v after %v; want the lost ping", err, took)
|
||||
}
|
||||
// the next ping goes PingAgain after the first (~900ms), and is lost
|
||||
// PingWait later (~1.2s)
|
||||
if took < 800*time.Millisecond || took > 10*time.Second {
|
||||
t.Fatalf("the dead path was found after %v; want at the ping PingAgain after the first", took)
|
||||
}
|
||||
}
|
||||
|
||||
// CloseIdleConnections closes a calmed transport's HTTP/2 connections, as
|
||||
// it closes Go's own: the gateway drops them when the proxy or region
|
||||
// moves (#4523, #5182). A Dispatch clone, for a provider's own proxy,
|
||||
// keeps connections of its own, dialled through that proxy, never base's.
|
||||
func TestCalmIdleConnectionsCloseAndClonesKeepTheirOwn(t *testing.T) {
|
||||
srv, open := slowH2(t, 0)
|
||||
u := "https://" + srv.Listener.Addr().String() + "/turn"
|
||||
tr := calmTransport(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
for range 2 {
|
||||
if got, err := calmAsk(tr, ctx, u); err != nil || got != "HTTP/2.0" {
|
||||
t.Fatalf("a request: %q, %v; want HTTP/2.0", got, err)
|
||||
}
|
||||
}
|
||||
if n := open.Load(); n != 1 {
|
||||
t.Fatalf("%d connections open after two requests; want one, kept", n)
|
||||
}
|
||||
tr.CloseIdleConnections()
|
||||
waitFor(t, func() bool { return open.Load() == 0 }, "the idle HTTP/2 connection to close")
|
||||
|
||||
d := Dispatch(tr)
|
||||
// the clone first: a connection it dialled and left in base's pool
|
||||
// would carry base's next request
|
||||
got, own, err := calmAskOn(d, With(ctx, "direct"), u)
|
||||
if err != nil || got != "HTTP/2.0" {
|
||||
t.Fatalf("a request through a provider's own proxy: %q, %v", got, err)
|
||||
}
|
||||
got, base, err := calmAskOn(d, ctx, u)
|
||||
if err != nil || got != "HTTP/2.0" {
|
||||
t.Fatalf("a request through base: %q, %v", got, err)
|
||||
}
|
||||
if base == own {
|
||||
t.Fatalf("base's request went on the clone's connection (%s)", own)
|
||||
}
|
||||
if n := open.Load(); n != 2 {
|
||||
t.Fatalf("%d connections open; want base's and the clone's own", n)
|
||||
}
|
||||
d.(interface{ CloseIdleConnections() }).CloseIdleConnections()
|
||||
waitFor(t, func() bool { return open.Load() == 0 }, "base's and the clone's idle connections to close")
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, ok func() bool, what string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for !ok() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("waited 10s for %s", what)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,44 @@ import (
|
||||
// connection). The test watches the bound with the timings scaled down: a
|
||||
// holed connection is pinged at PingAfter, dropped at PingAfter+PingWait,
|
||||
// and the try on it fails with the connection, while the next one dials
|
||||
// anew and succeeds.
|
||||
// anew and succeeds. The same holds for Go's own health check, which
|
||||
// DefaultTransport has (HTTP2Health), and for the gateway's (CalmHTTP2).
|
||||
func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) {
|
||||
pingAfter, pingWait := time.Second, 500*time.Millisecond
|
||||
t.Run("HTTP2Health", func(t *testing.T) {
|
||||
holedTry(t, pingAfter, pingWait, &http.Transport{
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: pingAfter, PingTimeout: pingWait},
|
||||
})
|
||||
})
|
||||
t.Run("CalmHTTP2", func(t *testing.T) {
|
||||
scalePings(t, pingAfter, pingWait, time.Minute)
|
||||
tr := &http.Transport{
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
if err := CalmHTTP2(tr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the gateway's lostPing knows the ping's failure by Go's words
|
||||
if said := holedTry(t, pingAfter, pingWait, tr); !strings.Contains(said, "http2: client connection lost") {
|
||||
t.Fatalf("the turn failed with %q; want Go's words for a lost ping", said)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func scalePings(t *testing.T, after, wait, again time.Duration) {
|
||||
wasAfter, wasWait, wasAgain := PingAfter, PingWait, PingAgain
|
||||
PingAfter, PingWait, PingAgain = after, wait, again
|
||||
t.Cleanup(func() { PingAfter, PingWait, PingAgain = wasAfter, wasWait, wasAgain })
|
||||
}
|
||||
|
||||
// holedTry runs a request on a connection whose path died through tr,
|
||||
// which pings after pingAfter and waits pingWait for the answer, and one
|
||||
// after it.
|
||||
func holedTry(t *testing.T, pingAfter, pingWait time.Duration, tr *http.Transport) string {
|
||||
t.Cleanup(tr.CloseIdleConnections)
|
||||
|
||||
// The vendor, speaking HTTP/2 over TLS on a listener the shim pumps
|
||||
// raw bytes into, as a CONNECT tunnel would.
|
||||
@@ -96,11 +131,7 @@ func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
client := &http.Client{Transport: &http.Transport{
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: pingAfter, PingTimeout: pingWait},
|
||||
}}
|
||||
client := &http.Client{Transport: tr, Timeout: 20 * time.Second}
|
||||
post := func() (time.Duration, int, error) {
|
||||
start := time.Now()
|
||||
req, err := http.NewRequest("POST", "https://"+shim.Addr().String()+"/turn", nil)
|
||||
@@ -150,6 +181,7 @@ func TestRequestOnAHoledConnectionFailsAtThePing(t *testing.T) {
|
||||
if dials != 2 {
|
||||
t.Fatalf("the vendor was dialed %d times; want the retry on a connection of its own", dials)
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
func containsAny(s string, subs ...string) bool {
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
// Install routes http.DefaultTransport (and so http.DefaultClient) through
|
||||
// Func, and http.DefaultClient's requests made on a provider's behalf
|
||||
// (With) through a transport of that provider's proxy (Dispatch). Its
|
||||
// HTTP/2 connections are checked as the gateway's are (HTTP2Health), and
|
||||
// HTTP/2 connections are checked by Go's own pings (HTTP2Health), and
|
||||
// the requests magpie sends on its own are written down (probelog).
|
||||
func Install() {
|
||||
if t, ok := http.DefaultTransport.(*http.Transport); ok {
|
||||
@@ -61,7 +61,10 @@ var PingAfter, PingWait = 10 * time.Second, 10 * time.Second
|
||||
// (#2843). A ping finds it, and the requests on it fail, so a group moves
|
||||
// on and the next request dials anew. A live vendor answers a ping
|
||||
// whatever its streams are doing, so a long wait for a first byte is
|
||||
// never cut by it.
|
||||
// never cut by it. But a ping's answer restarts the clock, so a wait of
|
||||
// minutes is pinged every PingAfter, which Google's front end ends the
|
||||
// connection for: the gateway's transports ping by CalmHTTP2 instead, and
|
||||
// this is for http.DefaultTransport's short requests.
|
||||
func HTTP2Health() *http.HTTP2Config {
|
||||
return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait}
|
||||
}
|
||||
@@ -282,6 +285,14 @@ func (d *dispatch) transport(r route) *http.Transport {
|
||||
if r.unchecked != "" {
|
||||
uncheckTLS(t)
|
||||
}
|
||||
if isCalm(d.base) {
|
||||
// a clone shares base's HTTP/2 connections, dialled through
|
||||
// base's proxy, until it is given its own
|
||||
t.TLSNextProto = nil
|
||||
if !r.h1 {
|
||||
CalmHTTP2(t)
|
||||
}
|
||||
}
|
||||
d.own[r] = t
|
||||
return t
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user