Files
seaweedfs/weed/s3api/s3api_circuit_breaker_test.go
T
77a6787335 Bound upload memory: admission by size, gateway holder writes, 503/SlowDown back-pressure, body deadline (#13021)
* util: one admission rule for upload limits

* operation: mark gateway fan-out holder writes as client traffic

* volume: bound upload admission, limit gateway holder writes, 503 on timeout

* volume: charge unknown-length uploads half the budget, document client wait cap

* s3, filer: admit uploads by inFlight+size and charge unknown lengths a chunk

* s3: answer a volume overload as SlowDown with Retry-After

* operation: cut an upload whose body crawls below the minimum rate on any host

* operation: make the slow-commit deadline test honour the request context

* s3: stop chunk uploads when the client goes away

* operation: treat a body deadline cut as back-pressure, not a same-holder retry

A body that crawls past the body deadline returns from retriedUploadData at
once, like an overload, and counts toward the single reassign the chunk loop
and the filer retry gate give back-pressure. A watchdog cut keeps its retry on
a fresh conn. Both still match ErrUploadStalled and stay reassignable.

* operation: apply the body deadline only to uploads that opt in

UploadOption.BodyDeadline and ChunkedUploadOption.BodyDeadline turn the
body deadline on; S3 chunk uploads (relay and fan-out) and the filer's chunk
loop set it. Mount, filer.sync, filer.copy and UploadWithRetry keep the stall
watchdog only, as before the deadline existed.

* s3, operation: check a chunk cancelled with its client is deleted from every holder

A volume commits on a context that ignores the cancel, so a chunk whose
caller went away after sending the body may still land. The chunk loop
already deletes the fid from every holder after a failed attempt; pin that
for the relay and fan-out paths and for an S3 PUT whose client goes away.

* s3: count a request's declared bytes in the circuit breaker byte limits

The per-bucket and global byte counters go back to the declared length (an
unknown length counts one chunk), so a bucket bytes limit still rejects a
single PUT larger than it. Only the upload budget uses the capped gateway
charge.

* s3: answer copy chunk overloads as SlowDown, tidy the client-gone checks

CopyObject and UploadPartCopy map a volume overload or an exhausted stall to
SlowDown, as PutObject does. The client-gone log check matches the mapper's
context.Canceled test, the truncated-body case drops a check the first case
already makes, and the Retry-After test reads the headers actually sent.

* filer, volume: clamp the filer charge chunk, set the upload gauge under the lock

A filer with -maxMB 0 charges its default chunk size instead of nothing. The
volume server sets its in-flight upload gauge inside the critical section.
The upload limit tests wait until the waiter is parked before releasing,
check handleUploadRequest gives its charge back, and use CI-safe bounds.

* volume: cap the Rust server's client upload-slot wait at 5s

Same cap as the Go volume server's volumeClientUploadWaitCap, so a gateway's
body deadline never fires before the 503.

* operation: reflow the body deadline comment

* volume(rs): count a gateway's src=client holder write against the upload limit

Mirrors operation.IsReplicaForward: only a primary-to-replica forward
skips the upload budget; a gateway's ?type=replicate&src=client fan-out
waits like any client write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): admit uploads by inFlight+size, reserved atomically

Mirrors the Go volume server's waitForUploadSlot: an upload is admitted
by util.UploadAdmits (idle server, or inFlight + size within the limit)
and reserves its bytes in the same step, so concurrent waiters cannot
all pass one check. Primary-to-replica forwards and unlimited servers
are counted but never refused. UploadLimitCond counts once per waiting
upload, and the wake-up is armed before each check so a release in
between is not missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): charge an unknown-length upload against the upload limit

Mirrors the Go volume server's uploadCharge: a chunked upload without
Content-Length reserves one file's worth of budget, at most half the
limit and at least 1 byte, instead of 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): a zero -inflightUploadDataTimeout waits the 5s client cap

The Go volume server now reads 0 as the 5s cap (its flag help says so);
the Rust server used a 2s wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): close a rejected large or unknown-length HTTP/1 upload

Mirrors the Go volume server's uploadRejectCloseThreshold: the 503 for
a body over 256 KiB, or one without a length, carries Connection: close
instead of keeping the connection for a body nobody reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): drop src from a primary's replica forward

A client upload carrying src=client kept it on the forward, so replicas
treated the forward as gateway fan-out and could refuse it after the
primary had already appended. Go's ReplicatedWrite builds a fresh query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep the upload admission CAS buildable on rust 1.91.1

Atomic try_update is stable only since 1.95.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): refuse an upload the in-flight counter cannot hold

A replica forward added its charge with fetch_add, so a Content-Length
near i64::MAX wrapped the shared counter negative and let later client
uploads past admission. The forward now reserves with a checked add and
answers 503 when the size does not fit; the client CAS adds only after
admission passes. With no upload limit the counter only feeds the gauge,
so it keeps wrapping arithmetic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse an upload the in-flight counter cannot hold

A replica forward added its charge unchecked, so a Content-Length near
math.MaxInt64 wrapped inFlightUploadDataSize negative and let later
client uploads past admission. Under the lock the reservation now
checks that the counter can hold the charge and answers 503 otherwise,
matching the Rust volume server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: keep the request body on a rejected upload

Replacing r.Body with http.NoBody hid the server's early close of the
unread body from net/http before Go 1.27, so it skipped the FIN-then-wait
close and reset the connection under a client still sending. Go 1.26.6,
the version go.mod declares, then failed
TestUploadLimit503ReachesGoClientForLargeBody with a write error instead of
the 503.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: compare upload admission without forming inFlight+size

* operation: reassign a chunk after a 429 as after a 503

* s3: do not count a chunk assignment the client cancelled as a filer failure

* filer: charge an upload by its request chunk size, and an inline upload by its whole body

* s3: hold an aws-chunked body to its X-Amz-Decoded-Content-Length

* volume: answer a rejected small-body upload without waiting for its body

* s3: fill the upload budget before testing that a release wakes every waiter

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:34:47 -08:00

551 lines
19 KiB
Go

package s3api
import (
"bufio"
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
type TestLimitCase struct {
actionName string
limitType string
bucketLimitValue int64
globalLimitValue int64
routineCount int
successCount int64
}
var (
bucket = "/test"
action = s3_constants.ACTION_WRITE
fileSize int64 = 200
TestLimitCases = []*TestLimitCase{
//bucket-LimitTypeCount
{action, s3_constants.LimitTypeCount, 5, 6, 60, 5},
{action, s3_constants.LimitTypeCount, 0, 6, 6, 0},
//global-LimitTypeCount
{action, s3_constants.LimitTypeCount, 6, 5, 6, 5},
{action, s3_constants.LimitTypeCount, 6, 0, 6, 0},
//bucket-LimitTypeBytes
{action, s3_constants.LimitTypeBytes, 1000, 1020, 6, 5},
{action, s3_constants.LimitTypeBytes, 0, 1020, 6, 0},
//global-LimitTypeBytes
{action, s3_constants.LimitTypeBytes, 1020, 1000, 6, 5},
{action, s3_constants.LimitTypeBytes, 1020, 0, 6, 0},
}
)
func TestLimit(t *testing.T) {
for _, tc := range TestLimitCases {
circuitBreakerConfig := &s3_pb.S3CircuitBreakerConfig{
Global: &s3_pb.S3CircuitBreakerOptions{
Enabled: true,
Actions: map[string]int64{
s3_constants.Concat(tc.actionName, tc.limitType): tc.globalLimitValue,
s3_constants.Concat(tc.actionName, tc.limitType): tc.globalLimitValue,
},
},
Buckets: map[string]*s3_pb.S3CircuitBreakerOptions{
bucket: {
Enabled: true,
Actions: map[string]int64{
s3_constants.Concat(tc.actionName, tc.limitType): tc.bucketLimitValue,
},
},
},
}
circuitBreaker := &CircuitBreaker{
counters: make(map[string]*int64),
limitations: make(map[string]int64),
}
err := circuitBreaker.loadCircuitBreakerConfig(circuitBreakerConfig)
if err != nil {
t.Fatal(err)
}
successCount := doLimit(circuitBreaker, tc.routineCount, &http.Request{ContentLength: fileSize}, tc.actionName)
if successCount != tc.successCount {
t.Errorf("successCount not equal, expect=%d, actual=%d, case: %v", tc.successCount, successCount, tc)
}
}
}
func doLimit(circuitBreaker *CircuitBreaker, routineCount int, r *http.Request, action string) int64 {
var successCounter int64
resultCh := make(chan []func(), routineCount)
var wg sync.WaitGroup
for i := 0; i < routineCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
rollbackFn, errCode := circuitBreaker.limit(r, bucket, action)
if errCode == s3err.ErrNone {
atomic.AddInt64(&successCounter, 1)
}
resultCh <- rollbackFn
}()
}
wg.Wait()
close(resultCh)
for fns := range resultCh {
for _, fn := range fns {
fn()
}
}
return successCounter
}
// TestLimitInterceptor verifies the optional request interceptor: it is a no-op
// when nil, runs ahead of the (disabled) breaker logic, and can either reject a
// request or pass it through to the wrapped handler.
func TestLimitInterceptor(t *testing.T) {
readAction := s3_constants.ACTION_READ
newCB := func() *CircuitBreaker {
// Enabled defaults to false and s3a is nil, so without an interceptor
// Limit's handler falls straight through to the wrapped handler.
return &CircuitBreaker{counters: make(map[string]*int64), limitations: make(map[string]int64)}
}
// 1. nil interceptor must not change behavior: the handler still runs.
t.Run("nil interceptor is a no-op", func(t *testing.T) {
cb := newCB()
called := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { called = true }, readAction)
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if !called {
t.Fatal("handler should run when no interceptor is set")
}
})
// 2. a rejecting interceptor runs first and prevents the handler, even
// though the breaker itself is disabled.
t.Run("interceptor can reject", func(t *testing.T) {
cb := newCB()
var order []string
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
order = append(order, "interceptor")
s3err.WriteErrorResponse(w, r, s3err.ErrTooManyRequest) // reject; do not call next
}
}
handlerRan := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
handlerRan = true
order = append(order, "handler")
}, readAction)
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if handlerRan {
t.Fatal("a rejecting interceptor must prevent the handler from running")
}
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503 from ErrTooManyRequest, got %d", rec.Code)
}
if len(order) != 1 || order[0] != "interceptor" {
t.Fatalf("interceptor should run alone, got %v", order)
}
})
// 3. a pass-through interceptor runs before the handler and sees the action.
t.Run("interceptor can pass through", func(t *testing.T) {
cb := newCB()
var order []string
var seenAction string
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
seenAction = action
order = append(order, "interceptor")
next(w, r)
}
}
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
order = append(order, "handler")
}, readAction)
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if seenAction != readAction {
t.Fatalf("interceptor should receive the route action, got %q", seenAction)
}
if len(order) != 2 || order[0] != "interceptor" || order[1] != "handler" {
t.Fatalf("interceptor must run before the handler, got %v", order)
}
})
// 4. installed AFTER Limit() returns: still takes effect, because the
// interceptor is consulted per request rather than captured at
// registration time (the handlers are built during router registration,
// before dependencies that need the running server exist).
t.Run("interceptor installed after registration takes effect", func(t *testing.T) {
cb := newCB()
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {}, readAction) // built while nil
ran := false
cb.Interceptor = func(next http.HandlerFunc, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ran = true
next(w, r)
}
}
h(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/bucket/object", nil))
if !ran {
t.Fatal("interceptor set after Limit() must still run (request-time evaluation)")
}
})
}
func newUploadLimitedCircuitBreaker(option *S3ApiServerOption) *CircuitBreaker {
return &CircuitBreaker{
counters: make(map[string]*int64),
limitations: make(map[string]int64),
s3a: &S3ApiServer{option: option, inFlightDataLimitCond: sync.NewCond(new(sync.Mutex))},
}
}
func putRequest(ctx context.Context, size int) *http.Request {
return httptest.NewRequest(http.MethodPut, "/bucket/object", strings.NewReader(strings.Repeat("x", size))).WithContext(ctx)
}
type readRecorder struct {
r io.Reader
read bool
}
func (b *readRecorder) Read(p []byte) (int, error) {
b.read = true
return b.r.Read(p)
}
func (b *readRecorder) Close() error { return nil }
func holdUploadSlot(t *testing.T, cb *CircuitBreaker, size int) (release func()) {
entered, done := make(chan struct{}), make(chan struct{})
finished := make(chan struct{})
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
close(entered)
<-done
}, s3_constants.ACTION_WRITE)
go func() {
defer close(finished)
h(httptest.NewRecorder(), putRequest(context.Background(), size))
}()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("first upload was not admitted")
}
return func() {
close(done)
<-finished
}
}
func TestLimitUploadSlotWait(t *testing.T) {
t.Run("wait for a slot times out with SlowDown", func(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentFileUploadLimit: 1, InflightUploadDataTimeout: 100 * time.Millisecond})
release := holdUploadSlot(t, cb, 10)
defer release()
ran := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { ran = true }, s3_constants.ACTION_WRITE)
rec := httptest.NewRecorder()
body := &readRecorder{r: strings.NewReader("0123456789")}
req := putRequest(context.Background(), 10)
req.Body = body
start := time.Now()
h(rec, req)
if ran {
t.Fatal("upload ran without a free slot")
}
if body.read {
t.Fatal("rejected upload body was read")
}
if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "SlowDown") {
t.Fatalf("got %d %q, want 503 SlowDown", rec.Code, rec.Body.String())
}
if elapsed := time.Since(start); elapsed < 100*time.Millisecond {
t.Fatalf("rejected after %v, before the wait timeout", elapsed)
}
if n := atomic.LoadInt64(&cb.s3a.inFlightUploads); n != 1 {
t.Fatalf("in-flight uploads %d, want 1", n)
}
})
t.Run("cancelled request stops waiting", func(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentFileUploadLimit: 1})
release := holdUploadSlot(t, cb, 10)
defer release()
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { t.Error("cancelled upload ran") }, s3_constants.ACTION_WRITE)
done := make(chan int)
go func() {
rec := httptest.NewRecorder()
h(rec, putRequest(ctx, 10))
done <- rec.Code
}()
select {
case code := <-done:
if code != 499 {
t.Fatalf("got %d, want 499", code)
}
case <-time.After(5 * time.Second):
t.Fatal("cancelled upload kept waiting for a slot")
}
})
t.Run("freed bytes admit every waiter that fits", func(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 100, InflightUploadDataTimeout: time.Minute})
// A large upload is charged at most half the budget, so two of them
// fill it and the waiters below have to wait for a release.
release := holdUploadSlot(t, cb, 1000)
releaseOther := holdUploadSlot(t, cb, 1000)
defer releaseOther()
if got := atomic.LoadInt64(&cb.s3a.inFlightDataSize); got != 100 {
t.Fatalf("in-flight %d, want the budget full at 100", got)
}
var admitted sync.WaitGroup
var entered atomic.Int32
admitted.Add(2)
proceed := make(chan struct{})
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
entered.Add(1)
admitted.Done()
<-proceed
}, s3_constants.ACTION_WRITE)
var finished sync.WaitGroup
for i := 0; i < 2; i++ {
finished.Add(1)
go func() {
defer finished.Done()
h(httptest.NewRecorder(), putRequest(context.Background(), 10))
}()
}
time.Sleep(50 * time.Millisecond)
if n := entered.Load(); n != 0 {
t.Fatalf("%d waiters entered a full budget", n)
}
release()
bothIn := make(chan struct{})
go func() {
admitted.Wait()
close(bothIn)
}()
select {
case <-bothIn:
case <-time.After(5 * time.Second):
t.Error("only some waiters were admitted after the large upload finished")
}
close(proceed)
finished.Wait()
})
}
func stalledPut(t *testing.T, h http.HandlerFunc) *http.Response {
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err := io.WriteString(conn, "PUT /bucket/object HTTP/1.1\r\nHost: s3\r\nContent-Length: 10\r\n\r\n"); err != nil {
t.Fatal(err)
}
resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
t.Fatalf("no reply while the body is unsent: %v", err)
}
return resp
}
func TestLimitUploadSlotRejectsStalledBody(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentFileUploadLimit: 1, InflightUploadDataTimeout: 100 * time.Millisecond})
release := holdUploadSlot(t, cb, 10)
defer release()
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { t.Error("upload ran without a free slot") }, s3_constants.ACTION_WRITE)
resp := stalledPut(t, h)
if resp.StatusCode != http.StatusServiceUnavailable || !resp.Close {
t.Fatalf("got %d close=%v, want 503 with Connection: close", resp.StatusCode, resp.Close)
}
}
// putThroughLimit sends req through a write-limited handler and reports the
// status and the in-flight bytes seen while the handler ran (-1 if it did not).
func putThroughLimit(cb *CircuitBreaker, req *http.Request) (code int, body string, inFlight int64) {
inFlight = -1
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
inFlight = atomic.LoadInt64(&cb.s3a.inFlightDataSize)
}, s3_constants.ACTION_WRITE)
rec := httptest.NewRecorder()
h(rec, req)
return rec.Code, rec.Body.String(), inFlight
}
func TestLimitUploadSlotNoOvershoot(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 10, InflightUploadDataTimeout: 50 * time.Millisecond})
cb.s3a.inFlightDataSize = 8
code, body, _ := putThroughLimit(cb, putRequest(context.Background(), 4))
if code != http.StatusServiceUnavailable || !strings.Contains(body, "<Code>SlowDown</Code>") {
t.Fatalf("got %d %q, want 503 SlowDown", code, body)
}
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 8 {
t.Fatalf("in-flight bytes %d, want 8", n)
}
}
func TestLimitUploadSlotChargesUnknownLength(t *testing.T) {
const limit = 1 << 20
newCB := func(inFlight int64) *CircuitBreaker {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: limit, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond})
cb.s3a.inFlightDataSize = inFlight
return cb
}
unknown := func() *http.Request {
req := putRequest(context.Background(), 1)
req.ContentLength = -1
return req
}
// an unknown length is charged half the budget, not 0 and not a 4 MiB chunk
cb := newCB(600 << 10)
if code, _, _ := putThroughLimit(cb, unknown()); code != http.StatusServiceUnavailable {
t.Fatalf("got %d, want 503", code)
}
cb = newCB(0)
code, _, inFlight := putThroughLimit(cb, unknown())
if code != http.StatusOK || inFlight != limit/2 {
t.Fatalf("idle: got %d in-flight %d, want 200 and %d", code, inFlight, limit/2)
}
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 {
t.Fatalf("in-flight bytes %d after release, want 0", n)
}
}
func TestLimitUploadSlotUsesDecodedLengthOnlyWhenUnknown(t *testing.T) {
newCB := func() *CircuitBreaker {
return newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 30, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond})
}
req := putRequest(context.Background(), 1)
req.ContentLength = 5000
req.Header.Set("X-Amz-Decoded-Content-Length", "4096")
if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 5000 {
t.Fatalf("known length: in-flight %d, want 5000", inFlight)
}
req = putRequest(context.Background(), 1)
req.ContentLength = -1
req.Header.Set("X-Amz-Content-Sha256", streamingUnsignedPayload)
req.Header.Set("X-Amz-Decoded-Content-Length", "4096")
if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 4096 {
t.Fatalf("unknown length, aws-chunked: in-flight %d, want 4096", inFlight)
}
// Only an aws-chunked body is held to the header, so on any other body it
// cannot lower the charge below the one chunk an unknown length costs.
req = putRequest(context.Background(), 1)
req.ContentLength = -1
req.Header.Set("X-Amz-Decoded-Content-Length", "0")
if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 4<<20 {
t.Fatalf("unknown length, plain body: in-flight %d, want one 4 MiB chunk", inFlight)
}
}
func TestLimitUploadSlotAdmitsHugeObjectBesideSmallOnes(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 64 << 20, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond})
cb.s3a.inFlightDataSize = 32 << 20
req := putRequest(context.Background(), 1)
req.ContentLength = 5 << 30
code, _, inFlight := putThroughLimit(cb, req)
if code != http.StatusOK || inFlight != 48<<20 {
t.Fatalf("got %d in-flight %d, want 200 and %d", code, inFlight, 48<<20)
}
}
// The breaker's byte counters keep their meaning: what the request declares,
// with an unknown length counted as one chunk — not the upload budget's
// charge, which caps at four chunks and at half the budget.
func TestLimitBucketBytesCounterSymmetricForUnknownLength(t *testing.T) {
for _, tc := range []struct {
name string
contentLength int64
want int64
}{
{name: "unknown length counts one chunk", contentLength: -1, want: 4 << 20},
{name: "declared length counts in full", contentLength: 64 << 20, want: 64 << 20},
} {
t.Run(tc.name, func(t *testing.T) {
// A 1 MiB budget charges either request 512 KiB; the counter must not.
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 20, MaxMB: 4})
cb.Enabled = true
key := s3_constants.Concat(s3_constants.ACTION_WRITE, s3_constants.LimitTypeBytes)
cb.limitations[key] = 1 << 40
req := putRequest(context.Background(), 1)
req.ContentLength = tc.contentLength
var during, budget int64
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
during = atomic.LoadInt64(cb.counters[key])
budget = atomic.LoadInt64(&cb.s3a.inFlightDataSize)
}, s3_constants.ACTION_WRITE)
h(httptest.NewRecorder(), req)
if during != tc.want {
t.Fatalf("counter during request %d, want %d", during, tc.want)
}
if budget != 512<<10 {
t.Fatalf("upload budget charge %d, want %d", budget, 512<<10)
}
if n := atomic.LoadInt64(cb.counters[key]); n != 0 {
t.Fatalf("counter after request %d, want 0", n)
}
})
}
}
// A bucket bytes limit still rejects one PUT that declares more than it
// allows, even though the upload budget charges that PUT far less.
func TestLimitBucketBytesRejectsDeclaredOversizedPut(t *testing.T) {
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 30, MaxMB: 4})
cb.Enabled = true
key := s3_constants.Concat("b", s3_constants.ACTION_WRITE, s3_constants.LimitTypeBytes)
cb.limitations[key] = 16 << 20
req := mux.SetURLVars(putRequest(context.Background(), 1), map[string]string{"bucket": "b"})
req.ContentLength = 64 << 20
ran := false
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { ran = true }, s3_constants.ACTION_WRITE)
rec := httptest.NewRecorder()
h(rec, req)
if ran {
t.Fatal("a PUT declaring 64 MiB must not pass a 16 MiB bucket bytes limit")
}
want := s3err.GetAPIError(s3err.ErrRequestBytesExceed)
if rec.Code != want.HTTPStatusCode || !strings.Contains(rec.Body.String(), want.Code) {
t.Fatalf("got %d %q, want %d %s", rec.Code, rec.Body.String(), want.HTTPStatusCode, want.Code)
}
if n := atomic.LoadInt64(cb.counters[key]); n != 0 {
t.Fatalf("bucket counter after rejection %d, want 0", n)
}
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 {
t.Fatalf("upload budget after rejection %d, want 0", n)
}
}