media: seal the upload body's hash under a lock
Plan 3 Task 6 fix round 2 (Astra P2): Go may overlap a request body's Read and Close, and HTTP/2 closes it asynchronously after an early answer, so reading the MD5 and count once Close had run raced a Read still in progress. sentBody now keeps both under a mutex and counts Reads in progress; seal marks the body sealed, waits until none is in progress, and answers the MD5 (or "" when short). A Read in progress at seal is counted; one begun after is rejected with errBodySealed. The closed channel and its 5 s wait are gone. A deterministic regression holds a Read inside the reader while Close and seal run; it passes 200 times under -race.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+143
−28
internal/mediahandler/upload.go+63 −27internal/mediahandler/upload_test.go+80 −1
CI passed — run details
diff --git a/internal/mediahandler/upload.go b/internal/mediahandler/upload.go| index fe6947030..ed25061e1 100644 |
| --- a/internal/mediahandler/upload.go |
| +++ b/internal/mediahandler/upload.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "crypto/md5" |
| "encoding/hex" |
| + "errors" |
| "hash" |
| "io" |
| "net/http" |
| @@ -23,10 +24,6 @@ const putRetries = 2 |
| // minute covers the task's clock running behind the store's. |
| const deniedMargin = 60 * time.Second |
| -// bodyClosedWait bounds the wait for the transport to finish with a |
| -// request body once the response has come, before its hash is read. |
| -const bodyClosedWait = 5 * time.Second |
| - |
| // upload PUTs one collected output with its transfer t (create-only: |
| // t's signed If-None-Match: *), reading every byte from c's open file |
| // through an io.SectionReader, with Content-Length c.Size. It answers |
| @@ -162,7 +159,7 @@ func putOnce(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, |
| defer cancel() |
| idle := cfg.idle(idleTimeout, cancel) |
| defer idle.Stop() |
| - b := &sentBody{r: r, h: md5.New(), idle: idle, closed: make(chan struct{})} |
| + b := newSentBody(r, idle) |
| req, err := http.NewRequestWithContext(actx, http.MethodPut, p.Transfers.URL(t), b) |
| if err != nil { |
| // url.Parse's error quotes the URL: drop it. |
| @@ -191,44 +188,83 @@ func putOnce(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, |
| // sent its headers and then stalls the body must not hold the |
| // handler (Task 6 fix 1). |
| resp.Body.Close() |
| - timer := time.NewTimer(bodyClosedWait) |
| - defer timer.Stop() |
| - select { |
| - case <-b.closed: |
| - // The transport is done with the body: its hash is final. |
| - if b.n == size { |
| - sum = hex.EncodeToString(b.h.Sum(nil)) |
| - } |
| - case <-timer.C: |
| - } |
| - return resp.StatusCode, unquoteETag(resp.Header.Get("ETag")), sum, nil |
| + return resp.StatusCode, unquoteETag(resp.Header.Get("ETag")), b.seal(size), nil |
| } |
| +// errBodySealed is a body read begun after its hash was taken. |
| +var errBodySealed = errors.New("request body read after its hash was taken") |
| + |
| // sentBody is a PUT's body: it hashes and counts what the transport |
| -// reads, resets the idle timer on each read, and closes closed when the |
| -// transport closes it (after its last read). |
| +// reads and resets the idle timer on each read. The transport may read |
| +// it on its own goroutine and close it at any time, also after Do has |
| +// returned (HTTP/2 closes request bodies asynchronously after an early |
| +// answer, and Go allows Read and Close to overlap), so the hash and |
| +// count are kept under mu, and seal takes them only once no Read is in |
| +// progress (Task 6 fix 2, Astra P2). The rule: a Read in progress when |
| +// seal begins is waited for and counted; a Read begun after seal is |
| +// rejected (errBodySealed) and counts nothing. Close does not change |
| +// the hash; it is the transport's to call. |
| type sentBody struct { |
| - r io.Reader |
| - h hash.Hash |
| - n int64 |
| - idle idleTimer |
| - closed chan struct{} |
| - once sync.Once |
| + r io.Reader |
| + idle idleTimer |
| + |
| + mu sync.Mutex |
| + settled *sync.Cond // signalled when a Read ends |
| + h hash.Hash |
| + n int64 |
| + reading int // Reads in progress |
| + sealed bool // seal has begun: later Reads are rejected |
| +} |
| + |
| +func newSentBody(r io.Reader, idle idleTimer) *sentBody { |
| + b := &sentBody{r: r, idle: idle, h: md5.New()} |
| + b.settled = sync.NewCond(&b.mu) |
| + return b |
| } |
| func (b *sentBody) Read(p []byte) (int, error) { |
| + b.mu.Lock() |
| + if b.sealed { |
| + b.mu.Unlock() |
| + return 0, errBodySealed |
| + } |
| + b.reading++ |
| + b.mu.Unlock() |
| + |
| n, err := b.r.Read(p) |
| + |
| + b.mu.Lock() |
| if n > 0 { |
| b.h.Write(p[:n]) |
| b.n += int64(n) |
| + } |
| + b.reading-- |
| + b.settled.Broadcast() |
| + b.mu.Unlock() |
| + if n > 0 { |
| b.idle.Reset(idleTimeout) |
| } |
| return n, err |
| } |
| -func (b *sentBody) Close() error { |
| - b.once.Do(func() { close(b.closed) }) |
| - return nil |
| +func (b *sentBody) Close() error { return nil } |
| + |
| +// seal ends the body: no Read begins after it, it waits for any Read in |
| +// progress (a local file or buffer: it returns), and it answers the MD5 |
| +// of the bytes read, lower-case hex, when they are all size of them, else |
| +// "" (the caller hashes the whole body afresh). It may be called again |
| +// and answers the same. |
| +func (b *sentBody) seal(size int64) string { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.sealed = true |
| + for b.reading > 0 { |
| + b.settled.Wait() |
| + } |
| + if b.n != size { |
| + return "" |
| + } |
| + return hex.EncodeToString(b.h.Sum(nil)) |
| } |
| // hashAll is the MD5 of everything r reads, lower-case hex. MD5 is the |
diff --git a/internal/mediahandler/upload_test.go b/internal/mediahandler/upload_test.go| index 6f3ee1c41..e2e65aabd 100644 |
| --- a/internal/mediahandler/upload_test.go |
| +++ b/internal/mediahandler/upload_test.go |
| @@ -6,9 +6,11 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "net/http" |
| "os" |
| "path/filepath" |
| + "runtime" |
| "strings" |
| "testing" |
| "time" |
| @@ -239,7 +241,7 @@ func TestUploadStalledAnswerBody(t *testing.T) { |
| if err != nil || etag != md5hex(data) { |
| t.Fatalf("upload = %q, %s", etag, codeOf(err)) |
| } |
| - if d := time.Since(start); d > bodyClosedWait { |
| + if d := time.Since(start); d > 5*time.Second { |
| t.Fatalf("the upload took %v over a stalled answer", d) |
| } |
| } |
| @@ -617,3 +619,80 @@ func TestResultCodecsMatchTheChecks(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// gateReader returns its data in one Read, but only after it has said |
| +// so on entered and been let go on release. |
| +type gateReader struct { |
| + data []byte |
| + entered, release chan struct{} |
| +} |
| + |
| +func (g *gateReader) Read(p []byte) (int, error) { |
| + close(g.entered) |
| + <-g.release |
| + n := copy(p, g.data) |
| + return n, io.EOF |
| +} |
| + |
| +// TestSentBodySealWaitsForAReadInProgress (Task 6 fix 2, Astra P2): a |
| +// Read in progress when the transport closes the body and seal begins |
| +// is waited for and counted; a Read begun after seal is rejected and |
| +// counts nothing. Deterministic: the Read is held inside the reader |
| +// until seal has started; were seal not to wait, it would answer the |
| +// hash of nothing. Run under -race (the fix's report: 200 times). |
| +func TestSentBodySealWaitsForAReadInProgress(t *testing.T) { |
| + data := randomBytes(t, 4096) |
| + g := &gateReader{data: data, entered: make(chan struct{}), release: make(chan struct{})} |
| + b := newSentBody(g, &fakeIdleTimer{fi: &fakeIdle{}, f: func() {}}) |
| + |
| + readDone := make(chan int, 1) |
| + go func() { |
| + n, _ := b.Read(make([]byte, len(data))) |
| + readDone <- n |
| + }() |
| + <-g.entered // the Read is in progress, counted in b.reading |
| + if err := b.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + sealed := make(chan string, 1) |
| + go func() { sealed <- b.seal(int64(len(data))) }() |
| + // Wait until seal has begun (sealed set, under mu) before letting |
| + // the Read finish: a seal that did not wait would by then have |
| + // answered the hash of nothing. |
| + for { |
| + b.mu.Lock() |
| + begun := b.sealed |
| + b.mu.Unlock() |
| + if begun { |
| + break |
| + } |
| + runtime.Gosched() |
| + } |
| + select { |
| + case got := <-sealed: |
| + t.Fatalf("seal answered %q while a Read was in progress", got) |
| + default: |
| + } |
| + close(g.release) |
| + if n := <-readDone; n != len(data) { |
| + t.Fatalf("Read = %d", n) |
| + } |
| + if got := <-sealed; got != md5hex(data) { |
| + t.Fatalf("seal = %q, want the MD5 of the read in progress, %q", got, md5hex(data)) |
| + } |
| + // A Read begun after seal is rejected and changes nothing. |
| + if n, err := b.Read(make([]byte, 16)); n != 0 || !errors.Is(err, errBodySealed) { |
| + t.Fatalf("a Read after seal = %d, %v", n, err) |
| + } |
| + if got := b.seal(int64(len(data))); got != md5hex(data) { |
| + t.Fatalf("a second seal = %q", got) |
| + } |
| + // Short of the size, seal answers "": the caller hashes afresh. |
| + short := newSentBody(bytes.NewReader(data[:10]), &fakeIdleTimer{fi: &fakeIdle{}, f: func() {}}) |
| + if _, err := io.ReadAll(short); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := short.seal(int64(len(data))); got != "" { |
| + t.Fatalf("seal of a partial body = %q", got) |
| + } |
| +} |