Ограничить ожидание зависимостей и отвечать 503 при их недоступности
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user