Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"io"
"net/http"
"os"
"sync"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -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()
}()
Expand Down
36 changes: 36 additions & 0 deletions downloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -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")
}
}
Loading