Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a silent HTTP/2 connection to a vendor is pinged and dropped (#2843)
yetone94919109cb3b
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 90600cf95..187780162 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -36,7 +36,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) || Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) || Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |-| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |+| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) || Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) || Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) || Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |diff --git a/internal/gateway/upstream_h2_silent_test.go b/internal/gateway/upstream_h2_silent_test.gonew file mode 100644index 000000000..4796d9a18--- /dev/null+++ b/internal/gateway/upstream_h2_silent_test.go@@ -0,0 +1,233 @@+package gateway++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/netproxy"+ "github.com/yetone/magpie/internal/provider"+)++// silentPath sits between the gateway and a vendor and can go silent on+// the connections open through it: it goes on taking what the gateway+// writes, so every write succeeds, and passes nothing either way, as a+// local proxy whose own way out died, or a NAT that forgot the flow, does.+// A connection opened after it went silent passes as before.+type silentPath struct {+ ln net.Listener+ to string+ mu sync.Mutex+ open []*silentConn+ wg sync.WaitGroup+}++type silentConn struct {+ a, b net.Conn+ silent atomic.Bool+}++func newSilentPath(t *testing.T, to string) *silentPath {+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ p := &silentPath{ln: ln, to: to}+ p.wg.Add(1)+ go func() {+ defer p.wg.Done()+ for {+ a, err := ln.Accept()+ if err != nil {+ return+ }+ b, err := net.Dial("tcp", to)+ if err != nil {+ a.Close()+ continue+ }+ c := &silentConn{a: a, b: b}+ p.mu.Lock()+ p.open = append(p.open, c)+ p.mu.Unlock()+ pipe := func(dst, src net.Conn) {+ defer p.wg.Done()+ buf := make([]byte, 32<<10)+ for {+ n, err := src.Read(buf)+ if n > 0 && !c.silent.Load() {+ if _, werr := dst.Write(buf[:n]); werr != nil {+ return+ }+ }+ if err != nil {+ return+ }+ }+ }+ p.wg.Add(2)+ go pipe(b, a)+ go pipe(a, b)+ }+ }()+ t.Cleanup(func() {+ p.ln.Close()+ p.mu.Lock()+ for _, c := range p.open {+ c.a.Close()+ c.b.Close()+ }+ p.mu.Unlock()+ p.wg.Wait()+ })+ return p+}++// hush silences every connection open now.+func (p *silentPath) hush() int {+ p.mu.Lock()+ defer p.mu.Unlock()+ for _, c := range p.open {+ c.silent.Store(true)+ }+ return len(p.open)+}++func (p *silentPath) conns() int {+ p.mu.Lock()+ defer p.mu.Unlock()+ return len(p.open)+}++// quickPings has the gateway's transports, made after it, ping a quiet+// HTTP/2 connection after 200ms and drop it 300ms later, and trust+// vendor's certificate.+func quickPings(t *testing.T, vendor *httptest.Server) {+ pool := x509.NewCertPool()+ pool.AddCert(vendor.Certificate())+ wasTLS, wasAfter, wasWait := upstreamTLS, netproxy.PingAfter, netproxy.PingWait+ upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"}+ netproxy.PingAfter, netproxy.PingWait = 200*time.Millisecond, 300*time.Millisecond+ t.Cleanup(func() { upstreamTLS, netproxy.PingAfter, netproxy.PingWait = wasTLS, wasAfter, wasWait })+}++func h2Vendor(t *testing.T, h http.HandlerFunc) *httptest.Server {+ vendor := httptest.NewUnstartedServer(h)+ vendor.EnableHTTP2 = true+ vendor.StartTLS()+ t.Cleanup(vendor.Close)+ return vendor+}++// #2843 (pinewhite): every request of a group to ClinePass hung with no+// first byte for half an hour, and a restart answered the same request in+// 1.6s. Over HTTP/2 every request to a vendor shares one connection, and+// one gone silent without closing (a proxy's way out died, a NAT dropped+// the flow) was kept and given every new request, each waiting up to the+// 10-minute ResponseHeaderTimeout, while the kernel took the writes. The+// gateway's transport now pings a connection quiet for a while and drops+// it when the ping goes unanswered: the request on it fails (so the group+// moves on) and the next one dials a new connection.+func TestSilentHTTP2ConnectionIsDropped(t *testing.T) {+ fresh(t)+ vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ io.WriteString(w, r.Proto)+ })+ path := newSilentPath(t, vendor.Listener.Addr().String())+ quickPings(t, vendor)+ s := New()+ t.Cleanup(s.client.CloseIdleConnections)+ u := "https://" + path.ln.Addr().String() + "/v1/chat/completions"+ ask := func(within time.Duration) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), within)+ defer cancel()+ req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, nil)+ res, err := s.client.Do(req)+ if err != nil {+ return "", err+ }+ defer res.Body.Close()+ b, err := io.ReadAll(res.Body)+ return string(b), err+ }+ if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" {+ t.Fatalf("first request: %q, %v; want HTTP/2.0", got, err)+ }+ if n := path.hush(); n != 1 {+ t.Fatalf("%d connections open before the path went silent, want 1", n)+ }+ // the stalled request ends well before a client gives up (curl -m 55+ // in the report), here 10s against a ping bound of 0.5s+ began := time.Now()+ _, err := ask(10 * time.Second)+ if err == nil {+ t.Fatal("a request on the silent connection was answered")+ }+ if d := time.Since(began); d >= 10*time.Second {+ t.Fatalf("a request on the silent connection hung %v, until the client gave up: %v", d, err)+ }+ // and the one after it goes out on a new connection, without a restart+ if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" {+ t.Fatalf("request after the silent connection: %q, %v; want HTTP/2.0 on a new connection", got, err)+ }+ if n := path.conns(); n != 2 {+ t.Errorf("%d connections dialled, want 2: the silent one and a new one", n)+ }+}++// The same through a routing group, as in the report: a group's first+// member on a connection gone silent is given up on and the next member+// answers, where before the request hung until its agent gave up and the+// next one hung the same way.+func TestGroupMovesOnFromSilentHTTP2Connection(t *testing.T) {+ fresh(t)+ vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"a","choices":[{"message":{"role":"assistant","content":"from a"}}]}`)+ })+ path := newSilentPath(t, vendor.Listener.Addr().String())+ quickPings(t, vendor)+ if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"},+ Chat: "https://" + path.ln.Addr().String() + "/v1"}); err != nil {+ t.Fatal(err)+ }+ serveOn(t, "b", "k", []string{"m"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"b","choices":[{"message":{"role":"assistant","content":"from b"}}]}`)+ }))+ if err := provider.SaveGroup(provider.Group{Name: "Auto", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {+ t.Fatal(err)+ }+ s := New()+ t.Cleanup(s.client.CloseIdleConnections)+ ask := func() (int, string, time.Duration) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/v1/chat/completions",+ strings.NewReader(`{"model":"group/auto","messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx)+ began := time.Now()+ s.Handler().ServeHTTP(rec, req)+ return rec.Code, rec.Body.String(), time.Since(began)+ }+ if code, body, _ := ask(); code != http.StatusOK || !strings.Contains(body, "from a") {+ t.Fatalf("first group request: %d %s; want a's reply", code, body)+ }+ path.hush()+ code, body, took := ask()+ if code != http.StatusOK || !strings.Contains(body, "from b") {+ t.Fatalf("group request with a's connection silent: %d %s after %v; want b's reply", code, body, took)+ }+}diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.goindex bce715a1f..d1cadd3db 100644--- a/internal/gateway/upstream_transport.go+++ b/internal/gateway/upstream_transport.go@@ -26,6 +26,8 @@ func upstreamTransport() http.RoundTripper {IdleConnTimeout: 90 * time.Second,ForceAttemptHTTP2: true,TLSClientConfig: upstreamTLS,+ // a silent HTTP/2 connection is pinged and dropped (#2843)+ HTTP2: netproxy.HTTP2Health(),})}}diff --git a/internal/netproxy/http2_health_test.go b/internal/netproxy/http2_health_test.gonew file mode 100644index 000000000..2282ddbde--- /dev/null+++ b/internal/netproxy/http2_health_test.go@@ -0,0 +1,23 @@+package netproxy++import (+ "net/http"+ "testing"+)++// http.DefaultClient's HTTP/2 connections (usage cards, catalogs,+// sign-ins) are checked as the gateway's are: one gone silent is pinged+// and dropped rather than given every request after it (#2843).+func TestInstallChecksHTTP2Connections(t *testing.T) {+ d, ok := http.DefaultTransport.(*http.Transport)+ if !ok {+ t.Skip("http.DefaultTransport is not an *http.Transport")+ }+ was, wasClient, wasProxy := d.HTTP2, http.DefaultClient.Transport, d.Proxy+ t.Cleanup(func() { d.HTTP2, http.DefaultClient.Transport, d.Proxy = was, wasClient, wasProxy })+ d.HTTP2 = nil+ Install()+ if d.HTTP2 == nil || d.HTTP2.SendPingTimeout != PingAfter || d.HTTP2.PingTimeout != PingWait {+ t.Fatalf("http.DefaultTransport's HTTP/2 after Install: %+v; want pings after %v, dropped after %v", d.HTTP2, PingAfter, PingWait)+ }+}diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.goindex abedcb0ad..5c9989cb5 100644--- a/internal/netproxy/netproxy.go+++ b/internal/netproxy/netproxy.go@@ -25,14 +25,35 @@ 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).+// (With) through a transport of that provider's proxy (Dispatch). Its+// HTTP/2 connections are checked as the gateway's are (HTTP2Health).func Install() {if t, ok := http.DefaultTransport.(*http.Transport); ok {t.Proxy = Func+ if t.HTTP2 == nil {+ t.HTTP2 = HTTP2Health()+ }http.DefaultClient.Transport = Dispatch(t)}}+// PingAfter and PingWait: an HTTP/2 connection that has had no frame for+// PingAfter is pinged, and dropped when no answer comes within PingWait.+var PingAfter, PingWait = 20 * time.Second, 10 * time.Second++// HTTP2Health is the HTTP/2 setting of a transport to the vendors. Every+// request to one host shares one HTTP/2 connection, and one gone silent+// without closing (a proxy's way out died, a NAT forgot the flow) was+// given every new request, each waiting for its transport's+// ResponseHeaderTimeout while the kernel took the writes, until a restart+// (#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.+func HTTP2Health() *http.HTTP2Config {+ return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait}+}+// Func is an http.Transport Proxy function: the proxy the request's// context names (With), or else the global one, which a host on the// user's own network goes around (onLAN).