From be0a6e6a400a9cd98a3479619b2f486b6a25a983 Mon Sep 17 00:00:00 2001 From: Ryan Bagas Date: Tue, 13 Oct 2026 19:22:25 +0700 Subject: [PATCH 1/3] feat(engine): restart a download when the file on the server changes Save the probe ETag and Last-Modified, and send one of them as If-Range on later range requests. A resume whose validator or size no longer matches, and a transfer whose If-Range is rejected, discards the partial file and fetches the new representation from the first byte. --- CHANGELOG.md | 7 + README.md | 10 +- internal/engine/download.go | 304 ++++++++++++++++++++++++------- internal/engine/if_range_test.go | 202 ++++++++++++++++++++ internal/engine/manager.go | 1 + 5 files changed, 459 insertions(+), 65 deletions(-) create mode 100644 internal/engine/if_range_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d925cfe..719ccdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ All notable changes to ODM are documented here. The format is based on ## [Unreleased] + +### Added + +- Resumed downloads send the saved `ETag` or `Last-Modified` as `If-Range`. + When the file on the server has changed, the partial file is discarded and + the download starts again from the first byte. + ## [0.4.3] - 2026-10-19 ### Added diff --git a/README.md b/README.md index 5c5ab21..60869c4 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,9 @@ queues. It runs as a desktop app, or headless with a JSON API. - A response that ends before its chunk is finished continues from the last byte written. One that brings no bytes at all is retried with a pause and gives up after the retry limit. +- A saved `ETag` or `Last-Modified` is sent as `If-Range` on resume. If the + file on the server has changed, the partial download is discarded and + started again from the first byte. - Servers that do not support ranges are fetched on a single stream. - Global and per-download speed limits, plus an optional data cap per time window. @@ -209,8 +212,11 @@ only. build the file before it answers. The other connections keep going. 4. **Finish.** The `.odmpart` file is renamed to the final name. -Each chunk's progress (`{id,start,end,done}`) is saved as JSON, so a restart -continues from the exact byte. Segmented ranges, byte-offset resume and chunk +Each chunk's progress (`{id,start,end,done}`) is saved as JSON, together with +the `ETag` and `Last-Modified` from the probe, so a restart continues from +the exact byte while the file on the server is unchanged. If `If-Range` fails, +or a later probe reports a different validator or size, ODM deletes the partial +file and downloads the new one. Segmented ranges, byte-offset resume and chunk splitting are standard download-manager techniques. ODM implements them in its own code. diff --git a/internal/engine/download.go b/internal/engine/download.go index 1447097..0cf4f46 100644 --- a/internal/engine/download.go +++ b/internal/engine/download.go @@ -96,6 +96,15 @@ type Download struct { // DefaultHeaderTimeout when set. Tests use short values; a zero value // means the default. stallTimeout, headerTimeout time.Duration + // ETag and LastModified identify the representation on the server. + // A resume sends one of them as If-Range and starts over when it no + // longer matches. + ETag string + LastModified string + + discardPart bool + changed bool + transferCancel context.CancelFunc } // New creates a queued download. Probing happens on the first Start. @@ -222,58 +231,89 @@ func (d *Download) Start(parent context.Context) { return } - if err := d.prepare(ctx); err != nil { - // A cancelled context means pause (or shutdown) during the probe, not - // a failure; same rule as the ctx.Err() check after the workers. - if ctx.Err() != nil { - d.mu.Lock() - d.Status = StatusPaused - d.mu.Unlock() - } else { - d.fail(err) + // One extra pass covers a representation that changes after the probe: + // the first pass stops, the partial file is dropped, and the second + // pass fetches the new file. A further change is reported as an error. + for pass := 0; pass < 2; pass++ { + if err := d.prepare(ctx); err != nil { + // A cancelled context means pause (or shutdown) during the probe, not + // a failure; same rule as the ctx.Err() check after the workers. + if ctx.Err() != nil { + d.mu.Lock() + d.Status = StatusPaused + d.mu.Unlock() + } else { + d.fail(err) + } + d.notify(true) + return } - d.notify(true) - return - } - - workers := d.Connections - if !d.RangeOK { - workers = 1 - } - if workers < 1 { - workers = 1 - } - var wg sync.WaitGroup - for i := 0; i < workers; i++ { - wg.Add(1) - go func() { defer wg.Done(); d.worker(ctx) }() - } - wg.Wait() + transferCtx, transferCancel := context.WithCancel(ctx) + d.mu.Lock() + d.transferCancel = transferCancel + d.mu.Unlock() - d.mu.Lock() - paused := ctx.Err() != nil - complete := d.allCompleteLocked() - status := d.Status - d.mu.Unlock() + workers := d.Connections + d.mu.Lock() + if !d.RangeOK { + workers = 1 + } + d.mu.Unlock() + if workers < 1 { + workers = 1 + } + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { defer wg.Done(); d.worker(transferCtx) }() + } + wg.Wait() + transferCancel() + d.mu.Lock() + d.transferCancel = nil + paused := ctx.Err() != nil + complete := d.allCompleteLocked() + status := d.Status + changed := d.changed + d.changed = false + d.mu.Unlock() - switch { - case complete: - if err := d.finish(); err != nil { - d.fail(err) - } else { + if paused { d.mu.Lock() - d.Status = StatusComplete + d.Status = StatusPaused d.mu.Unlock() + d.notify(true) + return } - case paused: - d.mu.Lock() - d.Status = StatusPaused - d.mu.Unlock() - case status != StatusError: - d.fail(errors.New("transfer ended with unfinished chunks")) + if changed { + if pass == 1 { + d.fail(errRepresentationChanged) + d.notify(true) + return + } + d.mu.Lock() + d.Status = StatusDownloading + d.Err = "" + d.mu.Unlock() + continue + } + + switch { + case complete: + if err := d.finish(); err != nil { + d.fail(err) + } else { + d.mu.Lock() + d.Status = StatusComplete + d.mu.Unlock() + } + case status != StatusError: + d.fail(errors.New("transfer ended with unfinished chunks")) + } + d.notify(true) + return } - d.notify(true) } func (d *Download) prepare(ctx context.Context) error { @@ -287,28 +327,104 @@ func (d *Download) prepare(ctx context.Context) error { if err != nil { return err } - d.mu.Lock() + d.applyProbe(p) + } else if err := d.revalidate(ctx); err != nil { + return err + } + return d.openTarget(needProbe) +} + +// applyProbe stores a first probe and builds the chunk plan. The caller +// does not hold d.mu. +func (d *Download) applyProbe(p *Probe) { + d.mu.Lock() + defer d.mu.Unlock() + d.FinalURL = p.FinalURL + if d.FileName == "" { + d.FileName = p.FileName + } + d.Total = p.Total + d.RangeOK = p.RangeOK + d.ETag = p.ETag + d.LastModified = p.LastModified + d.cookies = p.Cookies + if d.Connections <= 0 { + d.Connections = DefaultConnections + } + if d.SpeedLimit != 0 && d.limiter == nil { + d.limiter = NewLimiter(d.SpeedLimit) + } + d.planLocked(p) +} + +// revalidate runs before a resume. When the saved ETag, Last-Modified or +// size no longer matches, the partial file is discarded and planned again. +func (d *Download) revalidate(ctx context.Context) error { + d.mu.Lock() + rawURL, headers := d.URL, d.Headers + etag, modified, total, ranged := d.ETag, d.LastModified, d.Total, d.RangeOK + done := d.doneLocked() + d.mu.Unlock() + + p, err := Inspect(ctx, d.client, rawURL, headers) + if err != nil { + return err + } + d.mu.Lock() + defer d.mu.Unlock() + d.cookies = p.Cookies + if p.FinalURL != "" { d.FinalURL = p.FinalURL - if d.FileName == "" { - d.FileName = p.FileName - } - d.Total = p.Total - d.RangeOK = p.RangeOK - if d.Connections <= 0 { - d.Connections = DefaultConnections - } - if d.SpeedLimit != 0 && d.limiter == nil { - d.limiter = NewLimiter(d.SpeedLimit) + } + if !representationDiffers(etag, modified, total, ranged, done, p) { + if p.ETag != "" { + d.ETag = p.ETag } - d.cookies = p.Cookies - if p.RangeOK { - d.Chunks = NewPlan(p.Total, d.Connections) - } else { - d.Chunks = []*Chunk{{ID: 0, Start: 0, End: p.Total - 1}} + if p.LastModified != "" { + d.LastModified = p.LastModified } - d.mu.Unlock() + return nil } - return d.openTarget(needProbe) + d.ETag = p.ETag + d.LastModified = p.LastModified + d.Total = p.Total + d.RangeOK = p.RangeOK + d.planLocked(p) + d.discardPart = true + return nil +} + +// planLocked replaces the chunk list from a probe. The caller holds d.mu. +func (d *Download) planLocked(p *Probe) { + conns := d.Connections + if conns < 1 { + conns = 1 + } + if p.RangeOK { + d.Chunks = NewPlan(p.Total, conns) + return + } + d.Chunks = []*Chunk{{ID: 0, Start: 0, End: p.Total - 1}} +} + +// representationDiffers reports whether p is a different file from the one +// already partly stored. A missing saved validator does not count, so state +// written before validators were kept still resumes. A different size, or a +// ranged download whose server no longer accepts ranges, does. +func representationDiffers(etag, modified string, total int64, ranged bool, done int64, p *Probe) bool { + if total > 0 && p.Total > 0 && total != p.Total { + return true + } + if etag != "" && p.ETag != "" && etag != p.ETag { + return true + } + if modified != "" && p.LastModified != "" && modified != p.LastModified { + return true + } + if ranged && !p.RangeOK && done > 0 { + return true + } + return false } // openTarget opens the .odmpart file. A fresh download (first probe) claims @@ -320,6 +436,9 @@ func (d *Download) openTarget(fresh bool) error { if d.FileName == "" { d.FileName = "download.bin" } + discard := d.discardPart + d.discardPart = false + existing := d.file dir := d.BaseDir if dir == "" { dir = d.Dir @@ -343,6 +462,18 @@ func (d *Download) openTarget(fresh bool) error { rangeOK, total := d.RangeOK && d.Stream == nil, d.Total d.mu.Unlock() + if existing != nil && !fresh { + if discard { + if err := existing.Truncate(0); err != nil { + return err + } + } + if rangeOK && total > 0 { + return existing.Truncate(total) + } + return nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { return err } @@ -363,6 +494,12 @@ func (d *Download) openTarget(fresh bool) error { return err } } + if discard { + if err := f.Truncate(0); err != nil { + _ = f.Close() + return err + } + } if rangeOK && total > 0 { if err := f.Truncate(total); err != nil { _ = f.Close() @@ -388,6 +525,13 @@ func (d *Download) worker(ctx context.Context) { return } err := d.fetchWithRetry(ctx, ch) + if errors.Is(err, errRepresentationChanged) { + d.noteChanged() + d.mu.Lock() + ch.claimed = false + d.mu.Unlock() + return + } d.mu.Lock() ch.claimed = false if err != nil { @@ -436,6 +580,9 @@ func (d *Download) fetchWithRetry(ctx context.Context, ch *Chunk) error { if err == nil { return nil } + if errors.Is(err, errRepresentationChanged) { + return err + } if ctx.Err() != nil { return ctx.Err() } @@ -465,6 +612,10 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { finalURL := d.FinalURL headers := d.Headers cookies := d.cookies + validator := d.ETag + if validator == "" { + validator = d.LastModified + } d.mu.Unlock() req, err := http.NewRequestWithContext(ctx, http.MethodGet, finalURL, nil) @@ -479,6 +630,9 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { // an Accept-Encoding set on the download, which would ask for the // very compressed bytes that cannot be written here. req.Header.Set("Accept-Encoding", "identity") + if validator != "" { + req.Header.Set("If-Range", validator) + } req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end)) } if d.auth != nil { @@ -499,6 +653,11 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { defer resp.Body.Close() if rangeOK { + // If-Range failed: the server is sending the whole new representation. + // Do not write those bytes into the old range. + if resp.StatusCode == http.StatusOK && validator != "" { + return errRepresentationChanged + } if resp.StatusCode != http.StatusPartialContent { return fmt.Errorf("server ignored Range (status %s)", resp.Status) } @@ -684,6 +843,20 @@ func (d *Download) retryDelay() time.Duration { return 300 * time.Millisecond } +// errRepresentationChanged means the server no longer serves the bytes this +// download has partly stored. The partial file is discarded and fetched again. +var errRepresentationChanged = errors.New("file on the server changed") + +func (d *Download) noteChanged() { + d.mu.Lock() + d.changed = true + cancel := d.transferCancel + d.mu.Unlock() + if cancel != nil { + cancel() + } +} + func (d *Download) finish() error { d.mu.Lock() f := d.file @@ -871,6 +1044,8 @@ type State struct { OpenWhenDone bool `json:"open_when_done,omitempty"` Total int64 `json:"total"` RangeOK bool `json:"range_ok"` + ETag string `json:"etag,omitempty"` + LastModified string `json:"last_modified,omitempty"` CategoryName string `json:"category_name,omitempty"` Queue string `json:"queue,omitempty"` Description string `json:"description,omitempty"` @@ -910,7 +1085,8 @@ func (d *Download) State() State { BaseDir: d.BaseDir, Headers: d.Headers, Connections: d.Connections, SpeedLimit: d.SpeedLimit, OpenWhenDone: d.OpenWhenDone, CategoryName: d.CategoryName, Queue: d.Queue, Description: d.Description, Order: d.Order, - Total: d.Total, RangeOK: d.RangeOK, Status: status, Err: d.Err, + Total: d.Total, RangeOK: d.RangeOK, ETag: d.ETag, LastModified: d.LastModified, + Status: status, Err: d.Err, Chunks: chunks, Stream: stream, TrustFrom: d.TrustFrom, CreatedAt: d.CreatedAt, UpdatedAt: time.Now(), } } @@ -930,6 +1106,8 @@ func Restore(s State, client *http.Client) *Download { d.Dir = s.Dir d.Total = s.Total d.RangeOK = s.RangeOK + d.ETag = s.ETag + d.LastModified = s.LastModified d.OpenWhenDone = s.OpenWhenDone d.CategoryName = s.CategoryName d.Queue = s.Queue diff --git a/internal/engine/if_range_test.go b/internal/engine/if_range_test.go new file mode 100644 index 0000000..548dfdb --- /dev/null +++ b/internal/engine/if_range_test.go @@ -0,0 +1,202 @@ +package engine + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" +) + +func TestRepresentationDiffers(t *testing.T) { + same := &Probe{ETag: `"a"`, LastModified: "Mon, 1 Jan 2024 00:00:00 GMT", Total: 100, RangeOK: true} + if representationDiffers(`"a"`, same.LastModified, 100, true, 10, same) { + t.Fatal("identical probe reported as a different file") + } + if representationDiffers("", "", 100, true, 10, same) { + t.Fatal("a download saved before validators existed must still resume") + } + if !representationDiffers(`"a"`, "", 100, true, 10, &Probe{ETag: `"b"`, Total: 100, RangeOK: true}) { + t.Fatal("etag change was ignored") + } + if !representationDiffers("", same.LastModified, 100, true, 10, &Probe{LastModified: "Tue, 2 Jan 2024 00:00:00 GMT", Total: 100, RangeOK: true}) { + t.Fatal("modification time change was ignored") + } + if !representationDiffers(`"a"`, "", 100, true, 10, &Probe{ETag: `"a"`, Total: 80, RangeOK: true}) { + t.Fatal("size change was ignored") + } + if !representationDiffers("", "", 100, true, 10, &Probe{Total: 100, RangeOK: false}) { + t.Fatal("losing range support with bytes on disk was ignored") + } +} + +func TestResumeSendsIfRangeAndKeepsProgress(t *testing.T) { + data := payload(256 * 1024) + const etag = `"same"` + var sawIfRange atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-Range") == etag { + sawIfRange.Store(true) + } + writeRanged(w, r, data, etag, "Wed, 1 Jan 2025 00:00:00 GMT") + })) + defer srv.Close() + + dir := t.TempDir() + const half = 128 * 1024 + if err := os.WriteFile(filepath.Join(dir, "keep.bin.odmpart"), append(append([]byte{}, data[:half]...), make([]byte, len(data)-half)...), 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "keep", URL: srv.URL + "/keep.bin", FinalURL: srv.URL + "/keep.bin", + FileName: "keep.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if !sawIfRange.Load() { + t.Fatal("resume did not send If-Range") + } + got, err := os.ReadFile(filepath.Join(dir, "keep.bin")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("resumed file does not match") + } + if d.State().ETag != etag { + t.Fatalf("saved etag = %q", d.State().ETag) + } +} + +func TestResumeRestartsWhenETagChanges(t *testing.T) { + oldData := payload(192 * 1024) + newData := make([]byte, len(oldData)) + for i := range newData { + newData[i] = byte(255 - oldData[i]) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeRanged(w, r, newData, `"v2"`, "") + })) + defer srv.Close() + + dir := t.TempDir() + const half = 96 * 1024 + partial := make([]byte, len(oldData)) + copy(partial, oldData[:half]) + if err := os.WriteFile(filepath.Join(dir, "changed.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "changed", URL: srv.URL + "/changed.bin", FinalURL: srv.URL + "/changed.bin", + FileName: "changed.bin", Dir: dir, Connections: 1, Total: int64(len(oldData)), RangeOK: true, + ETag: `"v1"`, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(oldData)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + got, err := os.ReadFile(filepath.Join(dir, "changed.bin")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, newData) { + t.Fatal("file was not replaced after the etag changed") + } + if d.State().ETag != `"v2"` { + t.Fatalf("etag after restart = %q", d.State().ETag) + } +} + +func TestIfRangeFailureRestartsMidTransfer(t *testing.T) { + first := payload(128 * 1024) + second := make([]byte, len(first)) + for i := range second { + second[i] = first[len(first)-1-i] + } + var generation atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + explicit := strings.Contains(r.Header.Get("Range"), "-") && !strings.HasSuffix(r.Header.Get("Range"), "-") + if explicit && r.Header.Get("If-Range") == `"v1"` { + generation.Store(1) + w.Header().Set("ETag", `"v2"`) + w.Header().Set("Content-Length", strconv.Itoa(len(second))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(second) + return + } + data, etag := first, `"v1"` + if generation.Load() > 0 { + data, etag = second, `"v2"` + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + d := New("flip", srv.URL+"/flip.bin", dir, 1, nil, 0, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, second) { + t.Fatal("download kept the first representation after If-Range failed") + } +} + +func writeRanged(w http.ResponseWriter, r *http.Request, data []byte, etag, modified string) { + w.Header().Set("Accept-Ranges", "bytes") + if etag != "" { + w.Header().Set("ETag", etag) + } + if modified != "" { + w.Header().Set("Last-Modified", modified) + } + spec := strings.TrimPrefix(r.Header.Get("Range"), "bytes=") + parts := strings.SplitN(spec, "-", 2) + start := 0 + if parts[0] != "" { + start, _ = strconv.Atoi(parts[0]) + } + end := len(data) - 1 + if len(parts) == 2 && parts[1] != "" { + if v, err := strconv.Atoi(parts[1]); err == nil { + end = v + } + } + if start < 0 || start >= len(data) || end < start { + http.Error(w, "bad range", http.StatusRequestedRangeNotSatisfiable) + return + } + if end >= len(data) { + end = len(data) - 1 + } + body := data[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data))) + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write(body) +} diff --git a/internal/engine/manager.go b/internal/engine/manager.go index 18bbac3..1bdcf36 100644 --- a/internal/engine/manager.go +++ b/internal/engine/manager.go @@ -808,6 +808,7 @@ func (m *Manager) Readdress(ctx context.Context, id, newURL string) error { d.mu.Lock() d.URL, d.FinalURL, d.cookies = newURL, p.FinalURL, p.Cookies d.TrustFrom = "" // the user gave this address + d.ETag, d.LastModified = p.ETag, p.LastModified if d.Status == StatusError { d.Status, d.Err = StatusPaused, "" } From 96966030c691eb441652ecbbd1b45cff4cfde025 Mon Sep 17 00:00:00 2001 From: Ryan Bagas Date: Tue, 13 Oct 2026 20:45:18 +0700 Subject: [PATCH 2/3] fix(engine): keep a full-file 200 when the validator matches A range that already covers the whole file can be answered with 200 while the ETag or Last-Modified is unchanged. That body is the file. A 200 for any narrower range, or a different validator or length, still discards the partial and starts again. --- CHANGELOG.md | 3 +- README.md | 6 +- internal/engine/download.go | 47 +++++++++-- internal/engine/if_range_test.go | 136 +++++++++++++++++++++++++++++++ 4 files changed, 180 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 719ccdf..241532e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ All notable changes to ODM are documented here. The format is based on - Resumed downloads send the saved `ETag` or `Last-Modified` as `If-Range`. When the file on the server has changed, the partial file is discarded and - the download starts again from the first byte. + the download starts again from the first byte. A `200` response whose range + already covers the whole file is kept when that validator still matches. ## [0.4.3] - 2026-10-19 diff --git a/README.md b/README.md index 60869c4..a9d7be2 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,8 @@ queues. It runs as a desktop app, or headless with a JSON API. pause and gives up after the retry limit. - A saved `ETag` or `Last-Modified` is sent as `If-Range` on resume. If the file on the server has changed, the partial download is discarded and - started again from the first byte. + started again from the first byte. A `200` for a range that already covers + the whole file is kept when that validator still matches. - Servers that do not support ranges are fetched on a single stream. - Global and per-download speed limits, plus an optional data cap per time window. @@ -216,7 +217,8 @@ Each chunk's progress (`{id,start,end,done}`) is saved as JSON, together with the `ETag` and `Last-Modified` from the probe, so a restart continues from the exact byte while the file on the server is unchanged. If `If-Range` fails, or a later probe reports a different validator or size, ODM deletes the partial -file and downloads the new one. Segmented ranges, byte-offset resume and chunk +file and downloads the new one. A `200` for a range that already covers the +whole file is kept when the validator still matches. Segmented ranges, byte-offset resume and chunk splitting are standard download-manager techniques. ODM implements them in its own code. diff --git a/internal/engine/download.go b/internal/engine/download.go index 0cf4f46..c4e538e 100644 --- a/internal/engine/download.go +++ b/internal/engine/download.go @@ -612,11 +612,13 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { finalURL := d.FinalURL headers := d.Headers cookies := d.cookies - validator := d.ETag + etag, modified := d.ETag, d.LastModified + total := d.Total + d.mu.Unlock() + validator := etag if validator == "" { - validator = d.LastModified + validator = modified } - d.mu.Unlock() req, err := http.NewRequestWithContext(ctx, http.MethodGet, finalURL, nil) if err != nil { @@ -654,14 +656,16 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { if rangeOK { // If-Range failed: the server is sending the whole new representation. - // Do not write those bytes into the old range. + // Do not write those bytes into the old range. A 200 for a range that + // already covers the whole file is the same representation when the + // validator still matches, so that body is kept. if resp.StatusCode == http.StatusOK && validator != "" { - return errRepresentationChanged - } - if resp.StatusCode != http.StatusPartialContent { + if !wholeFileOK(start, end, total, etag, modified, resp) { + return errRepresentationChanged + } + } else if resp.StatusCode != http.StatusPartialContent { return fmt.Errorf("server ignored Range (status %s)", resp.Status) - } - if cs, _, _, ok := ParseContentRange(resp.Header.Get("Content-Range")); ok && cs != start { + } else if cs, _, _, ok := ParseContentRange(resp.Header.Get("Content-Range")); ok && cs != start { return fmt.Errorf("range mismatch: asked %d, got %d", start, cs) } } else if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { @@ -847,6 +851,31 @@ func (d *Download) retryDelay() time.Duration { // download has partly stored. The partial file is discarded and fetched again. var errRepresentationChanged = errors.New("file on the server changed") +// wholeFileOK reports whether a 200 response is the file this request already +// asked for in full. Some servers answer 200, not 206, when the range covers +// every byte and the validator still matches. +func wholeFileOK(start, end, total int64, etag, modified string, resp *http.Response) bool { + if total <= 0 || start != 0 || end != total-1 { + return false + } + switch { + case etag != "": + if resp.Header.Get("ETag") != etag { + return false + } + case modified != "": + if resp.Header.Get("Last-Modified") != modified { + return false + } + default: + return false + } + if n := resp.ContentLength; n >= 0 && n != total { + return false + } + return true +} + func (d *Download) noteChanged() { d.mu.Lock() d.changed = true diff --git a/internal/engine/if_range_test.go b/internal/engine/if_range_test.go index 548dfdb..ef80292 100644 --- a/internal/engine/if_range_test.go +++ b/internal/engine/if_range_test.go @@ -167,6 +167,142 @@ func TestIfRangeFailureRestartsMidTransfer(t *testing.T) { } } +func TestWholeFileOK(t *testing.T) { + header := make(http.Header) + header.Set("ETag", `"a"`) + resp := &http.Response{Header: header, ContentLength: 100} + if !wholeFileOK(0, 99, 100, `"a"`, "", resp) { + t.Fatal("matching etag on a full-file 200 was rejected") + } + if wholeFileOK(10, 99, 100, `"a"`, "", resp) { + t.Fatal("a 200 for a subrange was accepted") + } + header.Set("ETag", `"b"`) + if wholeFileOK(0, 99, 100, `"a"`, "", resp) { + t.Fatal("a different etag was accepted") + } + header.Set("ETag", `"a"`) + resp.ContentLength = 90 + if wholeFileOK(0, 99, 100, `"a"`, "", resp) { + t.Fatal("a different length was accepted") + } + resp.ContentLength = -1 + if !wholeFileOK(0, 99, 100, `"a"`, "", resp) { + t.Fatal("unknown length with a matching etag was rejected") + } + header.Del("ETag") + header.Set("Last-Modified", "Mon, 1 Jan 2024 00:00:00 GMT") + if !wholeFileOK(0, 99, 100, "", "Mon, 1 Jan 2024 00:00:00 GMT", resp) { + t.Fatal("matching modification time was rejected") + } + if wholeFileOK(0, 99, 100, "", "Tue, 2 Jan 2024 00:00:00 GMT", resp) { + t.Fatal("a different modification time was accepted") + } +} + +func TestFullFileOKWithSameETagCompletes(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + full := fmt.Sprintf("bytes=0-%d", len(data)-1) + var fullOK atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Range") == full && r.Header.Get("If-Range") == etag { + fullOK.Add(1) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("ETag", etag) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + d := New("full-ok", srv.URL+"/file.bin", dir, 1, nil, 0, srv.Client()) + t.Cleanup(func() { closeDownloadFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := fullOK.Load(); n != 1 { + t.Fatalf("full-file 200 responses = %d, want 1", n) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") + } +} + +func TestSubrangeOKWithSameETagDoesNotWrite(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + const half = 64 * 1024 + remainder := fmt.Sprintf("bytes=%d-", half) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Header.Get("Range"), remainder) && r.Header.Get("If-Range") == etag { + w.Header().Set("ETag", etag) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + partial := make([]byte, len(data)) + copy(partial, data[:half]) + if err := os.WriteFile(filepath.Join(dir, "part.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "part", URL: srv.URL + "/part.bin", FinalURL: srv.URL + "/part.bin", + FileName: "part.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + t.Cleanup(func() { closeDownloadFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusError { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if info.Error != errRepresentationChanged.Error() { + t.Fatalf("error=%q", info.Error) + } + if _, err := os.Stat(filepath.Join(dir, "part.bin")); !os.IsNotExist(err) { + t.Fatal("partial file was renamed after a subrange 200") + } + got, err := os.ReadFile(filepath.Join(dir, "part.bin.odmpart")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got[:half], data[:half]) { + t.Fatal("bytes already stored were overwritten") + } +} + +func closeDownloadFile(d *Download) { + d.mu.Lock() + if d.file != nil { + _ = d.file.Close() + d.file = nil + } + d.mu.Unlock() +} + func writeRanged(w http.ResponseWriter, r *http.Request, data []byte, etag, modified string) { w.Header().Set("Accept-Ranges", "bytes") if etag != "" { From f2b611c7ddac24561a09a89d7c1df7047962626a Mon Sep 17 00:00:00 2001 From: I Made Ocy Darma Putra Date: Mon, 19 Oct 2026 10:03:24 +0700 Subject: [PATCH 3/3] fix(engine): send only a strong validator as If-Range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review changes on top of the previous two commits: - A weak ETag (W/) is never sent as If-Range; Last-Modified is, or nothing. RFC 9110 does not allow a weak one there and Go's http.ServeContent answers it with a full 200, so every sub-range of a fresh multi-connection download looked like a changed file and failed. TestWeakETagFreshMultiConnection and TestWeakETagFallsBackToLastModified use http.ServeContent. - A 200 to a request with If-Range is told apart by its own validator: a different (or missing) one is a changed file and restarts; the same one is a server ignoring Range, kept when the range covered the whole file and otherwise reported as "server ignored Range", as on main. - revalidate probes FinalURL with the saved cookies through guardedClient, as the transfer itself does: a token link that only works there resumes as before. A probe failure is not fatal (If-Range on each request still guards), except a local-network refusal. A probe that sets no cookie keeps the saved ones. - Tests reuse closeEngineFile; the ignored-Range test sets retryBase. ✨ Generated with Claude Code (claude.ai/claude-code) 2.1.303 (claude-opus-5-5) --- CHANGELOG.md | 8 +- README.md | 19 +-- internal/engine/download.go | 87 +++++++++---- internal/engine/if_range_test.go | 208 ++++++++++++++++++++++++++----- 4 files changed, 251 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 241532e..c93a827 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,12 @@ All notable changes to ODM are documented here. The format is based on ## [Unreleased] - ### Added -- Resumed downloads send the saved `ETag` or `Last-Modified` as `If-Range`. - When the file on the server has changed, the partial file is discarded and - the download starts again from the first byte. A `200` response whose range +- Range requests send the file's `ETag` (only a strong one) or + `Last-Modified` as `If-Range`, and a resume checks them first. When the + file on the server has changed, the partial file is discarded and the + download starts again from the first byte. A `200` response whose range already covers the whole file is kept when that validator still matches. ## [0.4.3] - 2026-10-19 diff --git a/README.md b/README.md index a9d7be2..b7b3509 100644 --- a/README.md +++ b/README.md @@ -23,10 +23,11 @@ queues. It runs as a desktop app, or headless with a JSON API. - A response that ends before its chunk is finished continues from the last byte written. One that brings no bytes at all is retried with a pause and gives up after the retry limit. -- A saved `ETag` or `Last-Modified` is sent as `If-Range` on resume. If the - file on the server has changed, the partial download is discarded and - started again from the first byte. A `200` for a range that already covers - the whole file is kept when that validator still matches. +- Every range request carries the file's `ETag` (a strong one) or + `Last-Modified` as `If-Range`, and a resume checks them first. If the file + on the server has changed, the partial download is discarded and started + again from the first byte. A `200` for a range that already covers the + whole file is kept when that validator still matches. - Servers that do not support ranges are fetched on a single stream. - Global and per-download speed limits, plus an optional data cap per time window. @@ -215,10 +216,12 @@ only. Each chunk's progress (`{id,start,end,done}`) is saved as JSON, together with the `ETag` and `Last-Modified` from the probe, so a restart continues from -the exact byte while the file on the server is unchanged. If `If-Range` fails, -or a later probe reports a different validator or size, ODM deletes the partial -file and downloads the new one. A `200` for a range that already covers the -whole file is kept when the validator still matches. Segmented ranges, byte-offset resume and chunk +the exact byte while the file on the server is unchanged. If `If-Range` fails +(a `200` with another validator), or a later probe reports a different +validator or size, ODM deletes the partial file and downloads the new one. A +`200` with the same validator is a server ignoring `Range`: it is kept when +the range already covers the whole file. A weak `ETag` is never sent as +`If-Range`. Segmented ranges, byte-offset resume and chunk splitting are standard download-manager techniques. ODM implements them in its own code. diff --git a/internal/engine/download.go b/internal/engine/download.go index c4e538e..85ed714 100644 --- a/internal/engine/download.go +++ b/internal/engine/download.go @@ -359,20 +359,43 @@ func (d *Download) applyProbe(p *Probe) { // revalidate runs before a resume. When the saved ETag, Last-Modified or // size no longer matches, the partial file is discarded and planned again. +// +// It asks the address the transfer itself uses (FinalURL, with the cookies +// the first probe got), as a resume did before this check existed: a +// short-lived redirect or token link may no longer work from d.URL. A probe +// that fails is not fatal for the same reason; the resume goes on as it +// used to, and If-Range on every ranged request still catches a changed +// file. A refusal by the local-network guard is final, as everywhere. func (d *Download) revalidate(ctx context.Context) error { d.mu.Lock() - rawURL, headers := d.URL, d.Headers + rawURL := d.FinalURL + if rawURL == "" { + rawURL = d.URL + } + headers := make(map[string]string, len(d.Headers)+1) + for k, v := range d.Headers { + headers[k] = v + } + if len(d.cookies) > 0 { + headers["Cookie"] = cookieHeader(d.cookies) + } etag, modified, total, ranged := d.ETag, d.LastModified, d.Total, d.RangeOK done := d.doneLocked() d.mu.Unlock() - p, err := Inspect(ctx, d.client, rawURL, headers) + p, err := Inspect(ctx, d.guardedClient(), rawURL, headers) if err != nil { - return err + if ctx.Err() != nil || errors.Is(err, errLocalNetwork) { + return err + } + return nil } d.mu.Lock() defer d.mu.Unlock() - d.cookies = p.Cookies + // A probe that sets no cookie leaves the saved ones in place. + if len(p.Cookies) > 0 { + d.cookies = p.Cookies + } if p.FinalURL != "" { d.FinalURL = p.FinalURL } @@ -615,10 +638,7 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { etag, modified := d.ETag, d.LastModified total := d.Total d.mu.Unlock() - validator := etag - if validator == "" { - validator = modified - } + validator, isETag := ifRangeValidator(etag, modified) req, err := http.NewRequestWithContext(ctx, http.MethodGet, finalURL, nil) if err != nil { @@ -655,14 +675,19 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { defer resp.Body.Close() if rangeOK { - // If-Range failed: the server is sending the whole new representation. - // Do not write those bytes into the old range. A 200 for a range that - // already covers the whole file is the same representation when the - // validator still matches, so that body is kept. + // A 200 to a request with If-Range is either a changed file (the + // validator no longer matches, so the server sends the new one + // whole) or a server that ignores Range. The 200's own validator + // tells them apart: a different one restarts the download, the same + // one is the old file, kept when the range already covered all of + // it and otherwise reported as an ignored Range, as without If-Range. if resp.StatusCode == http.StatusOK && validator != "" { - if !wholeFileOK(start, end, total, etag, modified, resp) { + if !sameValidator(validator, isETag, resp) { return errRepresentationChanged } + if !wholeFileOK(start, end, total, resp) { + return fmt.Errorf("server ignored Range (status %s)", resp.Status) + } } else if resp.StatusCode != http.StatusPartialContent { return fmt.Errorf("server ignored Range (status %s)", resp.Status) } else if cs, _, _, ok := ParseContentRange(resp.Header.Get("Content-Range")); ok && cs != start { @@ -854,28 +879,38 @@ var errRepresentationChanged = errors.New("file on the server changed") // wholeFileOK reports whether a 200 response is the file this request already // asked for in full. Some servers answer 200, not 206, when the range covers // every byte and the validator still matches. -func wholeFileOK(start, end, total int64, etag, modified string, resp *http.Response) bool { +func wholeFileOK(start, end, total int64, resp *http.Response) bool { if total <= 0 || start != 0 || end != total-1 { return false } - switch { - case etag != "": - if resp.Header.Get("ETag") != etag { - return false - } - case modified != "": - if resp.Header.Get("Last-Modified") != modified { - return false - } - default: - return false - } if n := resp.ContentLength; n >= 0 && n != total { return false } return true } +// ifRangeValidator is what a ranged request sends as If-Range, and whether +// it is an ETag: the ETag when it is strong, else Last-Modified, else +// nothing. A weak ETag ("W/") is not allowed there (RFC 9110, 13.1.5), and +// servers such as Go's own http.ServeContent answer it with a full 200: +// every ranged request of a fresh download would look like a changed file. +func ifRangeValidator(etag, modified string) (string, bool) { + if etag != "" && !strings.HasPrefix(etag, "W/") { + return etag, true + } + return modified, false +} + +// sameValidator reports whether resp carries the validator that was sent +// as If-Range. A 200 without it cannot show the file is the same, so it +// counts as changed. +func sameValidator(validator string, isETag bool, resp *http.Response) bool { + if isETag { + return resp.Header.Get("ETag") == validator + } + return resp.Header.Get("Last-Modified") == validator +} + func (d *Download) noteChanged() { d.mu.Lock() d.changed = true diff --git a/internal/engine/if_range_test.go b/internal/engine/if_range_test.go index ef80292..a70a077 100644 --- a/internal/engine/if_range_test.go +++ b/internal/engine/if_range_test.go @@ -12,6 +12,7 @@ import ( "strings" "sync/atomic" "testing" + "time" ) func TestRepresentationDiffers(t *testing.T) { @@ -168,35 +169,181 @@ func TestIfRangeFailureRestartsMidTransfer(t *testing.T) { } func TestWholeFileOK(t *testing.T) { - header := make(http.Header) - header.Set("ETag", `"a"`) - resp := &http.Response{Header: header, ContentLength: 100} - if !wholeFileOK(0, 99, 100, `"a"`, "", resp) { - t.Fatal("matching etag on a full-file 200 was rejected") + resp := &http.Response{Header: make(http.Header), ContentLength: 100} + if !wholeFileOK(0, 99, 100, resp) { + t.Fatal("a full-file 200 was rejected") } - if wholeFileOK(10, 99, 100, `"a"`, "", resp) { + if wholeFileOK(10, 99, 100, resp) { t.Fatal("a 200 for a subrange was accepted") } - header.Set("ETag", `"b"`) - if wholeFileOK(0, 99, 100, `"a"`, "", resp) { - t.Fatal("a different etag was accepted") - } - header.Set("ETag", `"a"`) resp.ContentLength = 90 - if wholeFileOK(0, 99, 100, `"a"`, "", resp) { + if wholeFileOK(0, 99, 100, resp) { t.Fatal("a different length was accepted") } resp.ContentLength = -1 - if !wholeFileOK(0, 99, 100, `"a"`, "", resp) { - t.Fatal("unknown length with a matching etag was rejected") + if !wholeFileOK(0, 99, 100, resp) { + t.Fatal("unknown length was rejected") + } +} + +func TestIfRangeValidator(t *testing.T) { + const date = "Mon, 01 Jan 2024 00:00:00 GMT" + for _, c := range []struct { + etag, modified, want string + isETag bool + }{ + {`"a"`, date, `"a"`, true}, + {`W/"a"`, date, date, false}, // weak: never sent as If-Range + {`W/"a"`, "", "", false}, + {"", date, date, false}, + {"", "", "", false}, + } { + got, isETag := ifRangeValidator(c.etag, c.modified) + if got != c.want || isETag != c.isETag { + t.Errorf("ifRangeValidator(%q, %q) = %q, %v; want %q, %v", c.etag, c.modified, got, isETag, c.want, c.isETag) + } + } +} + +func TestSameValidator(t *testing.T) { + const date = "Mon, 01 Jan 2024 00:00:00 GMT" + h := make(http.Header) + h.Set("ETag", `"a"`) + h.Set("Last-Modified", date) + resp := &http.Response{Header: h} + if !sameValidator(`"a"`, true, resp) || sameValidator(`"b"`, true, resp) { + t.Fatal("ETag comparison") + } + if !sameValidator(date, false, resp) || sameValidator("Tue, 02 Jan 2024 00:00:00 GMT", false, resp) { + t.Fatal("Last-Modified comparison") + } + // An unquoted (non-standard) ETag is still compared as an ETag. + h.Set("ETag", "abc") + if !sameValidator("abc", true, resp) { + t.Fatal("unquoted ETag") + } + h.Del("ETag") + if sameValidator(`"a"`, true, resp) { + t.Fatal("a 200 without the ETag counted as the same file") + } +} + +// A weak ETag must not go into If-Range: Go's http.ServeContent (like +// RFC 9110) answers it with a full 200, which made every sub-range of a +// fresh multi-connection download look like a changed file. +func TestWeakETagFreshMultiConnection(t *testing.T) { + data := payload(512 * 1024) + var ifRange atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-Range") != "" { + ifRange.Add(1) + } + w.Header().Set("ETag", `W/"weak"`) + http.ServeContent(w, r, "weak.bin", time.Time{}, bytes.NewReader(data)) + })) + defer srv.Close() + + dir := t.TempDir() + d := New("weak", srv.URL+"/weak.bin", dir, 4, nil, 0, srv.Client()) + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := ifRange.Load(); n != 0 { + t.Fatalf("%d requests sent If-Range with a weak ETag and no Last-Modified", n) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") + } +} + +// With a weak ETag and a Last-Modified, the date goes into If-Range, and +// http.ServeContent honours it with 206s. +func TestWeakETagFallsBackToLastModified(t *testing.T) { + data := payload(512 * 1024) + mod := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) + var sent atomic.Value + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if v := r.Header.Get("If-Range"); v != "" { + sent.Store(v) + } + w.Header().Set("ETag", `W/"weak"`) + http.ServeContent(w, r, "weak.bin", mod, bytes.NewReader(data)) + })) + defer srv.Close() + + dir := t.TempDir() + d := New("weak-date", srv.URL+"/weak.bin", dir, 4, nil, 0, srv.Client()) + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if v, _ := sent.Load().(string); v != mod.Format(http.TimeFormat) { + t.Fatalf("If-Range = %q, want the Last-Modified date", v) + } +} + +// A resume checks the file at the address the transfer uses, with the +// cookies the first probe got: a token link that only works there (and +// a server that wants its cookie) resumes as it did before. +func TestResumeRevalidatesFinalURLWithCookies(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + var original atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/start" { + original.Add(1) + http.Error(w, "token expired", http.StatusGone) + return + } + if c, err := r.Cookie("session"); err != nil || c.Value != "s1" { + http.Error(w, "no session", http.StatusForbidden) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + const half = 64 * 1024 + dir := t.TempDir() + partial := make([]byte, len(data)) + copy(partial, data[:half]) + if err := os.WriteFile(filepath.Join(dir, "tok.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + d := Restore(State{ + ID: "tok", URL: srv.URL + "/start", FinalURL: srv.URL + "/file?token=1", + FileName: "tok.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{{ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}}, + }, srv.Client()) + d.cookies = []*http.Cookie{{Name: "session", Value: "s1"}} + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := original.Load(); n != 0 { + t.Fatalf("the original address was probed %d times on resume", n) } - header.Del("ETag") - header.Set("Last-Modified", "Mon, 1 Jan 2024 00:00:00 GMT") - if !wholeFileOK(0, 99, 100, "", "Mon, 1 Jan 2024 00:00:00 GMT", resp) { - t.Fatal("matching modification time was rejected") + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) } - if wholeFileOK(0, 99, 100, "", "Tue, 2 Jan 2024 00:00:00 GMT", resp) { - t.Fatal("a different modification time was accepted") + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") } } @@ -221,7 +368,7 @@ func TestFullFileOKWithSameETagCompletes(t *testing.T) { dir := t.TempDir() d := New("full-ok", srv.URL+"/file.bin", dir, 1, nil, 0, srv.Client()) - t.Cleanup(func() { closeDownloadFile(d) }) + t.Cleanup(func() { closeEngineFile(d) }) d.Start(context.Background()) info := d.Info() @@ -240,6 +387,9 @@ func TestFullFileOKWithSameETagCompletes(t *testing.T) { } } +// A 200 that carries the same ETag is the old file from a server that +// ignored Range: reported as such, not as a changed file, and nothing is +// written over the bytes already stored. func TestSubrangeOKWithSameETagDoesNotWrite(t *testing.T) { data := payload(128 * 1024) const etag = `"same"` @@ -272,15 +422,16 @@ func TestSubrangeOKWithSameETagDoesNotWrite(t *testing.T) { }, } d := Restore(st, srv.Client()) - t.Cleanup(func() { closeDownloadFile(d) }) + d.retryBase = time.Millisecond + t.Cleanup(func() { closeEngineFile(d) }) d.Start(context.Background()) info := d.Info() if info.Status != StatusError { t.Fatalf("status=%s err=%q", info.Status, info.Error) } - if info.Error != errRepresentationChanged.Error() { - t.Fatalf("error=%q", info.Error) + if !strings.HasPrefix(info.Error, "server ignored Range") { + t.Fatalf("error=%q, want server ignored Range", info.Error) } if _, err := os.Stat(filepath.Join(dir, "part.bin")); !os.IsNotExist(err) { t.Fatal("partial file was renamed after a subrange 200") @@ -294,15 +445,6 @@ func TestSubrangeOKWithSameETagDoesNotWrite(t *testing.T) { } } -func closeDownloadFile(d *Download) { - d.mu.Lock() - if d.file != nil { - _ = d.file.Close() - d.file = nil - } - d.mu.Unlock() -} - func writeRanged(w http.ResponseWriter, r *http.Request, data []byte, etag, modified string) { w.Header().Set("Accept-Ranges", "bytes") if etag != "" {