Ограничить ожидание зависимостей и отвечать 503 при их недоступности

This commit is contained in:
2026-10-06 15:13:04 +03:00
parent 9890482747
commit f6acdf91e0
10 changed files with 313 additions and 21 deletions
@@ -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)
}
}