Files
ziti/controller/api/timeouts.go
T
Paul Lorenz 54bfb3ca21 Return a readable 503 when an API request times out. Fixes #4509
- extends the per-request write deadline in TimeoutHandler when the server's write timeout would expire before the timeout response can be written, so clients get the 503 instead of a TLS error
- passes the server's write timeout from each API's xweb server config into TimeoutHandler through a shared helper
- carries the request context on REST change contexts and refuses to dispatch a command once that request's deadline has passed
- updates xweb to v3.0.6, whose compression middleware supports http.ResponseController and keeps the response status for Brotli
- tests timeout responses over HTTP/1.1 and h2 for each compression encoding, and the dispatcher deadline check
2026-11-03 23:29:55 -05:00

248 lines
6.8 KiB
Go

/*
Copyright NetFoundry Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"path"
goruntime "runtime"
"strings"
"sync"
"time"
"github.com/go-openapi/runtime"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/foundation/v2/debugz"
"github.com/openziti/foundation/v2/errorz"
)
// timeoutResponseMargin is how long past a TimeoutHandler's timeout the connection must stay writable so the
// buffered response, or the timeout error, can be sent.
const timeoutResponseMargin = 5 * time.Second
// TimeoutHandler wraps next, buffering its response. If next does not finish within timeout, apiErr is written
// as a JSON 503 using mapper. If next panics, an empty 500 is written. Downstream handlers are encouraged to
// implement their own panic recovery.
//
// On timeout next keeps running with a cancelled request context and its output is discarded, so any change it
// makes may still be applied after the client has received the error.
//
// writeTimeout is the server's write timeout. When it is shorter than timeout plus a margin, the per-request
// write deadline is extended so the response can still be written; this requires the http.ResponseWriter
// passed in to support http.ResponseController. Zero means the server has no write timeout.
func TimeoutHandler(next http.Handler, timeout, writeTimeout time.Duration, apiErr *errorz.ApiError, mapper ResponseMapper) http.Handler {
return &timeoutHandler{
next: next,
apiError: apiErr,
timeout: timeout,
writeTimeout: writeTimeout,
producer: runtime.JSONProducer(),
responseMapper: mapper,
}
}
type timeoutHandler struct {
next http.Handler
timeout time.Duration
writeTimeout time.Duration
apiError *errorz.ApiError
producer runtime.Producer
responseMapper ResponseMapper
deadlineWarnOnce sync.Once
}
// ensureWriteDeadline keeps the connection writable until the timeout response can be sent. net/http starts the
// write deadline before the handler runs, so a write timeout no longer than timeout expires before the 503 is
// written, and a failed TLS write leaves the connection unusable for any response.
func (h *timeoutHandler) ensureWriteDeadline(w http.ResponseWriter) {
needed := h.timeout + timeoutResponseMargin
if h.writeTimeout <= 0 || h.writeTimeout >= needed {
return
}
if err := http.NewResponseController(w).SetWriteDeadline(time.Now().Add(needed)); err != nil {
h.deadlineWarnOnce.Do(func() {
pfxlog.Logger().WithError(err).
WithField("writeTimeout", h.writeTimeout).
WithField("timeout", h.timeout).
Warn("unable to extend write deadline, requests that time out may fail without a response")
})
}
}
func (h *timeoutHandler) errorBody(w http.ResponseWriter, r *http.Request) error {
if h.apiError != nil {
requestId := ""
rc, _ := GetRequestContextFromHttpContext(r)
if rc != nil {
requestId = rc.GetId()
}
apiError := h.responseMapper.MapApiError(requestId, h.apiError)
err := h.producer.Produce(w, apiError)
return err
}
return errors.New("no timeout api error specified")
}
func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.ensureWriteDeadline(w)
ctx, cancelCtx := context.WithTimeout(r.Context(), h.timeout)
defer cancelCtx()
r = r.WithContext(ctx)
done := make(chan struct{})
tw := &timeoutWriter{
writer: w,
header: make(http.Header),
request: r,
}
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
pfxlog.Logger().Errorf("panic caught by timeout next: %v\n%v", p, debugz.GenerateLocalStack())
panicChan <- p
}
}()
h.next.ServeHTTP(tw, r)
close(done)
}()
select {
case <-panicChan:
tw.mu.Lock()
defer tw.mu.Unlock()
dst := w.Header()
for k, vv := range tw.header {
dst[k] = vv
}
w.WriteHeader(http.StatusInternalServerError)
case <-done:
tw.mu.Lock()
defer tw.mu.Unlock()
dst := w.Header()
for k, vv := range tw.header {
dst[k] = vv
}
if !tw.wroteHeader {
tw.code = http.StatusOK
}
w.WriteHeader(tw.code)
_, _ = w.Write(tw.buffer.Bytes())
case <-ctx.Done():
tw.mu.Lock()
defer tw.mu.Unlock()
pfxlog.Logger().WithFields(map[string]interface{}{
"url": r.URL,
"method": r.Method,
}).Errorf("timeout for request hit, returning Service Unavailable 503")
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
_ = h.errorBody(w, r)
tw.timedOut = true
}
}
// timeoutWriter is a proxy http.ResponseWriter that is used by TimeoutHandler.
type timeoutWriter struct {
writer http.ResponseWriter
header http.Header
buffer bytes.Buffer
request *http.Request
mu sync.Mutex
timedOut bool
wroteHeader bool
code int
}
var _ http.Pusher = (*timeoutWriter)(nil)
func (tw *timeoutWriter) Push(target string, opts *http.PushOptions) error {
if pusher, ok := tw.writer.(http.Pusher); ok {
return pusher.Push(target, opts)
}
return http.ErrNotSupported
}
func (tw *timeoutWriter) Header() http.Header { return tw.header }
func (tw *timeoutWriter) Write(p []byte) (int, error) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return 0, http.ErrHandlerTimeout
}
if !tw.wroteHeader {
tw.writeHeaderLocked(http.StatusOK)
}
return tw.buffer.Write(p)
}
func (tw *timeoutWriter) writeHeaderLocked(code int) {
checkWriteHeaderCode(code)
switch {
case tw.timedOut:
return
case tw.wroteHeader:
if tw.request != nil {
caller := relevantCaller()
pfxlog.Logger().Errorf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
}
default:
tw.wroteHeader = true
tw.code = code
}
}
func (tw *timeoutWriter) WriteHeader(code int) {
tw.mu.Lock()
defer tw.mu.Unlock()
tw.writeHeaderLocked(code)
}
func checkWriteHeaderCode(code int) {
if code < 100 || code > 999 {
panic(fmt.Sprintf("invalid WriteHeader code %v", code))
}
}
func relevantCaller() goruntime.Frame {
pc := make([]uintptr, 16)
n := goruntime.Callers(1, pc)
frames := goruntime.CallersFrames(pc[:n])
var frame goruntime.Frame
for {
frame, more := frames.Next()
if !strings.HasPrefix(frame.Function, "net/http.") && !strings.HasPrefix(frame.Function, "github.com/openziti/ziti/v2/controller/api_impl/timeout") {
return frame
}
if !more {
break
}
}
return frame
}