Ограничить ожидание зависимостей и отвечать 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 {
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
@@ -71,6 +74,42 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
||||
// which the API answers with 503 instead of 500; any other error is returned
|
||||
// unchanged. Unreachable means: the connection could not be made or broke,
|
||||
// the request deadline passed, or the server refused work (PostgreSQL error
|
||||
// classes 08 connection exception, 53 insufficient resources, 57 operator
|
||||
// intervention such as shutdown or statement timeout).
|
||||
func Classify(err error) error {
|
||||
if err == nil || !unreachable(err) {
|
||||
return err
|
||||
}
|
||||
return apperr.Wrap(apperr.KindUnavailable, "database unavailable", err)
|
||||
}
|
||||
|
||||
func unreachable(err error) bool {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch class := pgErr.Code[:min(2, len(pgErr.Code))]; class {
|
||||
case "08", "53", "57":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if _, ok := errors.AsType[*pgconn.ConnectError](err); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := errors.AsType[net.Error](err); ok {
|
||||
return true
|
||||
}
|
||||
return errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, net.ErrClosed) ||
|
||||
pgconn.Timeout(err) ||
|
||||
pgconn.SafeToRetry(err)
|
||||
}
|
||||
|
||||
// IsUniqueViolation reports whether err is a unique violation of the named
|
||||
// constraint.
|
||||
func IsUniqueViolation(err error, constraint string) bool {
|
||||
|
||||
@@ -4,9 +4,14 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
@@ -133,3 +138,40 @@ func TestIsUniqueViolation(t *testing.T) {
|
||||
t.Fatal("non-database error recognised as a violation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyMarksUnreachableDatabaseAsUnavailable(t *testing.T) {
|
||||
unavailable := map[string]error{
|
||||
"admin shutdown": &pgconn.PgError{Code: "57P01"},
|
||||
"statement timeout": &pgconn.PgError{Code: "57014"},
|
||||
"connection failure": &pgconn.PgError{Code: "08006"},
|
||||
"too many connections": &pgconn.PgError{Code: "53300"},
|
||||
"deadline": fmt.Errorf("query: %w", context.DeadlineExceeded),
|
||||
"network": &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset")},
|
||||
"unexpected eof": fmt.Errorf("read: %w", io.ErrUnexpectedEOF),
|
||||
}
|
||||
for name, err := range unavailable {
|
||||
got := postgres.Classify(err)
|
||||
if apperr.KindOf(got) != apperr.KindUnavailable || !errors.Is(got, err) {
|
||||
t.Errorf("%s: Classify = %v (kind %v), want KindUnavailable keeping the cause", name, got, apperr.KindOf(got))
|
||||
}
|
||||
}
|
||||
for name, err := range map[string]error{
|
||||
"unique violation": &pgconn.PgError{Code: "23505"},
|
||||
"plain": errors.New("boom"),
|
||||
"nil": nil,
|
||||
} {
|
||||
if got := postgres.Classify(err); got != err {
|
||||
t.Errorf("%s: Classify = %v, want the error unchanged", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyRealConnectFailure(t *testing.T) {
|
||||
_, err := postgres.NewPool(context.Background(), "postgres://u:p@127.0.0.1:1/db?connect_timeout=1")
|
||||
if err == nil {
|
||||
t.Fatal("NewPool to a closed port must fail")
|
||||
}
|
||||
if apperr.KindOf(postgres.Classify(err)) != apperr.KindUnavailable {
|
||||
t.Fatalf("connect failure classified as %v: %v", apperr.KindOf(postgres.Classify(err)), err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user