Ограничить ожидание зависимостей и отвечать 503 при их недоступности
This commit is contained in:
@@ -307,6 +307,26 @@ func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) {
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
}
|
||||
|
||||
// Everything below Timeout sees one deadline, so waiting on a dependency
|
||||
// ends with the request instead of holding the client.
|
||||
func TestTimeoutBoundsTheRequestContext(t *testing.T) {
|
||||
e := newEngine(t, nil)
|
||||
e.GET("/slow", httpx.Timeout(50*time.Millisecond), func(c *gin.Context) {
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
httpx.Error(c, apperr.Wrap(apperr.KindUnavailable, "gave up", c.Request.Context().Err()))
|
||||
case <-time.After(5 * time.Second):
|
||||
httpx.JSON(c, http.StatusOK, gin.H{})
|
||||
}
|
||||
})
|
||||
start := time.Now()
|
||||
rec, eb := do(t, e, http.MethodGet, "/slow", "", nil)
|
||||
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("request took %v, want it cut at the 50ms deadline", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
|
||||
t.Helper()
|
||||
var entry map[string]any
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
@@ -93,6 +94,18 @@ func recovery() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout bounds the whole request with one deadline: waiting for a pooled
|
||||
// connection, SQL statements and session lookups all observe it, so a hung
|
||||
// dependency ends in a 503 within d instead of holding the client.
|
||||
func Timeout(d time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
|
||||
defer cancel()
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
|
||||
// decoder as *http.MaxBytesError.
|
||||
func bodyLimit(maxBytes int64) gin.HandlerFunc {
|
||||
|
||||
Reference in New Issue
Block a user