update: a busy download host (502, 503, 504, 500, 429) is tried again

The owner's About page: "0.1.3316 下载失败 · download
magpie-darwin-arm64.zip: 504 Gateway Timeout". Only a connection that
broke was tried again; any status but 200/206 failed the download at
once, though a 504 from GitHub's asset host (or a mirror's) is its edge
timing out, and the next ask usually goes through. Such a reply is now
a NetError: download asks again after each of retryWaits (2s to 30s),
over HTTP/1.1 and keeping what came, as for a dropped connection. When
every try is busy it says "download <file>: 504 Gateway Timeout, on
every try", and the About row says the download broke off, a network
problem, with Check to try again. A 404 or 403 is still asked once.

Run (mote): go test ./internal/update ok; -run Update|Download|Mirror
in internal/gui and internal/cli ok; GOOS=linux and windows go vet
./internal/update ok; gofmt clean.
Broken by hand: with the busy case off, TestDownloadRetriesABusyHost
fails at the first 504 and TestDownloadBusyEveryTryAndMissingOnce sees
1 try of 6.
Not tried: a real 504 from GitHub; the host's answer is faked.
This commit is contained in:
yetone
2026-11-08 17:54:36 +08:00
parent e215d335a6
commit a46190e1f5
2 changed files with 106 additions and 0 deletions
+81
View File
@@ -0,0 +1,81 @@
package update
import (
"context"
"crypto/sha256"
"encoding/hex"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
)
// A host that is busy or whose gateway timed out (GitHub's asset host
// answered 504 Gateway Timeout for 0.1.3316) is asked again, as a
// connection that broke is, and the download goes through once it
// answers.
func TestDownloadRetriesABusyHost(t *testing.T) {
quickRetries(t)
body := []byte(strings.Repeat("magpie", 4096))
sum := sha256.Sum256(body)
for _, code := range []int{http.StatusGatewayTimeout, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusInternalServerError, http.StatusTooManyRequests} {
var tries atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tries.Add(1) <= 2 {
w.WriteHeader(code)
return
}
w.Write(body)
}))
path := filepath.Join(t.TempDir(), "magpie.zip")
err := download(context.Background(), Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path)
srv.Close()
if err != nil {
t.Fatalf("%d: %v", code, err)
}
if n := tries.Load(); n != 3 {
t.Fatalf("%d: tries = %d, want 3", code, n)
}
if b, _ := os.ReadFile(path); string(b) != string(body) {
t.Fatalf("%d: file has %d bytes", code, len(b))
}
}
}
// A host busy on every try fails as the network's, naming the file and
// the status; a file the host hasn't got (404) is asked for once.
func TestDownloadBusyEveryTryAndMissingOnce(t *testing.T) {
quickRetries(t)
for _, c := range []struct {
code int
tries int32
network bool
}{{http.StatusGatewayTimeout, int32(len(retryWaits) + 1), true}, {http.StatusNotFound, 1, false}} {
var tries atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tries.Add(1)
w.WriteHeader(c.code)
}))
path := filepath.Join(t.TempDir(), "magpie-darwin-arm64.zip")
err := download(context.Background(), Asset{URL: srv.URL, SHA256: strings.Repeat("0", 64)}, path)
srv.Close()
if err == nil {
t.Fatalf("%d: no error", c.code)
}
if n := tries.Load(); n != c.tries {
t.Fatalf("%d: tries = %d, want %d", c.code, n, c.tries)
}
if Network(err) != c.network {
t.Fatalf("%d: Network = %v, want %v (%v)", c.code, Network(err), c.network, err)
}
if msg := err.Error(); !strings.Contains(msg, "magpie-darwin-arm64.zip") || !strings.Contains(msg, http.StatusText(c.code)) {
t.Fatalf("%d: error %q names neither the file nor the status", c.code, msg)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("%d: a file is left at %s", c.code, path)
}
}
}
+25
View File
@@ -1197,6 +1197,9 @@ type NetError struct {
}
func (e *NetError) Error() string {
if s, ok := e.Err.(statusError); ok {
return fmt.Sprintf("download %s: %s, on every try", e.File, string(s))
}
cause := e.Err
var ue *url.Error
if errors.As(cause, &ue) {
@@ -1207,6 +1210,23 @@ func (e *NetError) Error() string {
func (e *NetError) Unwrap() error { return e.Err }
// statusError is a reply a host gives when it is busy, not a refusal of
// the file: its status line.
type statusError string
func (s statusError) Error() string { return string(s) }
// busyStatus is a status trying again may get past: the host or its
// gateway overloaded or timed out, or asking for a pause.
func busyStatus(code int) bool {
switch code {
case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway,
http.StatusServiceUnavailable, http.StatusGatewayTimeout:
return true
}
return false
}
// Network reports whether err is a download the network broke off, which
// trying again may get through.
func Network(err error) bool { return errors.As(err, new(*NetError)) }
@@ -1292,6 +1312,11 @@ func fetch(ctx context.Context, a Asset, path string) error {
flag = os.O_WRONLY | os.O_APPEND
case res.StatusCode == http.StatusOK:
have = 0 // the whole file again
case busyStatus(res.StatusCode):
// the host is busy or its edge timed out (GitHub's asset host
// answered 504 Gateway Timeout, 0.1.3316): tried again, as a
// connection that broke, with what came kept
return fail(&NetError{File: name, Err: statusError(res.Status)})
default:
if u != a.URL {
return fail(&MirrorError{Mirror: mirror, Err: fmt.Errorf("download %s through the mirror %s: %s", name, mirror, res.Status)})