From e484b4ff26168a542d8fd0b6dec783f1ed7c8f47 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 7 Nov 2026 06:08:36 +0800 Subject: [PATCH] update: a slow download still moving is never ended by a total time; Bun, Claude Code and pf-serve too #5572: since 80a47abba a silent download is broken off after 30s and tried again, but the update's download still had a 10-minute total (the update client's Timeout, the GUI run's ctx, `magpie update`'s ctx). A download under ~140 KB/s, still receiving bytes, failed the 83 MB Windows exe at 10 minutes part way. The stall timer is what ends a dead one now; nothing ends one that is still moving. - internal/update: fetch downloads through fileClient, the client without its Timeout. The feed and notes keep the 10-minute client. fetch's stall timer runs from the ask to the last byte, so a server that never answers still ends at stallAfter (30s), and download's retries stay bounded (len(retryWaits)+1 = 6 tries), so a connection that keeps going silent ends in about 4 minutes. - internal/gui (Mac Stage, Windows/Linux StageBinary): run's 10 minutes (checkWait, a var for tests) bound only LatestIn; the download runs under a ctx with no deadline. - internal/cli `magpie update` (Mac Stage, Windows/Linux ReplaceBinary): the same split. - Siblings with the same fixed cap: - new internal/stall: Start(ctx, after) gives a ctx that ends with ErrStalled once `after` goes by with no byte read through w.Reader. - Bun (internal/plugin getURLOnce): watched with a 60s stall; KeepBunUpdated's 10-minute ctx around CheckBun is gone. - Claude Code (internal/claudecode downloadOnce, ~200 MB): watched with a 60s stall; keepOnce's 30-minute ctx around install is gone. - pf-serve (internal/pii upgrade): its 10-minute ctx is gone; get already had a 60s stall and the client a 60s header timeout, as the model's download (no total) does. - Left as they are: plugin installs and npm updates (KeepUpdated's 10 minutes) run `bun install`, whose network is Bun's own, small tarballs; rtk (5 min client), skills (2 min client), skilltree and market reads are small files; Grok CLI install has no cap of its own (its caller's ctx). None of them carries a large download behind a wall-clock total. Run on mote (mote-run), at 49f207c78 + this change; the targeted set again after rebasing on d4a221f79 (ok): - go test ./internal/stall ./internal/update ./internal/claudecode ./internal/pii -run 'Stall|Slow|Silen|TestDownload|TestInstall|TestKeep'; go test ./internal/plugin -run Bun; go test ./internal/gui -run TestUpdate: ok - new: TestSlowButMovingIsReadWhole, TestSilenceIsAStall (no answer, part way), TestDownloadSlowButMovingOutlastsTheClientTimeout (client Timeout 300ms, body ~1.2s: one try, no retry), TestUpdateSlowDownloadOutlastsTheCheckBound (checkWait 200ms, body ~600ms: ready), TestDownloadThatGoesSilentIsAStall (claudecode), TestBunDownloadThatGoesSilentIsAStall. The silent server after its retries stays covered by TestDownloadStallEveryTimeSaysSo (6 tries, errStalled). - go test -race -count=3 ./internal/stall ./internal/update -run 'Stall|Slow|Silen': ok - win-run (Windows 11): ./internal/stall ./internal/update ./internal/claudecode ./internal/plugin with the same -run, and ./internal/gui -run 'TestUpdateSlowDownload|TestUpdateDownloadSaysStepAndSpeed': ok - wsl-run (Ubuntu 24.04), -tags nogui: the same packages and ./internal/gui -run TestUpdate: ok - gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build; GOOS=linux go build -tags nogui; GOOS=windows go build: clean - Full suite: run after the push under the suite lock. Broken by hand: fetch back on `client` fails TestDownloadSlowButMovingOutlastsTheClientTimeout ("broke off ... Client.Timeout or context cancellation while reading body"); the GUI's download back under the check's ctx fails TestUpdateSlowDownloadOutlastsTheCheckBound (state error, "context deadline exceeded"); stall's reader not putting the timer off fails TestSlowButMovingIsReadWhole (50 of 120 bytes); Bun's and Claude Code's downloads unwatched fail their silent tests at the 20s bound ("context deadline exceeded"). Not tried: a real update over a slow or throttled link, on any OS; a real Bun or Claude Code download over one. The Mac's unpack and signature check now run with no deadline (they had the 10 minutes before). Fixes #5572 --- internal/claudecode/claudecode.go | 14 +++++- internal/claudecode/claudecode_test.go | 24 +++++++++ internal/claudecode/keep.go | 10 ++-- internal/cli/update_cli.go | 9 ++-- internal/gui/update.go | 12 ++++- internal/gui/update_progress_test.go | 63 +++++++++++++++++++++++ internal/pii/fetch.go | 6 +-- internal/plugin/bun.go | 13 ++++- internal/plugin/bunupdate.go | 7 +-- internal/plugin/bunupdate_test.go | 22 ++++++++ internal/stall/stall.go | 66 ++++++++++++++++++++++++ internal/stall/stall_test.go | 69 ++++++++++++++++++++++++++ internal/update/download_test.go | 47 ++++++++++++++++++ internal/update/update.go | 16 +++++- 14 files changed, 356 insertions(+), 22 deletions(-) create mode 100644 internal/stall/stall.go create mode 100644 internal/stall/stall_test.go diff --git a/internal/claudecode/claudecode.go b/internal/claudecode/claudecode.go index 3dcf9b55d..d0e404f18 100644 --- a/internal/claudecode/claudecode.go +++ b/internal/claudecode/claudecode.go @@ -26,11 +26,13 @@ import ( "runtime" "strconv" "strings" + "time" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/libc" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/stall" ) // Base is where Anthropic publishes Claude Code's builds, as its installer @@ -273,7 +275,15 @@ func download(ctx context.Context, r Release, to string, progress func(int64)) e 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 { +// downloadStall is how long a download waits for its next byte. There is +// no bound on the whole: a slow link still moving finishes the ~200 MB +// build (#5572). A var for tests. +var downloadStall = 60 * time.Second + +func downloadOnce(ctx context.Context, r Release, to string, progress func(int64)) (err error) { + ctx, w := stall.Start(ctx, downloadStall) + defer w.Stop() + defer func() { err = w.Err(err) }() req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.URL, nil) if err != nil { return err @@ -291,7 +301,7 @@ func downloadOnce(ctx context.Context, r Release, to string, progress func(int64 return err } h := sha256.New() - n, err := io.Copy(io.MultiWriter(out, h, progressWriter(progress)), io.LimitReader(res.Body, r.Size+1)) + n, err := io.Copy(io.MultiWriter(out, h, progressWriter(progress)), io.LimitReader(w.Reader(res.Body), r.Size+1)) if cerr := out.Close(); err == nil { err = cerr } diff --git a/internal/claudecode/claudecode_test.go b/internal/claudecode/claudecode_test.go index 449dabd01..77b988307 100644 --- a/internal/claudecode/claudecode_test.go +++ b/internal/claudecode/claudecode_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "net/http" "net/http/httptest" @@ -12,7 +13,9 @@ import ( "runtime" "strings" "testing" + "time" + "github.com/yetone/magpie/internal/stall" "github.com/yetone/magpie/internal/testenv" ) @@ -212,3 +215,24 @@ func TestFindTakesTheMachinesOwnFirst(t *testing.T) { t.Errorf("with its own on PATH, Find() = %q, want that one", p) } } + +// A build download has no bound on the whole (#5572); one whose server +// goes silent part way is ended by the stall, said as one. +func TestDownloadThatGoesSilentIsAStall(t *testing.T) { + old := downloadStall + downloadStall = 100 * time.Millisecond + t.Cleanup(func() { downloadStall = old }) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1000") + w.Write([]byte("#!/bin/sh\n")) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + err := download(ctx, Release{URL: srv.URL, Size: 1000, Checksum: "00"}, filepath.Join(t.TempDir(), "claude"), nil) + if !errors.Is(err, stall.ErrStalled) || ctx.Err() != nil { + t.Fatalf("err = %v, want a stall", err) + } +} diff --git a/internal/claudecode/keep.go b/internal/claudecode/keep.go index 2be75f9cf..e543ebcc9 100644 --- a/internal/claudecode/keep.go +++ b/internal/claudecode/keep.go @@ -70,11 +70,11 @@ func keepOnce(ctx context.Context) (string, error) { if !newer(r.Version, v) { return "", nil } - dctx, cancel := context.WithTimeout(ctx, 30*time.Minute) - defer cancel() - // the old version stays until the next look: a run being started now - // may have been handed its path - if _, err := install(dctx, r, nil); err != nil { + // no bound on the whole: a slow download still moving finishes, and + // one that stops sending is ended by downloadStall (#5572). The old + // version stays until the next look: a run being started now may have + // been handed its path + if _, err := install(ctx, r, nil); err != nil { return "", fmt.Errorf("Claude Code %s: %w", r.Version, err) } return fmt.Sprintf("Claude Code: magpie's download updated from %s to %s", v, r.Version), nil diff --git a/internal/cli/update_cli.go b/internal/cli/update_cli.go index 0a72d9e6a..ab6060bf2 100644 --- a/internal/cli/update_cli.go +++ b/internal/cli/update_cli.go @@ -190,10 +190,13 @@ func updateCmd(args []string) error { if len(args) > 2 || len(args) == 2 && args[1] != "check" { return fmt.Errorf("usage: magpie update [check] [--proxy ] [--mirror ]") } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + // the check is bounded; the download after it is not: a slow one + // still moving goes on, and one that stops sending is ended by + // update's stall timer (#5572) + ctx := update.WithMirror(update.WithProxy(context.Background(), proxy), mirror) + cctx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() - ctx = update.WithMirror(update.WithProxy(ctx, proxy), mirror) - rel, err := update.Latest(ctx) + rel, err := update.Latest(cctx) if err != nil { return err } diff --git a/internal/gui/update.go b/internal/gui/update.go index 48d91d583..9b665cbdd 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -396,8 +396,16 @@ func (u *updater) begin() bool { return true } +// checkWait bounds asking the feed. The download after it has no total +// bound: a slow one still moving goes on, and one that stops sending is +// ended by update's stall timer, tried again a bounded number of times +// (#5572: an 83 MB download under ~140 KB/s failed at 10 minutes part +// way). A var for tests. +var checkWait = 10 * time.Minute + func (u *updater) run() { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + ctx := context.Background() + cctx, cancel := context.WithTimeout(ctx, checkWait) defer cancel() s := settings.Load() u.mu.Lock() @@ -410,7 +418,7 @@ func (u *updater) run() { lang = notesLang(trayLang(s.Lang, systemLang)) } stable := s.UpdateChannel == settings.UpdateStable - rel, err := update.LatestIn(ctx, lang) + rel, err := update.LatestIn(cctx, lang) u.mu.Lock() defer u.mu.Unlock() if err == nil && u.latest != nil && update.Newer(u.latest.Version, rel.Version) { diff --git a/internal/gui/update_progress_test.go b/internal/gui/update_progress_test.go index 328c750fa..f1cfa429e 100644 --- a/internal/gui/update_progress_test.go +++ b/internal/gui/update_progress_test.go @@ -125,3 +125,66 @@ func TestUpdateSpeedFallsWhenStalled(t *testing.T) { t.Fatalf("marks after the bytes went back = %d, want 1", len(m)) } } + +// The update's check is bounded (checkWait), its download isn't: one +// still moving past that bound finishes (#5572, an 83 MB download under +// ~140 KB/s failed at 10 minutes part way). Here the bound is 200ms and +// the bytes take ~600ms. +func TestUpdateSlowDownloadOutlastsTheCheckBound(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + old := checkWait + checkWait = 200 * time.Millisecond + t.Cleanup(func() { checkWait = old }) + + const chunk, chunks = 4 << 10, 10 + body := make([]byte, chunk*chunks) + for i := range body { + body[i] = byte(i * 5) + } + sum := sha256.Sum256(body) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/asset" { + for i := 0; i < chunks; i++ { + if _, err := w.Write(body[i*chunk : (i+1)*chunk]); err != nil { + return + } + w.(http.Flusher).Flush() + time.Sleep(60 * time.Millisecond) + } + return + } + json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", Assets: map[string]update.Asset{ + update.BinaryAsset(): {URL: "http://" + r.Host + "/asset", Size: int64(len(body)), SHA256: hex.EncodeToString(sum[:])}, + }}) + })) + defer srv.Close() + t.Setenv("MAGPIE_UPDATE_FEED", srv.URL) + oldV := Version + Version = "0.1.10" + defer func() { Version = oldV }() + exe, err := update.Executable() + if err != nil { + t.Fatal(err) + } + u := &updater{exe: exe} + u.self, _ = os.Stat(exe) + defer func() { + u.mu.Lock() + staged := u.staged + u.mu.Unlock() + if staged != "" { + os.Remove(staged) + } + }() + if !u.begin() { + t.Fatal("no check began") + } + u.run() + if j := u.json(); j.State != "ready" { + t.Fatalf("after the download: %+v", j) + } +} diff --git a/internal/pii/fetch.go b/internal/pii/fetch.go index 347f43d19..6790651ea 100644 --- a/internal/pii/fetch.go +++ b/internal/pii/fetch.go @@ -160,9 +160,9 @@ func upgrade() { return } defer upgrading.Store(false) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) - defer cancel() - if err := ensureServe(ctx); err != nil { + // no bound on the whole, as the model's download has none: get's + // stall timer ends one that stops sending (#5572) + if err := ensureServe(context.Background()); err != nil { return } stopWhenFree() diff --git a/internal/plugin/bun.go b/internal/plugin/bun.go index 91792a65c..a7b7b342c 100644 --- a/internal/plugin/bun.go +++ b/internal/plugin/bun.go @@ -27,6 +27,7 @@ import ( "github.com/yetone/magpie/internal/libc" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/source" + "github.com/yetone/magpie/internal/stall" ) // BunVersion is the Bun magpie downloads to run plugins with the first @@ -354,7 +355,15 @@ func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]by return b, err } -func getURLOnce(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) { +// downloadStall is how long a download from Bun's release waits for its +// next byte; there is no bound on the whole, so a slow link still moving +// finishes (#5572). A var for tests. +var downloadStall = 60 * time.Second + +func getURLOnce(ctx context.Context, url string, limit int64, mirror bool) (b []byte, err error) { + ctx, w := stall.Start(ctx, downloadStall) + defer w.Stop() + defer func() { err = w.Err(err) }() req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err @@ -374,7 +383,7 @@ func getURLOnce(ctx context.Context, url string, limit int64, mirror bool) ([]by if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s: %s", url, res.Status) } - b, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) + b, err = io.ReadAll(io.LimitReader(w.Reader(res.Body), limit+1)) if err != nil { return nil, err } diff --git a/internal/plugin/bunupdate.go b/internal/plugin/bunupdate.go index 649afe73d..73970fd02 100644 --- a/internal/plugin/bunupdate.go +++ b/internal/plugin/bunupdate.go @@ -310,11 +310,12 @@ func KeepBunUpdated(ctx context.Context) { case <-t.C: } if len(Load().Plugins) > 0 && HasBun() { - cctx, cancel := context.WithTimeout(ctx, 10*time.Minute) - if _, err := CheckBun(cctx); err != nil { + // no bound on the whole: a slow download still moving + // finishes, and one that stops sending is ended by + // downloadStall (#5572) + if _, err := CheckBun(ctx); err != nil { log.Printf("plugins: looking for a newer Bun: %s", err) } - cancel() } t.Reset(bunEvery) } diff --git a/internal/plugin/bunupdate_test.go b/internal/plugin/bunupdate_test.go index f47061903..a8528999e 100644 --- a/internal/plugin/bunupdate_test.go +++ b/internal/plugin/bunupdate_test.go @@ -18,6 +18,7 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/stall" "github.com/yetone/magpie/internal/testenv" ) @@ -346,3 +347,24 @@ func TestDownloadBunDefaultSkipsOfficialSums(t *testing.T) { t.Fatalf("zip asked %d times", zipAsked.Load()) } } + +// Bun's download has no bound on the whole (#5572); a server that goes +// silent part way is ended by the stall, said as one. +func TestBunDownloadThatGoesSilentIsAStall(t *testing.T) { + old := downloadStall + downloadStall = 100 * time.Millisecond + t.Cleanup(func() { downloadStall = old }) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1000") + w.Write([]byte("PK")) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + _, err := getURL(ctx, srv.URL+"/bun.zip", 1<<20) + if !errors.Is(err, stall.ErrStalled) || ctx.Err() != nil { + t.Fatalf("err = %v, want a stall", err) + } +} diff --git a/internal/stall/stall.go b/internal/stall/stall.go new file mode 100644 index 000000000..238f94cc1 --- /dev/null +++ b/internal/stall/stall.go @@ -0,0 +1,66 @@ +// Package stall ends a download that stops sending, and never one that is +// still moving, however slowly. A wall-clock cap on a whole download +// failed a slow link part way while its bytes were still coming (#5572: +// the 83 MB Windows update under ~140 KB/s against 10 minutes). +package stall + +import ( + "context" + "errors" + "fmt" + "io" + "time" +) + +// ErrStalled is a download that got no byte for its Watch's while. +var ErrStalled = errors.New("no data came for a while") + +// Watch is one download's idle timer. +type Watch struct { + after time.Duration + t *time.Timer + ctx context.Context + cancel context.CancelCauseFunc +} + +// Start returns a ctx under ctx that ends, its cause ErrStalled, once +// after goes by with no byte read through w.Reader. The timer runs from +// now: a server that never answers ends the same way. Stop it when the +// download is over. +func Start(ctx context.Context, after time.Duration) (context.Context, *Watch) { + c, cancel := context.WithCancelCause(ctx) + w := &Watch{after: after, ctx: c, cancel: cancel} + w.t = time.AfterFunc(after, func() { cancel(ErrStalled) }) + return c, w +} + +// Reader is r, each byte read from it putting the stall off again. +func (w *Watch) Reader(r io.Reader) io.Reader { return &reader{r: r, w: w} } + +// Stop ends the watch and the ctx Start gave. +func (w *Watch) Stop() { + w.t.Stop() + w.cancel(nil) +} + +// Err is err, said as a stall (wrapping ErrStalled) when the watch is +// what ended the download. +func (w *Watch) Err(err error) error { + if err != nil && errors.Is(context.Cause(w.ctx), ErrStalled) { + return fmt.Errorf("%w (nothing for %s)", ErrStalled, w.after) + } + return err +} + +type reader struct { + r io.Reader + w *Watch +} + +func (r *reader) Read(p []byte) (int, error) { + n, err := r.r.Read(p) + if n > 0 { + r.w.t.Reset(r.w.after) + } + return n, err +} diff --git a/internal/stall/stall_test.go b/internal/stall/stall_test.go new file mode 100644 index 000000000..af0e249a5 --- /dev/null +++ b/internal/stall/stall_test.go @@ -0,0 +1,69 @@ +package stall + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func get(ctx context.Context, url string, after time.Duration) (int, error) { + ctx, w := Start(ctx, after) + defer w.Stop() + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + res, err := http.DefaultClient.Do(req) + if err != nil { + return 0, w.Err(err) + } + defer res.Body.Close() + b, err := io.ReadAll(w.Reader(res.Body)) + return len(b), w.Err(err) +} + +// A body that keeps coming, slowly, for many times the stall's while is +// read whole: only silence ends it (#5572). +func TestSlowButMovingIsReadWhole(t *testing.T) { + const chunks = 12 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for i := 0; i < chunks; i++ { + if _, err := w.Write([]byte("0123456789")); err != nil { + return + } + w.(http.Flusher).Flush() + time.Sleep(50 * time.Millisecond) + } + })) + defer srv.Close() + n, err := get(context.Background(), srv.URL, 250*time.Millisecond) + if err != nil || n != chunks*10 { + t.Fatalf("got %d bytes, err %v; want %d", n, err, chunks*10) + } +} + +// A server that says nothing, before its answer or part way through it, +// ends with ErrStalled. +func TestSilenceIsAStall(t *testing.T) { + for name, h := range map[string]http.HandlerFunc{ + "no answer": func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }, + "part way": func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "100") + w.Write([]byte("0123456789")) + w.(http.Flusher).Flush() + <-r.Context().Done() + }, + } { + t.Run(name, func(t *testing.T) { + srv := httptest.NewServer(h) + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + _, err := get(ctx, srv.URL, 100*time.Millisecond) + if !errors.Is(err, ErrStalled) || ctx.Err() != nil { + t.Fatalf("err = %v, want a stall", err) + } + }) + } +} diff --git a/internal/update/download_test.go b/internal/update/download_test.go index c5dce902b..5692fc5af 100644 --- a/internal/update/download_test.go +++ b/internal/update/download_test.go @@ -292,3 +292,50 @@ func TestDownloadStallEveryTimeSaysSo(t *testing.T) { t.Fatalf("tries = %d, want %d", n, len(retryWaits)+1) } } + +// A download still moving, however slowly, is never ended by a total time +// (#5572: the 83 MB Windows exe under ~140 KB/s failed at the client's 10 +// minutes). Here the feed's client gives up after 300ms and the body +// takes ~1.2s, a byte every 100ms well inside the stall's while: one try +// reads it whole, with no break and no retry. +func TestDownloadSlowButMovingOutlastsTheClientTimeout(t *testing.T) { + quickRetries(t) + oldStall, oldClient := stallAfter, client + stallAfter = time.Second + client = &http.Client{Timeout: 300 * time.Millisecond, Transport: oldClient.Transport} + t.Cleanup(func() { stallAfter, client = oldStall, oldClient }) + const chunk, chunks = 4 << 10, 12 + body := make([]byte, chunk*chunks) + for i := range body { + body[i] = byte(i * 11) + } + sum := sha256.Sum256(body) + var tries atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tries.Add(1) + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + for i := 0; i < chunks; i++ { + if _, err := w.Write(body[i*chunk : (i+1)*chunk]); err != nil { + return + } + w.(http.Flusher).Flush() + time.Sleep(100 * time.Millisecond) + } + })) + defer srv.Close() + var steps []string + ctx := WithStep(context.Background(), func(s string) { steps = append(steps, s) }) + path := filepath.Join(t.TempDir(), "magpie.new") + if err := download(ctx, Asset{URL: srv.URL, Size: int64(len(body)), SHA256: hex.EncodeToString(sum[:])}, path); err != nil { + t.Fatalf("a moving download failed: %v", err) + } + if n := tries.Load(); n != 1 { + t.Fatalf("asked %d times, want one try that wasn't broken off", n) + } + if want := []string{StepDownload, StepVerify}; !slices.Equal(steps, want) { + t.Fatalf("steps = %q, want %q", steps, want) + } + if b, _ := os.ReadFile(path); !bytes.Equal(b, body) { + t.Fatalf("file has %d bytes, not the release's", len(b)) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 922f76035..15132ec58 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -69,9 +69,21 @@ type Asset struct { // client asks the feed and downloads a release through the proxy the rest // of magpie's requests take — Settings' Proxy, else the environment's, else // the system's (#294) — on a transport of its own, whatever the process has -// done to http.DefaultTransport. +// done to http.DefaultTransport. Its Timeout bounds the feed's small +// answers; a release's file goes through fileClient, which has none. var client = &http.Client{Timeout: 10 * time.Minute, Transport: proxied()} +// fileClient is client without its total Timeout, for a release's file: a +// slow download still moving goes on however long it takes, and one that +// stops sending is ended by fetch's stall timer (stallAfter) instead. The +// Timeout failed an 83 MB Windows download under ~140 KB/s at 10 minutes, +// part way and still coming (#5572). +func fileClient() *http.Client { + c := *client + c.Timeout = 0 + return &c +} + func proxied() http.RoundTripper { t := http.DefaultTransport.(*http.Transport).Clone() t.Proxy = netproxy.Func @@ -1258,7 +1270,7 @@ func fetch(ctx context.Context, a Asset, path string) error { if have > 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have)) } - res, err = source.Do(client, req) + res, err = source.Do(fileClient(), req) if err != nil { if ctx.Err() != nil { return fail(err)