mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 21:36:40 -10:00
fetch.Resumable downloads a large file into <path>.part and keeps it
across failures and runs: each retry asks only for the rest (Range, with
If-Range once the server named a strong ETag or Last-Modified, and
Accept-Encoding: identity, so no gzip changes what a range counts), a
try that reads nothing for Stall ends and is tried again, and Tries
tries in a row that bring nothing fail it, as do 100 tries in all, with
the wait doubling up to a minute. The file is kept at its path only once
its SHA-256 checks out; a part that doesn't is fetched again from
nothing, once. A server that ignores the range (200), has nothing past
it (416) or answers it from another byte starts the part again.
- A part that's already the whole file, as a run killed before its
rename or a try that failed after its last byte leaves it, is kept
without another request, where a range past its end would get a 416
and start it again.
- A failure that trying again in this run won't mend (a 403, a proxy
that refuses) keeps the part for the next run; only 404 and 410
(fetch.Gone) and a file over Limit take it with them.
- A part that can't be written, or a whole file that can't be renamed
into place, is ErrWrite, never tried again, and the part's hash and
length count only what the file took, so a short write can't put them
out of step.
- Content-Range is read strictly (parseContentRange, fuzzed), and a
length over Limit fails as ErrTooLarge.
- The structure test's status-lines rule counts a
fetch.Resumable{…}.Download as a request; structure.md says so, and
its internal/fetch row names Resumable.
Tested in a synctest bubble on memnet against a server that cuts,
stalls, hangs, answers 403, 404 or 410, ignores the range or answers it
from byte 0, cuts after the last byte, behind a proxy that refuses, with
a part that can't be written, a whole part left by a killed run and a
file that can't be renamed into place (TestResumableWholePart,
TestResumableRenameFails).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
587 lines
20 KiB
Go
587 lines
20 KiB
Go
package fetch
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"testing/synctest"
|
|
"time"
|
|
|
|
"github.com/devvmhq/devvm/internal/leaktest"
|
|
"github.com/devvmhq/devvm/internal/memnet"
|
|
)
|
|
|
|
// TestMain fails the tests if a goroutine of theirs outlives them: a
|
|
// Resumable try's stall timer included.
|
|
func TestMain(m *testing.M) { leaktest.Main(m) }
|
|
|
|
// flaky serves body at /f as a file server does (Range, If-Range on its
|
|
// ETag), going wrong on its first requests as fail says: each request's
|
|
// Range header is recorded.
|
|
type flaky struct {
|
|
body []byte
|
|
etag string
|
|
// fail is what each request in turn does wrong: "cut" sends a quarter
|
|
// of the body then drops the connection, "stall" sends a quarter then
|
|
// nothing until the client goes, "hang" sends nothing at all until
|
|
// then, "404" answers that, and "whole" sends the whole body (200),
|
|
// whatever range it was asked for; past the list, requests are served.
|
|
// "403" and "410" answer those, and "badrange" answers 206 from byte
|
|
// 0, whatever range it was asked for.
|
|
fail []string
|
|
|
|
mu sync.Mutex
|
|
ranges []string
|
|
encodings []string // each request's Accept-Encoding
|
|
}
|
|
|
|
func (f *flaky) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
n := len(f.ranges)
|
|
f.ranges = append(f.ranges, r.Header.Get("Range"))
|
|
f.encodings = append(f.encodings, r.Header.Get("Accept-Encoding"))
|
|
f.mu.Unlock()
|
|
how := ""
|
|
if n < len(f.fail) {
|
|
how = f.fail[n]
|
|
}
|
|
switch how {
|
|
case "404":
|
|
http.NotFound(w, r)
|
|
return
|
|
case "403":
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
case "410":
|
|
http.Error(w, "gone", http.StatusGone)
|
|
return
|
|
case "badrange":
|
|
w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(f.body)-1, len(f.body)))
|
|
w.WriteHeader(http.StatusPartialContent)
|
|
_, _ = w.Write(f.body)
|
|
return
|
|
case "hang":
|
|
<-r.Context().Done()
|
|
return
|
|
case "endcut":
|
|
// All of it, unsized, then the connection drops: the try fails
|
|
// after its last byte.
|
|
_, _ = w.Write(f.body)
|
|
w.(http.Flusher).Flush()
|
|
panic(http.ErrAbortHandler)
|
|
case "whole":
|
|
_, _ = w.Write(f.body)
|
|
return
|
|
}
|
|
w.Header().Set("ETag", f.etag)
|
|
if how == "" {
|
|
http.ServeContent(w, r, "f", time.Time{}, bytes.NewReader(f.body))
|
|
return
|
|
}
|
|
cw := &cutWriter{ResponseWriter: w, left: len(f.body) / 4}
|
|
http.ServeContent(cw, r, "f", time.Time{}, bytes.NewReader(f.body))
|
|
if how == "stall" {
|
|
<-r.Context().Done()
|
|
}
|
|
panic(http.ErrAbortHandler) // drops the connection
|
|
}
|
|
|
|
// cutWriter writes no more than left bytes of a body, flushed.
|
|
type cutWriter struct {
|
|
http.ResponseWriter
|
|
left int
|
|
}
|
|
|
|
func (c *cutWriter) Write(b []byte) (int, error) {
|
|
if c.left <= 0 {
|
|
return 0, errors.New("cut")
|
|
}
|
|
n := min(len(b), c.left)
|
|
c.left -= n
|
|
n, err := c.ResponseWriter.Write(b[:n])
|
|
if f, ok := c.ResponseWriter.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
if err == nil && c.left <= 0 {
|
|
err = errors.New("cut")
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
// serveFlaky runs f on a network in memory, returning a client that
|
|
// reaches it as http://f and a stop that ends both.
|
|
func serveFlaky(t *testing.T, f *flaky) (c *Client, stop func()) {
|
|
t.Helper()
|
|
var n memnet.Network
|
|
l, err := n.Listen("f:80")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := &http.Server{Handler: f, ReadHeaderTimeout: time.Minute}
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
_ = srv.Serve(l)
|
|
}()
|
|
c = NewClient(time.Hour, SameScheme)
|
|
c.Transport().DialContext = n.DialContext
|
|
c.Transport().Proxy = nil
|
|
return c, func() {
|
|
c.Transport().CloseIdleConnections()
|
|
_ = srv.Close()
|
|
<-done
|
|
}
|
|
}
|
|
|
|
// A Resumable download survives cuts and stalls, asking each retry only
|
|
// for what it lacks, and keeps the file once its SHA-256 checks out.
|
|
func TestResumableDownload(t *testing.T) {
|
|
body := bytes.Repeat([]byte("0123456789abcdef"), 4096)
|
|
sum := sha256.Sum256(body)
|
|
for _, tc := range []struct {
|
|
name string
|
|
fail []string
|
|
sum string
|
|
wantErr error
|
|
wantRanges []string // the first few
|
|
}{
|
|
{name: "whole", wantRanges: []string{""}},
|
|
{name: "cut twice", fail: []string{"cut", "cut"}, wantRanges: []string{"", "bytes=16384-", "bytes=32768-"}},
|
|
{name: "stalled", fail: []string{"stall"}, wantRanges: []string{"", "bytes=16384-"}},
|
|
{name: "a 404 fails at once", fail: []string{"404"}, wantErr: errors.New("404"), wantRanges: []string{""}},
|
|
{name: "a hang is tried again", fail: []string{"hang", "hang"}, wantRanges: []string{"", "", ""}},
|
|
{
|
|
name: "five tries in a row that bring nothing fail it", fail: []string{"cut", "hang", "hang", "hang", "hang", "hang"},
|
|
wantErr: ErrStalled, wantRanges: []string{"", "bytes=16384-", "bytes=16384-"},
|
|
},
|
|
{
|
|
name: "a wrong sum is fetched again once, then fails", sum: strings.Repeat("0", 64), wantErr: ErrChecksum,
|
|
wantRanges: []string{"", ""},
|
|
},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: tc.fail}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
want := tc.sum
|
|
if want == "" {
|
|
want = hex.EncodeToString(sum[:])
|
|
}
|
|
var log bytes.Buffer
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: want, Limit: 1 << 20, Stall: 30 * time.Second, Tries: 5, Delay: time.Second, Log: &log}
|
|
err := d.Download(t.Context(), c)
|
|
// Each failed try that's tried again is a line.
|
|
if n, want := strings.Count(log.String(), "trying again from byte"), max(len(tc.fail)-1, 0); tc.wantErr == nil && n != len(tc.fail) || tc.wantErr != nil && n < want {
|
|
t.Errorf("logged %d retries: %q", n, log.String())
|
|
}
|
|
switch {
|
|
case tc.wantErr == nil && err != nil:
|
|
t.Fatalf("Download: %v", err)
|
|
case tc.wantErr != nil && (err == nil || !errors.Is(err, tc.wantErr) && !strings.Contains(err.Error(), tc.wantErr.Error())):
|
|
t.Fatalf("Download: %v, want %v", err, tc.wantErr)
|
|
}
|
|
f.mu.Lock()
|
|
got := f.ranges
|
|
f.mu.Unlock()
|
|
if len(got) < len(tc.wantRanges) || !slices.Equal(got[:len(tc.wantRanges)], tc.wantRanges) {
|
|
t.Errorf("ranges asked: %q, want %q first", got, tc.wantRanges)
|
|
}
|
|
data, rerr := os.ReadFile(path) //nolint:gosec // the test's own temp folder
|
|
if tc.wantErr == nil && (rerr != nil || !bytes.Equal(data, body)) {
|
|
t.Errorf("the file: %d bytes, %v", len(data), rerr)
|
|
}
|
|
if tc.wantErr != nil && rerr == nil {
|
|
t.Error("a failed download left its file")
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// A part an earlier run left is resumed: only the rest is asked for.
|
|
func TestResumableKeepsPart(t *testing.T) {
|
|
body := bytes.Repeat([]byte("x"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
if err := os.WriteFile(path+".part", body[:4000], 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
if err := d.Download(t.Context(), c); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !slices.Equal(f.ranges, []string{"bytes=4000-"}) {
|
|
t.Errorf("ranges asked: %q", f.ranges)
|
|
}
|
|
if _, err := os.Stat(path + ".part"); !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("the part is still there: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
// What a run left, and a server that won't resume it: a part a server
|
|
// answers with the whole file (200) or has nothing past (416, a part as
|
|
// long as the file but not it) starts again; a part over the limit is
|
|
// dropped first; a file over the limit fails with ErrTooLarge and leaves
|
|
// nothing; an address that isn't one fails at once.
|
|
func TestResumableStartsAgain(t *testing.T) {
|
|
body := bytes.Repeat([]byte("y"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
for _, tc := range []struct {
|
|
name string
|
|
part []byte
|
|
fail []string
|
|
limit int64
|
|
url string
|
|
wantErr error
|
|
wantRanges []string
|
|
}{
|
|
{name: "a range answered whole", part: body[:4000], fail: []string{"whole"}, wantRanges: []string{"bytes=4000-"}},
|
|
{name: "nothing past the part", part: bytes.Repeat([]byte("z"), 10000), wantRanges: []string{"bytes=10000-", ""}},
|
|
{name: "a range answered from elsewhere", part: body[:4000], fail: []string{"badrange"}, wantRanges: []string{"bytes=4000-", ""}},
|
|
{name: "a part over the limit", part: bytes.Repeat([]byte("z"), 20000), limit: 15000, wantRanges: []string{""}},
|
|
{name: "a file over the limit", limit: 5000, wantErr: ErrTooLarge, wantRanges: []string{""}},
|
|
{name: "not an address", url: "http://f/\x7f", wantErr: errRequest},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: tc.fail}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
if tc.part != nil {
|
|
if err := os.WriteFile(path+".part", tc.part, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
d := Resumable{
|
|
URL: cmpOr(tc.url, "http://f/f"), Path: path, SHA256: hex.EncodeToString(sum[:]),
|
|
Limit: cmpOr(tc.limit, 1<<20), Stall: time.Minute, Tries: 3, Delay: time.Second,
|
|
}
|
|
err := d.Download(t.Context(), c)
|
|
if !errors.Is(err, tc.wantErr) {
|
|
t.Fatalf("Download: %v, want %v", err, tc.wantErr)
|
|
}
|
|
f.mu.Lock()
|
|
got := f.ranges
|
|
f.mu.Unlock()
|
|
if !slices.Equal(got, tc.wantRanges) && tc.wantRanges != nil {
|
|
t.Errorf("ranges asked: %q, want %q", got, tc.wantRanges)
|
|
}
|
|
data, rerr := os.ReadFile(path) //nolint:gosec // the test's own temp folder
|
|
if tc.wantErr == nil && !bytes.Equal(data, body) {
|
|
t.Errorf("the file: %d bytes, %v", len(data), rerr)
|
|
}
|
|
if _, err := os.Stat(path + ".part"); tc.wantErr != nil && !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("a download that can't succeed left its part: %v", err)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
t.Run("cancelled while it waits to try again", func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: []string{"cut"}}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
defer cancel()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Minute, Log: cancelling(cancel)}
|
|
if err := d.Download(ctx, c); !errors.Is(err, context.Canceled) {
|
|
t.Errorf("Download = %v, want the context's error", err)
|
|
}
|
|
if fi, err := os.Stat(path + ".part"); err != nil || fi.Size() != int64(len(body)/4) {
|
|
t.Errorf("the part: %v, %v, want what came kept", fi, err)
|
|
}
|
|
})
|
|
})
|
|
t.Run("a part that can't be read", func(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
if err := os.Mkdir(path+".part", 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d := Resumable{URL: "http://f/f", Path: path, Limit: 1, Tries: 1}
|
|
if err := d.Download(t.Context(), NewClient(time.Minute, SameScheme)); err == nil {
|
|
t.Error("Download of a part that's a folder succeeded")
|
|
}
|
|
})
|
|
t.Run("cancelled", func(t *testing.T) {
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
cancel()
|
|
d := Resumable{URL: "http://f/f", Path: filepath.Join(t.TempDir(), "f"), Limit: 1, Tries: 1}
|
|
if err := d.Download(ctx, NewClient(time.Minute, SameScheme)); !errors.Is(err, context.Canceled) {
|
|
t.Errorf("Download = %v, want the context's error", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A failure that trying again in this run won't mend keeps what came for
|
|
// the next run: an answer such as 403, and a proxy that can't be gone
|
|
// through (its password not saved). Only a server that says the file is
|
|
// gone for good (404, 410) takes the part with it.
|
|
func TestResumableKeepsPartOnFailure(t *testing.T) {
|
|
body := bytes.Repeat([]byte("k"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
for _, tc := range []struct {
|
|
name string
|
|
fail []string
|
|
proxy bool // the second request's proxy refuses it
|
|
wantErr error
|
|
wantPart bool
|
|
}{
|
|
{name: "403", fail: []string{"cut", "403"}, wantErr: errors.New("403"), wantPart: true},
|
|
{name: "the proxy refuses", fail: []string{"cut"}, proxy: true, wantErr: ErrProxy, wantPart: true},
|
|
{name: "404", fail: []string{"cut", "404"}, wantErr: errors.New("404")},
|
|
{name: "410", fail: []string{"cut", "410"}, wantErr: errors.New("410")},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: tc.fail}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
if tc.proxy {
|
|
n := 0
|
|
c.Transport().Proxy = func(*http.Request) (*url.URL, error) {
|
|
if n++; n > 1 {
|
|
return nil, fmt.Errorf("company proxy: %w", ErrProxy)
|
|
}
|
|
return nil, nil
|
|
}
|
|
}
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
err := d.Download(t.Context(), c)
|
|
if err == nil || !errors.Is(err, tc.wantErr) && !strings.Contains(err.Error(), tc.wantErr.Error()) {
|
|
t.Fatalf("Download: %v, want %v", err, tc.wantErr)
|
|
}
|
|
fi, serr := os.Stat(path + ".part")
|
|
switch {
|
|
case tc.wantPart && (serr != nil || fi.Size() != int64(len(body)/4)):
|
|
t.Errorf("the part: %v, %v, want what came kept", fi, serr)
|
|
case !tc.wantPart && !errors.Is(serr, os.ErrNotExist):
|
|
t.Errorf("the part of a file that's gone is still there: %v", serr)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// A part that can't be written fails at once, as this machine's own
|
|
// failure rather than the network's: trying again won't mend it.
|
|
func TestResumableWriteFails(t *testing.T) {
|
|
body := bytes.Repeat([]byte("w"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "gone", "f")
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
if err := d.Download(t.Context(), c); !errors.Is(err, ErrWrite) || !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("Download = %v, want ErrWrite with its cause", err)
|
|
}
|
|
if len(f.ranges) != 1 {
|
|
t.Errorf("asked %d times, want once: %q", len(f.ranges), f.ranges)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A part that's already the whole file is kept, never asked for again:
|
|
// what a run killed between its last write and the rename left, and a try
|
|
// that failed after its last byte, which a range would answer with 416
|
|
// and start again from nothing.
|
|
func TestResumableWholePart(t *testing.T) {
|
|
body := bytes.Repeat([]byte("z"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
for _, tc := range []struct {
|
|
name string
|
|
part bool // the whole file is left as the part
|
|
fail []string // the server's
|
|
wantRanges []string
|
|
}{
|
|
{name: "left by a killed run", part: true, wantRanges: nil},
|
|
{name: "a try cut after its last byte", fail: []string{"endcut"}, wantRanges: []string{""}},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: tc.fail}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
if tc.part {
|
|
if err := os.WriteFile(path+".part", body, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
if err := d.Download(t.Context(), c); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !slices.Equal(f.ranges, tc.wantRanges) {
|
|
t.Errorf("ranges asked: %q, want %q", f.ranges, tc.wantRanges)
|
|
}
|
|
if data, err := os.ReadFile(path); err != nil || !bytes.Equal(data, body) { //nolint:gosec // the test's own temp folder
|
|
t.Errorf("the file: %d bytes, %v", len(data), err)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// A file that came whole but can't be put in place fails as this
|
|
// machine's (ErrWrite), with its cause.
|
|
func TestResumableRenameFails(t *testing.T) {
|
|
body := bytes.Repeat([]byte("r"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
path := filepath.Join(t.TempDir(), "f")
|
|
// A folder that isn't empty can't be renamed over.
|
|
if err := os.MkdirAll(filepath.Join(path, "x"), 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d := Resumable{URL: "http://f/f", Path: path, SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
if err := d.Download(t.Context(), c); !errors.Is(err, ErrWrite) {
|
|
t.Errorf("Download = %v, want ErrWrite", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Every try asks for the file as it is (identity), so a server or proxy
|
|
// that would gzip it can't put other bytes in the part than the ones a
|
|
// range counts.
|
|
func TestResumableAsksForIdentity(t *testing.T) {
|
|
body := bytes.Repeat([]byte("i"), 10000)
|
|
sum := sha256.Sum256(body)
|
|
synctest.Test(t, func(t *testing.T) {
|
|
f := &flaky{body: body, etag: `"v1"`, fail: []string{"cut"}}
|
|
c, stop := serveFlaky(t, f)
|
|
defer stop()
|
|
d := Resumable{URL: "http://f/f", Path: filepath.Join(t.TempDir(), "f"), SHA256: hex.EncodeToString(sum[:]), Limit: 1 << 20, Stall: time.Minute, Tries: 3, Delay: time.Second}
|
|
if err := d.Download(t.Context(), c); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !slices.Equal(f.encodings, []string{"identity", "identity"}) {
|
|
t.Errorf("Accept-Encoding asked: %q, want identity each time", f.encodings)
|
|
}
|
|
})
|
|
}
|
|
|
|
// FuzzContentRange: a Content-Range is read only as RFC 9110 writes one,
|
|
// "bytes START-END/LENGTH" or "/*", in plain digits without leading
|
|
// zeros, START no more than END and END before LENGTH, and read as
|
|
// exactly those numbers.
|
|
func FuzzContentRange(f *testing.F) {
|
|
for _, s := range []string{"bytes 100-199/200", "bytes 5-9/*", "bytes */200", "bytes 9-5/10", "bytes 01-2/3", "bytes 1-2/3x", ""} {
|
|
f.Add(s)
|
|
}
|
|
f.Fuzz(func(t *testing.T, s string) {
|
|
start, end, total, ok := parseContentRange(s)
|
|
if !ok {
|
|
return
|
|
}
|
|
if start < 0 || end < start || total != -1 && end >= total {
|
|
t.Fatalf("%q read as %d-%d/%d", s, start, end, total)
|
|
}
|
|
length := "*"
|
|
if total >= 0 {
|
|
length = strconv.FormatInt(total, 10)
|
|
}
|
|
if want := fmt.Sprintf("bytes %d-%d/%s", start, end, length); s != want {
|
|
t.Fatalf("%q read as %q", s, want)
|
|
}
|
|
})
|
|
}
|
|
|
|
// cancelling is a log that cancels its context at its first line.
|
|
type cancelling context.CancelFunc
|
|
|
|
func (c cancelling) Write(b []byte) (int, error) {
|
|
c()
|
|
return len(b), nil
|
|
}
|
|
|
|
func cmpOr[T comparable](v, def T) T {
|
|
var zero T
|
|
if v == zero {
|
|
return def
|
|
}
|
|
return v
|
|
}
|
|
|
|
// A Content-Range read strictly, as RFC 9110 writes one: its first and
|
|
// last byte and the file's length (-1 for *), or nothing for what isn't
|
|
// one, a range that ends before it starts or past the file, and numbers
|
|
// with signs, spaces or more digits than a length has; an answer's
|
|
// validator for If-Range: a strong ETag, else its Last-Modified.
|
|
func TestResumeHeaders(t *testing.T) {
|
|
type rng struct{ start, end, total int64 }
|
|
for cr, want := range map[string]*rng{
|
|
"bytes 100-199/200": {100, 199, 200},
|
|
"bytes 5-9/*": {5, 9, -1},
|
|
"bytes 0-0/1": {0, 0, 1},
|
|
"bytes */200": nil,
|
|
"": nil,
|
|
"bytes 9-5/10": nil,
|
|
"bytes 5-10/10": nil,
|
|
"bytes -1-5/10": nil,
|
|
"bytes +1-5/10": nil,
|
|
"bytes 1-5/10 ": nil,
|
|
"bytes 1-5/10": nil,
|
|
"bits 1-5/10": nil,
|
|
"bytes 1-5": nil,
|
|
"bytes 1-5/": nil,
|
|
"bytes 1-/10": nil,
|
|
"bytes 1-99999999999999999999/*": nil,
|
|
"bytes 01-5/10": nil,
|
|
} {
|
|
start, end, total, ok := parseContentRange(cr)
|
|
switch {
|
|
case want == nil && ok:
|
|
t.Errorf("parseContentRange(%q) = %d-%d/%d, want none", cr, start, end, total)
|
|
case want != nil && (!ok || (rng{start, end, total}) != *want):
|
|
t.Errorf("parseContentRange(%q) = %d-%d/%d %v, want %v", cr, start, end, total, ok, *want)
|
|
}
|
|
}
|
|
lm := "Wed, 01 Jan 2026 00:00:00 GMT"
|
|
for _, tc := range []struct {
|
|
etag, modified, want string
|
|
}{
|
|
{`"abc"`, lm, `"abc"`},
|
|
{`W/"abc"`, lm, lm},
|
|
{"", lm, lm},
|
|
{`W/"abc"`, "", ""},
|
|
} {
|
|
h := http.Header{}
|
|
if tc.etag != "" {
|
|
h.Set("ETag", tc.etag)
|
|
}
|
|
if tc.modified != "" {
|
|
h.Set("Last-Modified", tc.modified)
|
|
}
|
|
if got := validator(h); got != tc.want {
|
|
t.Errorf("validator(%q, %q) = %q, want %q", tc.etag, tc.modified, got, tc.want)
|
|
}
|
|
}
|
|
}
|