carlos / platform Public

rootaws: measure body progress on the connection, below chunking

Astra round 1, P1: the body bound timed each Read, and net/http's
chunked reader keeps filling the caller's buffer until the chunk ends,
so a store trickling bytes inside one large chunk held a single Read
past the bound while still sending. That healthy transfer was cut.

Progress is now measured below TLS and chunk decoding. The bounded HTTP
client's DialContext wraps each connection in a progressConn that
records when it last received bytes; the middleware finds the request's
connection through an httptrace GotConn hook (unwrapping the TLS conn).
When a Read's timer fires it checks the connection: quiet for the bound
since the later of the Read's start and the last bytes is a stall,
otherwise the timer waits out the rest. Consumer pauses between reads
stay exempt, nothing sets a connection-wide deadline, and with HTTP/2
any stream's bytes count, which can only delay a timeout. A connection
that is not ours (another HTTP client, or a non-legacy defaults mode,
which replaces DialContext) gets no body bound rather than one that
could cut a healthy transfer; the header timeout still applies.

StallHTTPClient and StallAPIOptions export the pair for clients built
from bare service options.

P2: the comment now calls both bounds per-phase inactivity limits and
gives the real worst case: the timers are independent, so three
attempts can take about twelve minutes plus dial and backoff, more if
the body made progress before stalling.

Retries: a stall inside an answer the SDK decodes is retried like any
timeout. A streamed GetObject body fails after the operation returned,
so the SDK does not retry it; S3Store.Get returns the io.ReadAll error
directly, as it does today on a broken connection.

Tests: one chunk delivered in 64-byte fragments, each a twentieth of a
1 s bound apart, read by one 3 s Read, now succeeds; on the previous
stall.go it fails after 1.0s ("response body stalled"). The trickle
tests use gaps of a twentieth of the bound, and a TLS test shows the
bound finds its connection under TLS with a CA bundle loaded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 93be380be102b913c718f4753577eee4e8fa949d parent 91e6d5b
2 files changed, +330 −71
  • internal/rootaws/stall.go +154 −32
  • internal/rootaws/stall_test.go +176 −39
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go
index a2024c078..e4d65ffc0 100644
--- a/internal/rootaws/stall.go
+++ b/internal/rootaws/stall.go
@@ -4,7 +4,10 @@ import (
"context"
"fmt"
"io"
+ "net"
"net/http"
+ "net/http/httptrace"
+ "sync"
"sync/atomic"
"time"
@@ -19,25 +22,33 @@ import (
// answers, or answers and then stops sending the body, holds the call until
// the caller's context ends, and many agent loops run each pass on
// context.Background(): one such call parks the loop until the process
-// restarts. The two bounds below end that wait. Neither caps a whole call:
-// an upload's own write time is not counted, and a large download that keeps
-// receiving bytes is never cut off, however long it takes.
+// restarts. The two bounds below end that wait.
+//
+// Both are per-phase INACTIVITY limits, not deadlines. Neither caps a whole
+// call: an upload's own write time is not counted, and a download that keeps
+// receiving bytes is never cut off, however long it takes. They guarantee
+// only that a call cannot wait forever on a store that has gone quiet; a
+// caller that needs a whole-request or whole-pass bound still sets its own.
//
// The values are this tree's own ceiling for one store request: 120 s is
// hostbox.RequestLimit, lease's stagingRequestTimeout and
// claimgeneration's generationRequestLimit, each a bound on a WHOLE request.
// A healthy bucket answers in well under a second, so a call that waits this
-// long for one header or one chunk of body is stalled, not slow, and no call
-// that fits those whole-request bounds today can be cut by these per-phase
-// ones. With the SDK's three attempts a stalled call ends in about six
-// minutes at worst; convergePassTimeout (5 min) guards the converge pass
-// tighter still.
+// long for its headers, or gets no bytes at all for this long, is stalled,
+// not slow, and no call that fits those whole-request bounds today can be cut
+// by these per-phase ones. How long a stalled call takes to fail depends on
+// where it stalls: one attempt that stalls at once on the headers ends in
+// 120 s, and with the SDK's three attempts in about six minutes plus dial
+// time and backoff. The timers are independent, so an attempt whose headers
+// come just inside 120 s and whose decoded body then stalls takes up to
+// 240 s, about twelve minutes over three attempts, and body progress before
+// a stall extends that further.
const (
// ResponseHeaderTimeout bounds the wait for a response's headers once
// the request, body included, has been written.
ResponseHeaderTimeout = 120 * time.Second
- // BodyIdleTimeout bounds one wait for response body bytes: a read that
- // gets nothing for this long fails. It is armed only while a read is
+ // BodyIdleTimeout bounds how long a body read may wait while the
+ // connection under it receives nothing. It runs only while a read is
// in progress, so a caller pausing between reads is never cut off.
BodyIdleTimeout = 120 * time.Second
)
@@ -58,15 +69,79 @@ func withStallBounds(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfi
// APIOption on the config it reaches every client built from it, the
// credential clients the loader builds (STS) included.
func stallBounds(header, idle time.Duration) []func(*awsconfig.LoadOptions) error {
- client := awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) {
- t.ResponseHeaderTimeout = header
- })
return []func(*awsconfig.LoadOptions) error{
- awsconfig.WithHTTPClient(client),
+ awsconfig.WithHTTPClient(stallHTTPClient(header)),
awsconfig.WithAPIOptions([]func(*middleware.Stack) error{idleBodyOption(idle)}),
}
}
+// StallHTTPClient and StallAPIOptions are the two bounds for a client built
+// from bare service options rather than a loaded config (awss3.New(opts)):
+// set the first as the options' HTTPClient and append the second to their
+// APIOptions.
+func StallHTTPClient() *awshttp.BuildableClient { return stallHTTPClient(ResponseHeaderTimeout) }
+
+func StallAPIOptions() []func(*middleware.Stack) error {
+ return []func(*middleware.Stack) error{idleBodyOption(BodyIdleTimeout)}
+}
+
+// stallHTTPClient is the SDK's default client with the header timeout, and
+// every connection it dials counting its reads (progressConn), which is
+// what the body bound measures progress by.
+//
+// A non-legacy defaults mode (AWS_DEFAULTS_MODE) makes a service client
+// replace DialContext with a plain dialer's; its connections then go
+// uncounted and the body bound stands aside for them (idleBodyMiddleware),
+// so the header timeout is all that applies. The default is legacy.
+func stallHTTPClient(header time.Duration) *awshttp.BuildableClient {
+ return awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) {
+ t.ResponseHeaderTimeout = header
+ if dial := t.DialContext; dial != nil {
+ t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ c, err := dial(ctx, network, addr)
+ if err != nil || c == nil {
+ return c, err
+ }
+ return &progressConn{Conn: c}, nil
+ }
+ }
+ })
+}
+
+// progressConn records when the connection last received bytes. Progress is
+// measured here, below TLS and below HTTP's chunk decoding: one body Read
+// can span many socket reads (net/http's chunked reader keeps filling the
+// caller's buffer until the chunk ends), so the time a single Read takes says
+// nothing about whether the store is still sending.
+type progressConn struct {
+ net.Conn
+ last atomic.Int64 // UnixNano of the last read that returned bytes; 0 before any
+}
+
+func (c *progressConn) Read(p []byte) (int, error) {
+ n, err := c.Conn.Read(p)
+ if n > 0 {
+ c.last.Store(time.Now().UnixNano())
+ }
+ return n, err
+}
+
+// connProgress finds the progressConn under the connection a request got:
+// net/http hands GotConn the TLS connection over it for https.
+func connProgress(c net.Conn) *progressConn {
+ for i := 0; i < 4 && c != nil; i++ {
+ if pc, ok := c.(*progressConn); ok {
+ return pc
+ }
+ u, ok := c.(interface{ NetConn() net.Conn })
+ if !ok {
+ return nil
+ }
+ c = u.NetConn()
+ }
+ return nil
+}
+
// idleBodyID names the body-bounding middleware.
const idleBodyID = "rootaws.BodyIdleTimeout"
@@ -88,18 +163,34 @@ func (idleBodyMiddleware) ID() string { return idleBodyID }
func (m idleBodyMiddleware) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
middleware.DeserializeOutput, middleware.Metadata, error) {
+ // The connection this attempt's request was sent on. The trace composes
+ // with any the caller or the SDK set; it only observes.
+ var conn atomic.Pointer[progressConn]
+ ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) {
+ if pc := connProgress(info.Conn); pc != nil {
+ conn.Store(pc)
+ }
+ }})
out, md, err := next.HandleDeserialize(ctx, in)
if err != nil {
return out, md, err
}
+ pc := conn.Load()
+ if pc == nil {
+ // Not one of ours (another HTTP client, a non-legacy defaults
+ // mode): no way to tell a stall from a slow chunk, so no body
+ // bound rather than one that could cut a healthy transfer.
+ return out, md, nil
+ }
if resp, ok := out.RawResponse.(*smithyhttp.Response); ok && resp.Body != nil && resp.Body != http.NoBody {
- resp.Body = &idleBody{rc: resp.Body, idle: m.idle}
+ resp.Body = &idleBody{rc: resp.Body, idle: m.idle, conn: pc}
}
return out, md, nil
}
-// bodyStallError is a body read that got no bytes for the idle bound. It is
-// a timeout, as the transport's own header timeout is.
+// bodyStallError is a body read that waited the idle bound with the
+// connection receiving nothing. It is a timeout, as the transport's own
+// header timeout is.
type bodyStallError struct{ idle time.Duration }
func (e bodyStallError) Error() string {
@@ -108,38 +199,69 @@ func (e bodyStallError) Error() string {
func (bodyStallError) Timeout() bool { return true }
func (bodyStallError) Temporary() bool { return true }
-// idleBody fails a Read that waits past idle by closing the body under it,
-// which is how net/http aborts a pending read. Reads are not concurrent (an
-// io.Reader's contract), so one timer serves them all.
+// idleBody fails a Read during which the connection has received nothing
+// for idle, by closing the body under it, which is how net/http aborts a
+// pending read. Quiet time counts from the later of the Read's start and the
+// connection's last received bytes, so neither a consumer's pause between
+// reads nor a long Read that keeps receiving is a stall. With HTTP/2 any
+// stream's bytes count as progress, which can only delay a timeout.
type idleBody struct {
- rc io.ReadCloser
- idle time.Duration
- timer *time.Timer
- stalled atomic.Bool
+ rc io.ReadCloser
+ idle time.Duration
+ conn *progressConn
+
+ mu sync.Mutex // guards the fields below; never held across I/O
+ timer *time.Timer
+ reading bool
+ readStart int64 // UnixNano
+ stalled bool
}
func (b *idleBody) Read(p []byte) (int, error) {
- if b.stalled.Load() {
+ b.mu.Lock()
+ if b.stalled {
+ b.mu.Unlock()
return 0, bodyStallError{b.idle}
}
+ b.reading, b.readStart = true, time.Now().UnixNano()
if b.timer == nil {
- b.timer = time.AfterFunc(b.idle, b.stall)
+ b.timer = time.AfterFunc(b.idle, b.check)
} else {
b.timer.Reset(b.idle)
}
+ b.mu.Unlock()
+
n, err := b.rc.Read(p)
+
+ b.mu.Lock()
+ b.reading = false
b.timer.Stop()
- // Checked whatever Stop answered: a timer that fired as the read
- // returned may close the body only after this read, and the next one
- // must still say why it failed.
- if b.stalled.Load() {
+ stalled := b.stalled
+ b.mu.Unlock()
+ if stalled {
return n, bodyStallError{b.idle}
}
return n, err
}
-func (b *idleBody) stall() {
- b.stalled.Store(true)
+// check runs when the timer fires: a stall if the connection has been quiet
+// for idle since the Read began, otherwise the timer waits out the rest. A
+// check that fires after its Read returned finds reading false (or a newer
+// Read's start) and does nothing harmful.
+func (b *idleBody) check() {
+ b.mu.Lock()
+ if !b.reading || b.stalled {
+ b.mu.Unlock()
+ return
+ }
+ last := max(b.conn.last.Load(), b.readStart)
+ if quiet := time.Duration(time.Now().UnixNano() - last); quiet < b.idle {
+ b.timer.Reset(b.idle - quiet)
+ b.mu.Unlock()
+ return
+ }
+ b.stalled = true
+ b.mu.Unlock()
b.rc.Close() // unblocks the pending Read
}
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go
index 2cc1d58f0..edc0f3961 100644
--- a/internal/rootaws/stall_test.go
+++ b/internal/rootaws/stall_test.go
@@ -1,10 +1,12 @@
package rootaws
import (
+ "bufio"
"bytes"
"context"
"encoding/pem"
"errors"
+ "fmt"
"io"
"net"
"net/http"
@@ -12,6 +14,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
"time"
@@ -32,17 +35,22 @@ func installedBounds(t *testing.T, cfg aws.Config) (header, idle time.Duration)
if !ok {
t.Fatalf("HTTP client is %T, want a BuildableClient", cfg.HTTPClient)
}
+ return client.GetTransport().ResponseHeaderTimeout, registeredIdle(t, cfg.APIOptions)
+}
+
+func registeredIdle(t *testing.T, opts []func(*middleware.Stack) error) time.Duration {
+ t.Helper()
stack := middleware.NewStack("probe", nil)
- for _, fn := range cfg.APIOptions {
+ for _, fn := range opts {
if err := fn(stack); err != nil {
t.Fatal(err)
}
}
m, ok := stack.Deserialize.Get(idleBodyID)
if !ok {
- t.Fatal("no body idle bound among the config's APIOptions")
+ t.Fatal("no body idle bound among the APIOptions")
}
- return client.GetTransport().ResponseHeaderTimeout, m.(idleBodyMiddleware).idle
+ return m.(idleBodyMiddleware).idle
}
// Every loader in this package hands out a config carrying both bounds at
@@ -79,17 +87,24 @@ func TestLoadersInstallStallBounds(t *testing.T) {
}
}
+// The exported pair for clients built from bare options carries the same
+// production values.
+func TestExportedStallBounds(t *testing.T) {
+ if h := StallHTTPClient().GetTransport().ResponseHeaderTimeout; h != ResponseHeaderTimeout {
+ t.Fatalf("header %s", h)
+ }
+ if idle := registeredIdle(t, StallAPIOptions()); idle != BodyIdleTimeout {
+ t.Fatalf("idle %s", idle)
+ }
+}
+
// The HTTP client stays buildable so a CA bundle still loads, and the
// bundle keeps the header timeout.
func TestStallBoundsKeepCABundle(t *testing.T) {
isolatedAWSEnv(t)
srv := httptest.NewTLSServer(http.NotFoundHandler())
defer srv.Close()
- bundle := filepath.Join(t.TempDir(), "ca.pem")
- if err := os.WriteFile(bundle, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Setenv("AWS_CA_BUNDLE", bundle)
+ t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv))
cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET")
if err != nil {
t.Fatalf("a CA bundle no longer loads: %v", err)
@@ -102,25 +117,39 @@ func TestStallBoundsKeepCABundle(t *testing.T) {
}
}
+func caBundle(t *testing.T, srv *httptest.Server) string {
+ t.Helper()
+ bundle := filepath.Join(t.TempDir(), "ca.pem")
+ if err := os.WriteFile(bundle, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return bundle
+}
+
const (
+ // The stall tests' bounds: a stall must fail, so short is fine.
testHeaderTimeout = 300 * time.Millisecond
testIdleTimeout = 300 * time.Millisecond
+ // The progress tests' bound, with the server's gaps a twentieth of it
+ // (progressGap): a loaded runner would have to delay one write by
+ // nearly a second to fail them falsely.
+ progressIdle = time.Second
+ progressGap = progressIdle / 20
// stallDeadline is how long a stalled call may take to fail in these
// tests: the bound plus slack for a loaded machine, far short of a hang.
stallDeadline = 10 * time.Second
)
-// stallClient is an S3 client over the bounds with the test values, one
-// attempt per call, against url.
-func stallClient(t *testing.T, url string) *awss3.Client {
+// stallClient is an S3 client over the bounds (testHeaderTimeout and idle),
+// one attempt per call, against url. extra adds load options (a CA bundle).
+func stallClient(t *testing.T, url string, idle time.Duration, extra ...func(*awsconfig.LoadOptions) error) *awss3.Client {
t.Helper()
- isolatedAWSEnv(t)
- opts := append(stallBounds(testHeaderTimeout, testIdleTimeout),
+ opts := append(stallBounds(testHeaderTimeout, idle),
awsconfig.WithRegion("us-east-1"),
awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}),
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", "")),
awsconfig.WithRetryMaxAttempts(1))
- cfg, err := awsconfig.LoadDefaultConfig(context.Background(), opts...)
+ cfg, err := awsconfig.LoadDefaultConfig(context.Background(), append(opts, extra...)...)
if err != nil {
t.Fatal(err)
}
@@ -134,6 +163,7 @@ func stallClient(t *testing.T, url string) *awss3.Client {
// closes before the server does.
func stallServer(t *testing.T, handler func(w http.ResponseWriter, r *http.Request, done <-chan struct{})) string {
t.Helper()
+ isolatedAWSEnv(t)
done := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(w, r, done) }))
t.Cleanup(srv.Close)
@@ -162,36 +192,65 @@ func wantTimeout(t *testing.T, err error, start time.Time) {
}
}
-func get(t *testing.T, c *awss3.Client) ([]byte, error) {
+func getObject(t *testing.T, c *awss3.Client) (io.ReadCloser, error) {
t.Helper()
out, err := c.GetObject(context.Background(), &awss3.GetObjectInput{Bucket: aws.String("b"), Key: aws.String("k")})
if err != nil {
return nil, err
}
- defer out.Body.Close()
- return io.ReadAll(out.Body)
+ return out.Body, nil
+}
+
+func get(t *testing.T, c *awss3.Client) ([]byte, error) {
+ t.Helper()
+ body, err := getObject(t, c)
+ if err != nil {
+ return nil, err
+ }
+ defer body.Close()
+ return io.ReadAll(body)
}
// (a) A store that takes the request and never sends headers.
func TestStallNoHeadersFails(t *testing.T) {
url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { block(r, done) })
start := time.Now()
- _, err := get(t, stallClient(t, url))
+ _, err := get(t, stallClient(t, url, testIdleTimeout))
wantTimeout(t, err, start)
}
+func stallAfterSome(w http.ResponseWriter, r *http.Request, done <-chan struct{}) {
+ w.Header().Set("Content-Length", "1048576")
+ w.WriteHeader(http.StatusOK)
+ w.Write(bytes.Repeat([]byte("x"), 1024))
+ w.(http.Flusher).Flush()
+ block(r, done)
+}
+
// (b) Headers, part of the body, then nothing: a streamed GetObject body
// read by the caller.
func TestStallBodyFailsGetObject(t *testing.T) {
- url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) {
- w.Header().Set("Content-Length", "1048576")
- w.WriteHeader(http.StatusOK)
- w.Write(bytes.Repeat([]byte("x"), 1024))
- w.(http.Flusher).Flush()
- block(r, done)
- })
+ url := stallServer(t, stallAfterSome)
start := time.Now()
- _, err := get(t, stallClient(t, url))
+ _, err := get(t, stallClient(t, url, testIdleTimeout))
+ wantTimeout(t, err, start)
+ var stall bodyStallError
+ if !errors.As(err, &stall) {
+ t.Fatalf("not the body bound: %v", err)
+ }
+}
+
+// (b) over TLS: the bound finds its connection under the TLS one, with a
+// CA bundle loaded as well.
+func TestStallBodyFailsOverTLS(t *testing.T) {
+ isolatedAWSEnv(t)
+ done := make(chan struct{})
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { stallAfterSome(w, r, done) }))
+ t.Cleanup(srv.Close)
+ t.Cleanup(func() { close(done) })
+ t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv))
+ start := time.Now()
+ _, err := get(t, stallClient(t, srv.URL, testIdleTimeout))
wantTimeout(t, err, start)
var stall bodyStallError
if !errors.As(err, &stall) {
@@ -209,15 +268,14 @@ func TestStallBodyFailsDecodedAnswer(t *testing.T) {
block(r, done)
})
start := time.Now()
- _, err := stallClient(t, url).ListObjectsV2(context.Background(), &awss3.ListObjectsV2Input{Bucket: aws.String("b")})
+ _, err := stallClient(t, url, testIdleTimeout).ListObjectsV2(context.Background(), &awss3.ListObjectsV2Input{Bucket: aws.String("b")})
wantTimeout(t, err, start)
}
-// (c) A large body that trickles in, never idle as long as the bound but
-// taking many times the bound overall, arrives whole.
+// (c) A body that trickles in as many flushed chunks, never quiet for
+// long but taking several times the bound overall, arrives whole.
func TestTrickleBodySucceeds(t *testing.T) {
- const chunks, size = 40, 16 << 10
- gap := testIdleTimeout / 6
+ const chunks, size = 60, 4 << 10 // 60 gaps of progressIdle/20: 3x the bound
url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) {
w.WriteHeader(http.StatusOK)
for i := 0; i < chunks; i++ {
@@ -225,20 +283,99 @@ func TestTrickleBodySucceeds(t *testing.T) {
return
}
w.(http.Flusher).Flush()
- time.Sleep(gap)
+ time.Sleep(progressGap)
}
})
start := time.Now()
- body, err := get(t, stallClient(t, url))
+ body, err := get(t, stallClient(t, url, progressIdle))
if err != nil {
t.Fatalf("a steady transfer was cut off after %s: %v", time.Since(start), err)
}
if len(body) != chunks*size {
t.Fatalf("got %d bytes, want %d", len(body), chunks*size)
}
- if d := time.Since(start); d < 3*testIdleTimeout {
- t.Fatalf("the transfer took %s, not long enough to prove anything", d)
+}
+
+// (c) One HTTP chunk delivered in small fragments, each well inside the
+// bound, read with a buffer larger than the chunk: net/http's chunked reader
+// keeps filling that buffer until the chunk ends, so a single Read spans
+// every fragment and lasts longer than the bound while bytes keep arriving
+// (Astra round 1, P1). It must not be cut.
+func TestOneSlowChunkInOneReadSucceeds(t *testing.T) {
+ isolatedAWSEnv(t)
+ const fragments, fragment = 60, 64 // 60 gaps of progressIdle/20: 3x the bound
+ want := bytes.Repeat([]byte("z"), fragments*fragment)
+ url := rawServer(t, func(c net.Conn) {
+ fmt.Fprintf(c, "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: application/octet-stream\r\n\r\n%x\r\n", len(want))
+ for i := 0; i < fragments; i++ {
+ if _, err := c.Write(want[i*fragment : (i+1)*fragment]); err != nil {
+ return
+ }
+ time.Sleep(progressGap)
+ }
+ io.WriteString(c, "\r\n0\r\n\r\n")
+ })
+ body, err := getObject(t, stallClient(t, url, progressIdle))
+ if err != nil {
+ t.Fatal(err)
}
+ defer body.Close()
+ buf := make([]byte, 2*len(want))
+ start := time.Now()
+ n, err := body.Read(buf)
+ took := time.Since(start)
+ if err != nil && err != io.EOF {
+ t.Fatalf("a chunk arriving steadily was cut off after %s: %v", took, err)
+ }
+ if took < progressIdle {
+ t.Fatalf("the Read took %s, shorter than the bound: the test proves nothing", took)
+ }
+ rest, err := io.ReadAll(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := append(buf[:n], rest...); !bytes.Equal(got, want) {
+ t.Fatalf("got %d bytes, want %d", len(got), len(want))
+ }
+}
+
+// rawServer answers each request on a connection with respond, writing the
+// response bytes itself; it closes its listener and connections at cleanup.
+func rawServer(t *testing.T, respond func(net.Conn)) string {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mu sync.Mutex
+ var conns []net.Conn
+ t.Cleanup(func() {
+ ln.Close()
+ mu.Lock()
+ defer mu.Unlock()
+ for _, c := range conns {
+ c.Close()
+ }
+ })
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ mu.Lock()
+ conns = append(conns, c)
+ mu.Unlock()
+ go func() {
+ defer c.Close()
+ if _, err := http.ReadRequest(bufio.NewReader(c)); err != nil {
+ return
+ }
+ respond(c)
+ }()
+ }
+ }()
+ return "http://" + ln.Addr().String()
}
// A caller that pauses between reads longer than the bound is not cut off:
@@ -248,17 +385,17 @@ func TestPausingReaderSucceeds(t *testing.T) {
url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) {
io.WriteString(w, want)
})
- out, err := stallClient(t, url).GetObject(context.Background(), &awss3.GetObjectInput{Bucket: aws.String("b"), Key: aws.String("k")})
+ body, err := getObject(t, stallClient(t, url, testIdleTimeout))
if err != nil {
t.Fatal(err)
}
- defer out.Body.Close()
+ defer body.Close()
head := make([]byte, 10)
- if _, err := io.ReadFull(out.Body, head); err != nil {
+ if _, err := io.ReadFull(body, head); err != nil {
t.Fatal(err)
}
time.Sleep(3 * testIdleTimeout)
- rest, err := io.ReadAll(out.Body)
+ rest, err := io.ReadAll(body)
if err != nil {
t.Fatalf("a pausing reader was cut off: %v", err)
}