Files
sub2api/backend/internal/server/middleware/request_body_memory.go
T
cyh fdfadb2442 Merge upstream main; classify WithBodyReadTimeout failures
Upstream added WithBodyReadTimeout (gateway.request_body_read_timeout_seconds)
and client-gone handling for body reads. Drop this branch's own server-level
idle-timeout wrapper and server.request_body_idle_timeout setting in favor of
it, and keep the classification and diagnostics on top:

- readRequestBodyChunksWithBudget reports the read error before ctx.Err():
  on HTTP/1 a read deadline also cancels the request context, which turned
  every timeout into context.Canceled. Read errors carry bytes read and
  elapsed time in RequestBodyReadError.
- handleRequestBodyReadError and RejectRequestBodyReadError skip the
  client-gone (empty 499) path for read timeouts, so they are reported as
  408 instead of a client cancellation (HTTP/1) or a generic 400 (HTTP/2).
- Every gateway body read site and both body-reading middlewares log
  payload-free diagnostics, including the client-gone path.
2026-11-07 01:52:36 +08:00

39 lines
1.4 KiB
Go

package middleware
import (
"errors"
"net/http"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/gin-gonic/gin"
)
// RejectRequestBodyReadError handles early ingress termination before the route
// handler runs. Cancelled clients have no response body and an uncommitted
// response is marked 499, matching the gateway handler's cancellation path.
// A read deadline on HTTP/1 also cancels the request context; timeouts are left
// to AbortWithRequestBodyReadFailure (408).
func RejectRequestBodyReadError(c *gin.Context, component string, err error) bool {
if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil && !pkghttputil.IsRequestBodyReadTimeout(err) {
logRequestBodyReadFailure(c, component, pkghttputil.DescribeRequestBodyReadFailure(c.Request, err))
if !c.Writer.Written() {
c.Status(499)
}
c.Abort()
return true
}
return RejectRequestBodyMemoryOverload(c, err)
}
// RejectRequestBodyMemoryOverload keeps temporary capacity errors distinct
// from invalid JSON and the per-request 413 size limit.
func RejectRequestBodyMemoryOverload(c *gin.Context, err error) bool {
if !errors.Is(err, pkghttputil.ErrRequestBodyMemoryBudget) {
return false
}
c.Header("Retry-After", "1")
groupModelAllowlistErrorWriter(c)(c, http.StatusServiceUnavailable, "Request body buffering capacity is exhausted; retry later")
c.Abort()
return true
}