update: a download whose HTTP/2 transfer broke off tries again over HTTP/1.1

biubiu8802 on X (tweet 2118719081872540038): behind their proxy every
update failed with "download broke off, a network problem", while the
same proxy carried ordinary downloads. Confirmed in the code: download()
retried up to 5 times with Range, but each try went through
netproxy.Dispatch over HTTP/2 again; Dispatch moves a host to HTTP/1.1
only on a TLS record error (recordError: bad record MAC and kin), and
"unexpected EOF" or a stream reset is not one. So a proxy that cuts
HTTP/2 streams part way cut every try the same way.

- netproxy: OverHTTP1(ctx) sends every request under ctx through
  Dispatch's HTTP/1.1 copy (route.h1), kept through With.
  BrokeOff(err) says a transfer broke off (net.Error, unexpected EOF,
  HTTP/2 stream error / GOAWAY / lost connection, a reset; not a
  context that ended). AgainOverHTTP1 runs a download once more over
  HTTP/1.1 after such a failure.
- update: the tries after a broken one go over HTTP/1.1, and still
  resume with Range from the bytes kept.
- Siblings, the other big downloads through Dispatch's client: the
  masking model and pf-serve (pii.fetch, one more try over HTTP/1.1
  from what is on the .part file), Bun's zip (plugin getURLFrom),
  Claude Code's binary (claudecode.download) and the Grok CLI
  (grokDownload) each try once more over HTTP/1.1.
- docs/subsystems/providers-accounts.md names it.

Run (mote, Go 1.26.8, at this tree, base 80ae904c2 = origin/main fetched
just before push):
- TestDownloadBrokenOverHTTP2TriesHTTP1 (httptest TLS HTTP/2 server
  that resets each HTTP/2 stream after 100KB, serves HTTP/1.1 whole):
  red with the update.go line taken out, all six tries over HTTP/2
  ("stream error: ... INTERNAL_ERROR"); green after, asked
  ["HTTP/2.0 ", "HTTP/1.1 bytes=102400-"].
- TestOverHTTP1EveryHost, TestAgainOverHTTP1, TestBrokeOff: green.
- go test ./internal/netproxy ./internal/update ./internal/pii
  ./internal/claudecode ./internal/plugin ./internal/provider: ok.
- go test ./... -count=1 -timeout 45m: 86 ok, gateway 795s and agent
  303s ok; internal/gui red only on two AppKit tests already filed for
  mote's macOS 27: TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322). Nothing in gui is
  touched here.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of the touched
  packages clean.

Not tried: a real proxy that cuts HTTP/2 (the reporter's); the retry of
pii, Bun, Claude Code and Grok against a real host (unit-covered by
AgainOverHTTP1 only); Windows/Linux test runs.
This commit is contained in:
yetone
2026-11-06 23:44:58 +08:00
parent 80ae904c23
commit 1fd0bb9670
10 changed files with 285 additions and 7 deletions
+1 -1
View File
@@ -314,7 +314,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- Claude Code's `/usage` prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). `claudeResetTime` reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and `claudeResetSlack`: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2, except a provider held to HTTP/1.1 (`HTTP1`, below) and a host whose HTTP/2 broke on a TLS record error.
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2, except a provider held to HTTP/1.1 (`HTTP1`, below), a host whose HTTP/2 broke on a TLS record error, and the requests of a download trying again after its transfer broke off (`netproxy.OverHTTP1`, `AgainOverHTTP1`, `BrokeOff`: magpie's update, from where it stopped, the masking model's files, Bun, Claude Code and the Grok CLI; biubiu8802 on X: a proxy cut every HTTP/2 stream of the update part way, "unexpected EOF", while it carried HTTP/1.1 whole; `TestDownloadBrokenOverHTTP2TriesHTTP1`, `TestAgainOverHTTP1`).
- A streamed turn to the ChatGPT backend (POST `CodexBase`/responses with `"stream":true`) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (`codexSocket` in [codex_socket.go](../../internal/gateway/codex_socket.go), first in the gateway's `upstreamTransport`, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, before `response.completed`, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with `OpenAI-Beta: responses_websockets=2026-02-06`, without `x-codex-turn-state` and the responses-lite header, which go in the message's `client_metadata` as Codex puts them; the message is the body with `"type":"response.create"` ahead of it (a zstd body is decoded first). `codex.rate_limits` and `codex.response.metadata`, read ahead of the reply, are also told as the `x-codex-*` and `x-codex-turn-state` headers the HTTP route carries; `responsesapi.websocket_timing` is dropped. An `error` frame ahead of the reply is that status with its error as the body; `websocket_connection_limit_reached`, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (`codexSocketShun`). A socket that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. magpie opens a socket per turn and sends the whole body, where Codex's own client sends a delta after `previous_response_id` on a kept socket. A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 ([A Responses WebSocket](gateway-routing.md#a-responses-websocket)), sending a turn as a delta after `previous_response_id`; magpie gives each turn the whole conversation before it goes on, so this leg still sends the whole body. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it.
- A provider the user added may have its certificate left unchecked (`InsecureTLS`, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (`TakesInsecureTLS`: no account, no preset, not Vertex, not a subscription's or plugin's id); `Save` refuses it on any other, and one written into providers.json by hand is ignored. `Provider.Via` then adds `netproxy.WithUncheckedTLS` with the hosts of its own base URLs (`UncheckedHosts`: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a `Dispatch` transport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (`route.unchecked`). A redirect or a models, balance or image URL on another host is checked, and `netproxy.With` drops the leave for a request made for another provider. An `https://` proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (`ErrUncheckedOverHTTPSProxy`); an `http://` or `socks5://` proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
- A provider the user added may be held to HTTP/1.1 (`HTTP1`, the editor's "HTTP version" row under Advanced, shown while an address is `https://`; kepner_53726 on Discord: a company gateway whose HTTP/2 streams broke mid-reply with "tls: bad record MAC" while a plain Go client held). It takes the same providers as `InsecureTLS` (`TakesInsecureTLS`), and `Save` refuses it on any other. `Provider.Via` adds `netproxy.WithHTTP1` with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through the `Dispatch` transport's HTTP/1.1 copy (`route.h1`); another host, and a request made for another provider (`netproxy.With` drops it), are offered HTTP/2 as before (`TestHTTP1AskedOnlyItsHost`, `TestHTTP1OwnProviderOnly`, `TestProviderSaveHTTP1`). Without it, a TLS record error read on an HTTP/2 reply (`recordError`: "bad record MAC", "received record with version …", an oversized record) moves that host:port to HTTP/1.1 for 6 hours (`h2BrokenFor`; see [Gateway routing](gateway-routing.md)).
+8
View File
@@ -29,6 +29,7 @@ import (
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/libc"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
)
@@ -265,7 +266,14 @@ func prune(kept string) {
}
}
// download fetches r to to, once more over HTTP/1.1 when the connection
// broke off (netproxy.AgainOverHTTP1): a proxy that cuts HTTP/2 streams
// part way carries HTTP/1.1 whole.
func download(ctx context.Context, r Release, to string, progress func(int64)) error {
return netproxy.AgainOverHTTP1(ctx, func(ctx context.Context) error { return downloadOnce(ctx, r, to, progress) })
}
func downloadOnce(ctx context.Context, r Release, to string, progress func(int64)) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.URL, nil)
if err != nil {
return err
+60
View File
@@ -5,6 +5,7 @@ import (
"crypto/tls"
"errors"
"io"
"net"
"net/http"
"net/url"
"strings"
@@ -125,3 +126,62 @@ func (b h2Watch) Read(p []byte) (int, error) {
}
return n, err
}
type overHTTP1Key struct{}
// OverHTTP1 is ctx for requests that go over HTTP/1.1 to every host,
// through a transport Dispatch made: a download whose HTTP/2 transfer
// broke off part way tries again with it (AgainOverHTTP1). Some proxies
// cut an HTTP/2 stream mid-file (unexpected EOF, a stream reset, GOAWAY)
// while they carry HTTP/1.1 to the same host whole, and a download that
// tried again over HTTP/2 broke the same way on every try (biubiu8802 on
// X: the update said "download broke off" each time, while the proxy
// served other downloads). It is kept through With.
func OverHTTP1(ctx context.Context) context.Context {
return context.WithValue(ctx, overHTTP1Key{}, true)
}
func overHTTP1(ctx context.Context) bool {
if ctx == nil {
return false
}
on, _ := ctx.Value(overHTTP1Key{}).(bool)
return on
}
// BrokeOff says err is a transfer the connection broke off: the
// connection failed or dropped (a net.Error, a reset, unexpected EOF), or
// an HTTP/2 stream or connection was ended under it (a stream error such
// as INTERNAL_ERROR, GOAWAY, a lost connection). A context that ended is
// no such thing: the caller stopped it.
func BrokeOff(err error) bool {
if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) || recordError(err) {
return true
}
var ne net.Error
if errors.As(err, &ne) {
return true
}
s := err.Error()
for _, w := range []string{"stream error", "GOAWAY", "http2:", "connection reset", "forcibly closed", "broken pipe", "unexpected EOF"} {
if strings.Contains(s, w) {
return true
}
}
return false
}
// AgainOverHTTP1 runs get, and once more with every request under its
// context over HTTP/1.1 (OverHTTP1) when it failed with the connection
// broken off (BrokeOff) while ctx is live. get starts over, or goes on from
// what it kept, as its caller does.
func AgainOverHTTP1(ctx context.Context, get func(context.Context) error) error {
err := get(ctx)
if err == nil || ctx.Err() != nil || overHTTP1(ctx) || !BrokeOff(err) {
return err
}
return get(OverHTTP1(ctx))
}
+4 -3
View File
@@ -169,8 +169,9 @@ var HTTP1 func(u *url.URL) bool
// the idle connections the old one dialled, which a transport, pooling
// by target host alone, would have carried over the switch (#4523). A
// request HTTP1 names, one to a host its provider asked HTTP/1.1 of
// (WithHTTP1), and one to a host whose HTTP/2 connection carried a TLS
// record that didn't decrypt (recordError, for h2Broken after) go
// (WithHTTP1), every request under OverHTTP1 (a download trying again
// after its HTTP/2 transfer broke off), and one to a host whose HTTP/2
// connection carried a TLS record that didn't decrypt (recordError, for h2Broken after) go
// through a clone kept for HTTP/1.1 (http1Only), and one to a host whose certificate the provider's user
// said not to check (WithUncheckedTLS) through a clone kept for that
// host alone (uncheckTLS). A host whose IPv6 is taken but goes nowhere
@@ -203,7 +204,7 @@ func (d *dispatch) RoundTrip(req *http.Request) (*http.Response, error) {
if d.moved() {
d.CloseIdleConnections()
}
r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || h2BrokenFor(req), unchecked: uncheckedHost(req)}
r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL) || http1Asked(req) || overHTTP1(req.Context()) || h2BrokenFor(req), unchecked: uncheckedHost(req)}
t := d.base
if r != (route{}) {
t = d.transport(r)
+96
View File
@@ -0,0 +1,96 @@
package netproxy
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"syscall"
"testing"
)
// A request under OverHTTP1 goes over HTTP/1.1 to every host, through a
// provider's proxy (With) too; one without it over HTTP/2 as before.
func TestOverHTTP1EveryHost(t *testing.T) {
clearProxyEnv(t)
srv, d := h2Server(t, nil)
other, _ := h2Server(t, nil)
h1 := OverHTTP1(context.Background())
for _, u := range []string{srv.URL, other.URL} {
if got := protoOf(t, d, h1, u); got != "HTTP/1.1" {
t.Errorf("%s under OverHTTP1 spoken %s", u, got)
}
}
if got := protoOf(t, d, With(h1, ""), srv.URL); got != "HTTP/1.1" {
t.Errorf("With dropped OverHTTP1: spoken %s", got)
}
if got := protoOf(t, d, context.Background(), srv.URL); got != "HTTP/2.0" {
t.Errorf("not asked, spoken %s", got)
}
}
// AgainOverHTTP1 tries once more over HTTP/1.1 after a transfer an
// HTTP/2 stream reset broke off, and not after a failure of another kind
// or a context that ended.
func TestAgainOverHTTP1(t *testing.T) {
clearProxyEnv(t)
srv, d := h2Server(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1000000")
io.WriteString(w, strings.Repeat("x", 4096))
w.(http.Flusher).Flush()
if r.ProtoMajor == 2 {
panic(http.ErrAbortHandler)
}
io.WriteString(w, strings.Repeat("x", 1000000-4096))
})
c := &http.Client{Transport: d}
var protos []string
get := func(ctx context.Context) error {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
res, err := c.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
protos = append(protos, res.Proto)
_, err = io.Copy(io.Discard, res.Body)
return err
}
if err := AgainOverHTTP1(context.Background(), get); err != nil {
t.Fatalf("AgainOverHTTP1: %v (protos %q)", err, protos)
}
if fmt.Sprint(protos) != "[HTTP/2.0 HTTP/1.1]" {
t.Fatalf("protos = %q", protos)
}
n := 0
notNet := errors.New("checksum")
AgainOverHTTP1(context.Background(), func(context.Context) error { n++; return notNet })
ctx, cancel := context.WithCancel(context.Background())
cancel()
AgainOverHTTP1(ctx, func(context.Context) error { n++; return io.ErrUnexpectedEOF })
if n != 2 {
t.Fatalf("tried %d times, want 2 (no second try)", n)
}
}
func TestBrokeOff(t *testing.T) {
for _, err := range []error{
io.ErrUnexpectedEOF,
fmt.Errorf("read: %w", syscall.ECONNRESET),
errors.New("stream error: stream ID 1; INTERNAL_ERROR; received from peer"),
errors.New("http2: server sent GOAWAY and closed the connection"),
errors.New("http2: client connection lost"),
} {
if !BrokeOff(err) {
t.Errorf("BrokeOff(%v) = false", err)
}
}
for _, err := range []error{nil, context.Canceled, fmt.Errorf("x: %w", context.DeadlineExceeded), errors.New("download magpie: 404 Not Found")} {
if BrokeOff(err) {
t.Errorf("BrokeOff(%v) = true", err)
}
}
}
+10
View File
@@ -254,6 +254,16 @@ func fetch(ctx context.Context, url, path string, size int64, want string, done
}
if size < 0 || have < size {
got, err := get(ctx, url, part, have, done)
if err != nil && ctx.Err() == nil && netproxy.BrokeOff(err) {
// once more over HTTP/1.1, from what is on disk: a proxy
// that cuts HTTP/2 streams part way carries HTTP/1.1 whole
// (netproxy.OverHTTP1)
have = 0
if fi, serr := os.Stat(part); serr == nil {
have = fi.Size()
}
got, err = get(netproxy.OverHTTP1(ctx), url, part, have, done)
}
if err != nil {
return err
}
+12
View File
@@ -342,7 +342,19 @@ func getURLOfficial(ctx context.Context, url string, limit int64) ([]byte, error
return getURLFrom(ctx, url, limit, false)
}
// getURLFrom reads url, once more over HTTP/1.1 when the connection broke
// off (netproxy.AgainOverHTTP1): Bun's zip is tens of MB, which a proxy
// that cuts HTTP/2 streams part way breaks on each try over HTTP/2.
func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) {
var b []byte
err := netproxy.AgainOverHTTP1(ctx, func(ctx context.Context) (err error) {
b, err = getURLOnce(ctx, url, limit, mirror)
return err
})
return b, err
}
func getURLOnce(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
+8 -1
View File
@@ -32,6 +32,7 @@ import (
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
)
@@ -172,8 +173,14 @@ func grokOpen(ctx context.Context, u string) (*http.Response, error) {
return res, nil
}
// grokDownload writes what u has to path, unpacked when gzipped.
// grokDownload writes what u has to path, unpacked when gzipped, once
// more over HTTP/1.1 when the connection broke off
// (netproxy.AgainOverHTTP1).
func grokDownload(ctx context.Context, u, path string, gzipped bool) error {
return netproxy.AgainOverHTTP1(ctx, func(ctx context.Context) error { return grokDownloadOnce(ctx, u, path, gzipped) })
}
func grokDownloadOnce(ctx context.Context, u, path string, gzipped bool) error {
res, err := grokOpen(ctx, u)
if err != nil {
return err
+79
View File
@@ -0,0 +1,79 @@
package update
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/netproxy"
)
// biubiu8802 on X: a proxy that cuts every HTTP/2 stream part way, while
// it carries HTTP/1.1 to the same host whole. Each try of the update broke
// off the same way ("unexpected EOF"), as each went over HTTP/2 again; the
// tries after the first go over HTTP/1.1, and on from where it broke off.
func TestDownloadBrokenOverHTTP2TriesHTTP1(t *testing.T) {
quickRetries(t)
body := make([]byte, 512<<10)
for i := range body {
body[i] = byte(i * 13)
}
sum := sha256.Sum256(body)
var mu sync.Mutex
var asked []string // "proto range" of each request
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.Proto+" "+r.Header.Get("Range"))
mu.Unlock()
from := 0
if rg := r.Header.Get("Range"); rg != "" {
from, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rg, "bytes="), "-"))
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", from, len(body)-1, len(body)))
w.Header().Set("Content-Length", strconv.Itoa(len(body)-from))
w.WriteHeader(http.StatusPartialContent)
} else {
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
}
if r.ProtoMajor == 2 {
// the proxy cuts the stream part way: a reset
// (INTERNAL_ERROR) after the first 100KB
w.Write(body[from:min(from+100<<10, len(body))])
w.(http.Flusher).Flush()
panic(http.ErrAbortHandler)
}
w.Write(body[from:])
}))
srv.EnableHTTP2 = true
srv.StartTLS()
defer srv.Close()
pool := x509.NewCertPool()
pool.AddCert(srv.Certificate())
old := client
tr := &http.Transport{ForceAttemptHTTP2: true, TLSClientConfig: &tls.Config{RootCAs: pool}}
client = &http.Client{Transport: netproxy.Dispatch(tr)}
t.Cleanup(func() { client = old; tr.CloseIdleConnections() })
path := filepath.Join(t.TempDir(), "magpie.new")
if err := download(context.Background(), Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path); err != nil {
t.Fatalf("download: %v (asked %q)", err, asked)
}
want := []string{"HTTP/2.0 ", "HTTP/1.1 bytes=102400-"}
if fmt.Sprint(asked) != fmt.Sprint(want) {
t.Fatalf("asked %q, want %q", asked, want)
}
if b, _ := os.ReadFile(path); !bytes.Equal(b, body) {
t.Fatalf("file has %d bytes, not the release's", len(b))
}
}
+7 -2
View File
@@ -1077,8 +1077,8 @@ func WithProgress(ctx context.Context, f func(done, total int64)) context.Contex
var retryWaits = []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 30 * time.Second}
// download fetches a to path and checks its hash. A connection that drops
// is tried again after each of retryWaits, asking with Range for what is
// still missing; the hash is checked over the whole file, the bytes kept
// is tried again after each of retryWaits, over HTTP/1.1 (OverHTTP1),
// asking with Range for what is still missing; the hash is checked over the whole file, the bytes kept
// from the tries before included.
func download(ctx context.Context, a Asset, path string) error {
if a.SHA256 == "" {
@@ -1101,6 +1101,11 @@ func download(ctx context.Context, a Asset, path string) error {
if err = fetch(ctx, a, path); err == nil || ctx.Err() != nil || !Network(err) {
break
}
// the tries after a connection that broke go over HTTP/1.1: a
// proxy that cuts HTTP/2 streams part way cuts every try made
// over it the same way, while HTTP/1.1 through it holds
// (biubiu8802 on X: "unexpected EOF" on each try)
ctx = netproxy.OverHTTP1(ctx)
}
if err != nil {
if cerr := clearFile(path); cerr != nil {