Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions internal/gateway/abuse.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,22 @@ func peekResponseBody(resp *http.Response) []byte {
return prefix
}

// bufferRetryResponse releases a response's transport before the next attempt,
// retaining at most 64 KiB of its body, including any prefix read before an error.
// bufferRetryResponse retains an error response across later attempts.
// doInferenceAttempt has already bounded and buffered non-2xx bodies under the
// error-body deadline, so this read is memory-only. Keep the same size cap: a
// second, smaller cap would truncate otherwise valid error JSON on a retry.
func bufferRetryResponse(resp *http.Response) {
if resp == nil || resp.Body == nil {
return
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(body))
resp.ContentLength = int64(len(body))
resp.Header.Del("Content-Length")
resp.Header.Del("Transfer-Encoding")
resp.TransferEncoding = nil
resp.Trailer = nil
}

// replaceRetryResponse keeps the latest HTTP response across transport failures
Expand Down
41 changes: 37 additions & 4 deletions internal/gateway/first_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,15 @@ func (b *attemptBody) Close() error {
return b.body.Close()
}

// Non-2xx bodies are buffered before classification or forwarding; see
// doInferenceAttempt. The time cap applies even when the optional attempt
// deadline is disabled; cancellation interrupts the transport read without a
// background reader.
const (
maxErrorBodyBytes = 1 << 20
errorBodyTimeout = 2 * time.Second
)

// doInferenceAttempt sends one upstream attempt through client under two
// optional deadlines. It passes straight through to client.Do when both
// timeouts are zero or negative, and for the /systemone path.
Expand All @@ -221,8 +230,10 @@ func (b *attemptBody) Close() error {
// errFirstEventTimeout as the error when that deadline caused the failure, and
// closing the returned body also releases the attempt's context.
func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeout, attemptTimeout time.Duration) (*http.Response, error) {
if (firstEventTimeout <= 0 && attemptTimeout <= 0) || strings.HasSuffix(req.URL.Path, "/systemone") {
return client.Do(req)
// /systemone skips the optional deadlines, but its error bodies are still
// bounded below like every other attempt's.
if strings.HasSuffix(req.URL.Path, "/systemone") {
firstEventTimeout, attemptTimeout = 0, 0
}
trace := &attemptTrace{}
ctx, cancel := context.WithCancelCause(req.Context())
Expand Down Expand Up @@ -273,8 +284,30 @@ func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeou
cancel(nil)
return resp, &phasedError{err: err, phase: trace.phase()}
}
// Without a first-event wait the attempt is done once headers arrive.
if firstEventTimeout <= 0 || resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
if resp.StatusCode/100 != 2 {
// Error bodies are read by classification, retries and the error copied
// to the client, all after this function returns and without a deadline
// of their own: a peer that sends headers and then stalls would hold the
// retry loop until the request budget is gone. Read at most
// maxErrorBodyBytes here under an absolute errorBodyTimeout (not reset
// by a peer trickling bytes; the attempt timer also stays armed), then
// close without draining. Status, headers and whatever bytes arrived are
// kept, so 403/429/5xx classification and retries are unchanged.
bodyTimer := time.AfterFunc(errorBodyTimeout, func() { cancel(context.DeadlineExceeded) })
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))
bodyTimer.Stop()
_ = resp.Body.Close()
cancel(nil)
resp.Body = io.NopCloser(bytes.NewReader(body))
resp.ContentLength = int64(len(body))
resp.Header.Del("Content-Length")
resp.Header.Del("Transfer-Encoding")
resp.TransferEncoding = nil
resp.Trailer = nil
return resp, nil
}
// Without a first-event wait a successful attempt commits at headers.
if firstEventTimeout <= 0 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
if attemptTimer != nil {
if cause := commitDeadline(); cause != nil {
cancel(nil)
Expand Down
11 changes: 6 additions & 5 deletions internal/httpx/body.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"io"
)

// DrainAndClose discards up to 64 KiB of body and closes it, so the
// connection can be reused. A nil body is ignored. The bound keeps a small
// response fully drained while a large or endless one cannot hold the caller
// for more than that amount of data.
// DrainAndClose closes body without speculative reads. A byte-limited drain
// is not time-limited: even one unread byte can stall the caller forever.
// Callers that want connection reuse must consume the body under their own
// deadline first; the regular and Bun transports already reuse a connection
// after a clean EOF. Closing an unread body only gives up reuse. The name is
// kept for existing callers. A nil body is ignored.
func DrainAndClose(body io.ReadCloser) {
if body == nil {
return
}
_, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10))
_ = body.Close()
}