Files
magpie/internal/update/download_test.go
T
yetone 6335625a60 update: a download that breaks off is tried five more times, from where it stopped
AIMetaPhD on X: on Windows, 0.1.1615 couldn't download 0.1.1618;
GitHub's asset host dropped the connection ("EOF"). The download was
tried three times, two and four seconds apart, each time from byte zero,
and then it gave up. The error also carried the full signed redirect
URL, which the GUI showed.

Now a try the network breaks off (the connect, or the body part way) is
tried again after 2, 4, 8, 16 and 30 seconds. Each later try asks with
Range for the bytes still missing. A host that sends 200 instead has the
file written again from the start, and a 206 whose Content-Range doesn't
start where the file ends is refused. The SHA-256 from the feed is
checked over the whole file read back from disk, so the bytes from
earlier tries are covered. A failure that isn't the network's (a 404, a
checksum mismatch, a write that fails) is not tried again, and the file
is removed. The error is a NetError that names the file and the cause
("the download of magpie.exe.new broke off (EOF)"), never the address.

Release timing was checked and is not the cause. v0.1.1618's
magpie-releases release was created at 16:32:48Z, its assets were
uploaded from 16:36:13Z to 16:36:17Z, and it was published at
16:36:18Z. The feed reads only releases/latest, which skips drafts, and
needs SHA256SUMS, so it couldn't name 1618 before its files were there.
The URL in the screenshot is the asset host's redirect, which exists
only for an uploaded asset.

Run: go test ./internal/update ./internal/cli (ok); gofmt -l clean;
GOOS=linux and GOOS=windows go vet ./internal/update. New tests run on
httptest servers: a body cut mid-stream twice (resumed with
bytes=102400- and bytes=307200-, file and progress whole), a resume
with the wrong bytes (checksum fails, nothing kept), a connection hung
up before any answer behind a redirect to a ?sig=&jwt= URL (six tries,
and the error holds no URL), and a 404 (one try).

Broken by hand: without the Range header the resume test is red
(ranges "" "" ""); with the NetError keeping the url.Error the address
test is red (the signed URL in the text); with three tries it is red
(tries = 3, want 6).

Not tried: a real self-update on this machine or the Windows box, or a
real cut connection to GitHub. The China mirror and the user's
UpdateMirror get the same Range header; a mirror that ignores it sends
200 and the file is written again from the start.
2026-10-27 01:34:26 +08:00

200 lines
6.7 KiB
Go

package update
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
)
// A download that drops part way is tried again, and reports its progress.
func TestDownloadRetriesAndReports(t *testing.T) {
body := make([]byte, 256<<10)
for i := range body {
body[i] = byte(i)
}
sum := sha256.Sum256(body)
tries := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tries++
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
if tries == 1 {
w.Write(body[:1000]) // then the connection goes
return
}
w.Write(body)
}))
defer srv.Close()
var done, total int64
ctx := WithProgress(context.Background(), func(d, t int64) { done, total = d, t })
path := filepath.Join(t.TempDir(), "magpie.new")
if err := download(ctx, Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path); err != nil {
t.Fatal(err)
}
if tries != 2 {
t.Fatalf("tries = %d, want 2", tries)
}
if done != int64(len(body)) || total != int64(len(body)) {
t.Fatalf("progress = %d/%d, want %d/%d", done, total, len(body), len(body))
}
if b, _ := os.ReadFile(path); len(b) != len(body) {
t.Fatalf("file has %d bytes", len(b))
}
}
// quickRetries has download's tries follow each other at once.
func quickRetries(t *testing.T) {
t.Helper()
old := retryWaits
retryWaits = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond}
t.Cleanup(func() { retryWaits = old })
}
// A download the connection cuts part way goes on from where it broke
// off: the next try asks for the rest with Range, and the hash is checked
// over the whole file, the bytes of the first try included.
func TestDownloadResumesWhereItBrokeOff(t *testing.T) {
quickRetries(t)
body := make([]byte, 512<<10)
for i := range body {
body[i] = byte(i * 7)
}
sum := sha256.Sum256(body)
var ranges []string
cut := []int{100 << 10, 300 << 10} // where the first two tries break off
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ranges = append(ranges, r.Header.Get("Range"))
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)))
}
to := len(body)
if n := len(ranges) - 1; n < len(cut) {
to = cut[n]
}
w.Write(body[from:to])
if to < len(body) {
w.(http.Flusher).Flush()
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close() // mid-stream
}
}))
defer srv.Close()
var done, total int64
ctx := WithProgress(context.Background(), func(d, t int64) { done, total = d, t })
path := filepath.Join(t.TempDir(), "magpie.new")
if err := download(ctx, Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path); err != nil {
t.Fatal(err)
}
want := []string{"", "bytes=102400-", "bytes=307200-"}
if !slices.Equal(ranges, want) {
t.Fatalf("ranges asked = %q, want %q", ranges, want)
}
if b, _ := os.ReadFile(path); !bytes.Equal(b, body) {
t.Fatalf("file has %d bytes, not the release's", len(b))
}
if done != int64(len(body)) || total != int64(len(body)) {
t.Fatalf("progress = %d/%d, want %d/%d", done, total, len(body), len(body))
}
}
// The rest of a file sent with other bytes than the release's (a host
// that resumes wrongly) fails the hash, which covers the whole file, and
// nothing is kept.
func TestDownloadResumedFileIsStillChecked(t *testing.T) {
quickRetries(t)
body := bytes.Repeat([]byte("magpie"), 50<<10)
sum := sha256.Sum256(body)
tries := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tries++
if tries == 1 {
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.Write(body[:1000])
w.(http.Flusher).Flush()
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close()
return
}
w.Header().Set("Content-Range", fmt.Sprintf("bytes 1000-%d/%d", len(body)-1, len(body)))
w.WriteHeader(http.StatusPartialContent)
w.Write(bytes.Repeat([]byte("x"), len(body)-1000))
}))
defer srv.Close()
path := filepath.Join(t.TempDir(), "magpie.new")
err := download(context.Background(), Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path)
if err == nil || !strings.Contains(err.Error(), "does not match its checksum") {
t.Fatalf("err = %v, want a checksum mismatch", err)
}
if _, serr := os.Stat(path); !os.IsNotExist(serr) {
t.Fatal("the mismatched file was kept")
}
}
// A connection dropped before any answer (EOF at the connect, what the
// reporter's Windows box got from GitHub's asset host) is tried again
// every time retryWaits allows, and the error that ends it names the file
// and the cause, not the signed address it was redirected to.
func TestDownloadDroppedConnectionErrorKeepsAddressOut(t *testing.T) {
quickRetries(t)
tries := 0
assets := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tries++
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close() // EOF, no answer at all
}))
defer assets.Close()
signed := assets.URL + "/github-production-release-asset/1?sig=SECRETSIG&jwt=SECRETJWT"
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, signed, http.StatusFound)
}))
defer gh.Close()
path := filepath.Join(t.TempDir(), "magpie.new")
err := download(context.Background(), Asset{URL: gh.URL + "/magpie-windows-amd64.exe", SHA256: "00"}, path)
if err == nil || !Network(err) {
t.Fatalf("err = %v, want a network error", err)
}
if tries != len(retryWaits)+1 {
t.Fatalf("tries = %d, want %d", tries, len(retryWaits)+1)
}
if msg := err.Error(); strings.Contains(msg, "SECRET") || strings.Contains(msg, "http") || !strings.Contains(msg, "magpie.new") || !strings.Contains(msg, "EOF") {
t.Fatalf("error = %q", msg)
}
if _, serr := os.Stat(path); !os.IsNotExist(serr) {
t.Fatal("a partial file was kept")
}
}
// A refusal that isn't the network's (404: not uploaded yet) isn't tried
// again and again.
func TestDownloadNotFoundIsNotRetried(t *testing.T) {
quickRetries(t)
tries := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tries++
http.NotFound(w, r)
}))
defer srv.Close()
err := download(context.Background(), Asset{URL: srv.URL, SHA256: "00"}, filepath.Join(t.TempDir(), "magpie.new"))
if err == nil || Network(err) || tries != 1 {
t.Fatalf("err = %v after %d tries, want one 404", err, tries)
}
}