diff --git a/downloader.go b/downloader.go index e89063c..f6073e3 100644 --- a/downloader.go +++ b/downloader.go @@ -13,7 +13,6 @@ import ( "io" "net/http" "os" - "sync" "sync/atomic" "time" ) @@ -146,26 +145,31 @@ func DownloadWithConfig(ctx context.Context, file string, reqURL string, config completed.Store(localSize) } if config.PollFunction != nil { - var updateLock sync.Mutex update := func() { - updateLock.Lock() - defer updateLock.Unlock() config.PollFunction(completed.Load(), remoteSize) } // send initial update update() - interval := cmp.Or(config.PollInterval.Abs(), 250*time.Millisecond) - var t *time.Timer - t = time.AfterFunc(interval, func() { - // send intermediate updates - update() - t.Reset(interval) - }) + ticker := time.NewTicker(cmp.Or(config.PollInterval.Abs(), 250*time.Millisecond)) + stop := make(chan struct{}) + go func() { + for { + select { + case <-ticker.C: + // send intermediate updates + update() + case <-stop: + return + } + } + }() defer func() { - t.Stop() + ticker.Stop() + // unbuffered send: returns when the polling goroutine receives it and exits + stop <- struct{}{} // send final update update() }() diff --git a/downloader_test.go b/downloader_test.go index c44761f..9ec2c93 100644 --- a/downloader_test.go +++ b/downloader_test.go @@ -14,6 +14,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "sync/atomic" "testing" "time" @@ -373,3 +374,38 @@ func TestInactivityTimeout(t *testing.T) { // Check that it took around 1 second (initial burst of data 500ms + 500ms second timeout) require.InEpsilon(t, 1000*time.Millisecond, elapsed, 0.05, "Elapsed time should be around 1 second, but is %v", elapsed) } + +func TestPollFunctionNotCalledAfterReturn(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "50") + if r.Method == "HEAD" { + return + } + for range 10 { + time.Sleep(10 * time.Millisecond) + fmt.Fprintf(w, "AAAAA") + w.(http.Flusher).Flush() + } + }) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + for range 20 { + var returned atomic.Bool + var lateCalls atomic.Int32 + err := downloader.DownloadWithConfig(t.Context(), makeTmpFile(t), server.URL+"/slow", downloader.Config{ + PollInterval: time.Nanosecond, + PollFunction: func(current, size int64) { + if returned.Load() { + lateCalls.Add(1) + } + }, + }) + require.NoError(t, err) + returned.Store(true) + + time.Sleep(20 * time.Millisecond) + require.Zero(t, lateCalls.Load(), "PollFunction called after DownloadWithConfig returned") + } +}