mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
* 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>
204 lines
6.8 KiB
Go
204 lines
6.8 KiB
Go
package s3err
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/xml"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
|
|
"github.com/gorilla/mux"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
|
|
)
|
|
|
|
type mimeType string
|
|
|
|
const (
|
|
mimeNone mimeType = ""
|
|
MimeXML mimeType = "application/xml"
|
|
|
|
errorResponseBodyDrainTimeout = 30 * time.Second
|
|
)
|
|
|
|
func WriteAwsXMLResponse(w http.ResponseWriter, r *http.Request, statusCode int, result interface{}) {
|
|
var bytesBuffer bytes.Buffer
|
|
err := xmlutil.BuildXML(result, xml.NewEncoder(&bytesBuffer))
|
|
if err != nil {
|
|
WriteErrorResponse(w, r, ErrInternalError)
|
|
return
|
|
}
|
|
WriteResponse(w, r, statusCode, bytesBuffer.Bytes(), MimeXML)
|
|
}
|
|
|
|
func WriteXMLResponse(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) {
|
|
WriteResponse(w, r, statusCode, EncodeXMLResponse(response), MimeXML)
|
|
}
|
|
|
|
func WriteEmptyResponse(w http.ResponseWriter, r *http.Request, statusCode int) {
|
|
WriteResponse(w, r, statusCode, []byte{}, mimeNone)
|
|
PostLog(r, statusCode, ErrNone)
|
|
}
|
|
|
|
func WriteErrorResponse(w http.ResponseWriter, r *http.Request, errorCode ErrorCode) {
|
|
WriteErrorResponseWithMessage(w, r, errorCode, "")
|
|
}
|
|
|
|
// WriteErrorResponseWithMessage writes an S3 error response that uses the
|
|
// standard error code mapping (status + Code). When message is non-empty,
|
|
// it overrides the default Message field so the caller can surface why the
|
|
// request was rejected (e.g. which POST policy condition failed) instead
|
|
// of the generic APIError Description.
|
|
func WriteErrorResponseWithMessage(w http.ResponseWriter, r *http.Request, errorCode ErrorCode, message string) {
|
|
r, _ = request_id.Ensure(r)
|
|
apiError := GetAPIError(errorCode)
|
|
errorResponse := ErrorResponseFor(r, errorCode)
|
|
if message != "" {
|
|
errorResponse.Message = message
|
|
}
|
|
drainRequestBody(w, r)
|
|
if apiError.Code == "SlowDown" {
|
|
// Tell the client how long to back off, so an SDK that honours it
|
|
// waits instead of retrying straight into the overload.
|
|
w.Header().Set("Retry-After", "1")
|
|
}
|
|
WriteXMLResponse(w, r, apiError.HTTPStatusCode, errorResponse)
|
|
PostLog(r, apiError.HTTPStatusCode, errorCode)
|
|
}
|
|
|
|
// ErrorResponseFor builds the <Error> document WriteErrorResponse sends for
|
|
// errorCode, for a caller that has to write it into a response already begun.
|
|
func ErrorResponseFor(r *http.Request, errorCode ErrorCode) RESTErrorResponse {
|
|
r, reqID := request_id.Ensure(r)
|
|
vars := mux.Vars(r)
|
|
bucket := vars["bucket"]
|
|
object := vars["object"]
|
|
if strings.HasPrefix(object, "/") {
|
|
object = object[1:]
|
|
}
|
|
return getRESTErrorResponse(GetAPIError(errorCode), r.URL.Path, bucket, object, reqID)
|
|
}
|
|
|
|
// StartStreamingResponse sends the status line and the headers every response
|
|
// carries, without a Content-Length, for a body the caller writes in pieces.
|
|
func StartStreamingResponse(w http.ResponseWriter, r *http.Request, statusCode int, mType mimeType) {
|
|
setCommonHeaders(w, r)
|
|
if mType != mimeNone {
|
|
w.Header().Set("Content-Type", string(mType))
|
|
}
|
|
w.WriteHeader(statusCode)
|
|
}
|
|
|
|
func drainRequestBody(w http.ResponseWriter, r *http.Request) {
|
|
if r == nil || r.Body == nil || r.Body == http.NoBody {
|
|
return
|
|
}
|
|
rc := http.NewResponseController(w)
|
|
if err := rc.SetReadDeadline(time.Now().Add(errorResponseBodyDrainTimeout)); err == nil {
|
|
defer rc.SetReadDeadline(time.Time{})
|
|
}
|
|
_, _ = io.Copy(io.Discard, r.Body)
|
|
}
|
|
|
|
func getRESTErrorResponse(err APIError, resource string, bucket, object, requestID string) RESTErrorResponse {
|
|
return RESTErrorResponse{
|
|
Code: err.Code,
|
|
BucketName: bucket,
|
|
Key: object,
|
|
Message: err.Description,
|
|
Resource: resource,
|
|
RequestID: requestID,
|
|
}
|
|
}
|
|
|
|
// Encodes the response headers into XML format.
|
|
func EncodeXMLResponse(response interface{}) []byte {
|
|
return append([]byte(xml.Header), EncodeXMLBody(response)...)
|
|
}
|
|
|
|
// EncodeXMLBody encodes response without the XML declaration, for a body
|
|
// whose declaration was already sent.
|
|
func EncodeXMLBody(response interface{}) []byte {
|
|
var bytesBuffer bytes.Buffer
|
|
e := xml.NewEncoder(&bytesBuffer)
|
|
e.Encode(response)
|
|
return bytesBuffer.Bytes()
|
|
}
|
|
|
|
func setCommonHeaders(w http.ResponseWriter, r *http.Request) {
|
|
_, reqID := request_id.Ensure(r)
|
|
w.Header().Set(request_id.AmzRequestIDHeader, reqID)
|
|
w.Header().Set("Accept-Ranges", "bytes")
|
|
|
|
// Handle CORS headers for requests with Origin header
|
|
if r.Header.Get("Origin") != "" {
|
|
// Use mux.Vars to detect bucket-specific requests more reliably
|
|
vars := mux.Vars(r)
|
|
bucket := vars["bucket"]
|
|
isBucketRequest := bucket != ""
|
|
|
|
if !isBucketRequest {
|
|
// Service-level request (like OPTIONS /) - apply static CORS if none set
|
|
if w.Header().Get("Access-Control-Allow-Origin") == "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "*")
|
|
w.Header().Set("Access-Control-Expose-Headers", "*")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
}
|
|
} else {
|
|
// Bucket-specific request - preserve existing CORS headers or set default
|
|
// This handles cases where CORS middleware set headers but auth failed
|
|
if w.Header().Get("Access-Control-Allow-Origin") == "" {
|
|
// No CORS headers were set by middleware, so this request doesn't match any CORS rule
|
|
// According to CORS spec, we should not set CORS headers for non-matching requests
|
|
// However, if the bucket has CORS config but request doesn't match,
|
|
// we still should not set headers here as it would be incorrect
|
|
}
|
|
// If CORS headers were already set by middleware, preserve them
|
|
}
|
|
}
|
|
}
|
|
|
|
// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
|
|
func bodyAllowedForStatus(status int) bool {
|
|
switch {
|
|
case status >= 100 && status <= 199:
|
|
return false
|
|
case status == http.StatusNoContent:
|
|
return false
|
|
case status == http.StatusNotModified:
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func WriteResponse(w http.ResponseWriter, r *http.Request, statusCode int, response []byte, mType mimeType) {
|
|
setCommonHeaders(w, r)
|
|
canHaveBody := bodyAllowedForStatus(statusCode)
|
|
if response != nil && canHaveBody {
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
|
}
|
|
if mType != mimeNone {
|
|
w.Header().Set("Content-Type", string(mType))
|
|
}
|
|
w.WriteHeader(statusCode)
|
|
if response != nil && canHaveBody && r.Method != http.MethodHead {
|
|
glog.V(4).Infof("status %d %s: %s", statusCode, mType, string(response))
|
|
_, err := w.Write(response)
|
|
if err != nil {
|
|
glog.V(1).Infof("write err: %v", err)
|
|
}
|
|
w.(http.Flusher).Flush()
|
|
}
|
|
}
|
|
|
|
// If none of the http routes match respond with MethodNotAllowed
|
|
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
|
|
glog.V(2).Infof("unsupported %s %s", r.Method, r.RequestURI)
|
|
WriteErrorResponse(w, r, ErrMethodNotAllowed)
|
|
}
|