Ограничить ожидание зависимостей и отвечать 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
+16 -2
View File
@@ -4,6 +4,7 @@
package app
import (
"context"
"log/slog"
"time"
@@ -34,19 +35,32 @@ type Deps struct {
Sessions *redis.Client
SessionTTL time.Duration
MaxBodyBytes int64
// RequestTimeout bounds every API request; zero means the default.
RequestTimeout time.Duration
}
// defaultRequestTimeout stays below the server's 10s write timeout, so a
// request that gives up on a dependency can still write its 503.
const defaultRequestTimeout = 5 * time.Second
func New(d Deps) *App {
users := user.NewService(userstore.NewUsers(d.DB))
chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users)
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes)
probes := health.New()
probes := health.New(
health.Check{Name: "postgres", Probe: d.DB.Ping},
health.Check{Name: "valkey", Probe: func(ctx context.Context) error { return d.Sessions.Ping(ctx).Err() }},
)
probes.Register(engine)
sessions := auth.NewService(users, authstore.NewSessions(d.Sessions), d.SessionTTL)
public := engine.Group("/api/v1")
timeout := d.RequestTimeout
if timeout == 0 {
timeout = defaultRequestTimeout
}
public := engine.Group("/api/v1", httpx.Timeout(timeout))
protected := public.Group("", auth.RequireSession(sessions))
auth.NewHandler(sessions).Register(public, protected)
user.NewHandler(users).Register(public, protected)
+100
View File
@@ -0,0 +1,100 @@
package app_test
import (
"context"
"io"
"log/slog"
"net/http"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/testenv"
)
// newIsolatedTester assembles the application over containers of its own,
// so a test can stop or pause them without disturbing the shared ones.
func newIsolatedTester(t *testing.T, requestTimeout time.Duration) (*tester, *testenv.DB, *testenv.KV) {
t.Helper()
ctx := context.Background()
pg, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pg.Close)
vk, err := testenv.StartValkey(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(vk.Close)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
a := app.New(app.Deps{
Log: log,
DB: pg.Pool,
Sessions: vk.Client,
SessionTTL: time.Hour,
MaxBodyBytes: 64 * 1024,
RequestTimeout: requestTimeout,
})
return &tester{t: t, a: a}, pg, vk
}
// Without the session store no caller can be authenticated: the API answers
// 503, never 401 (the token is not at fault) and never as an anonymous user.
// Registration does not need the store and keeps working.
func TestValkeyOutageAnswers503(t *testing.T) {
ts, _, vk := newIsolatedTester(t, 5*time.Second)
alice := ts.user("alice", "Алиса")
room := ts.chat(alice.token, "t", alice.ID)
if err := vk.Stop(context.Background()); err != nil {
t.Fatal(err)
}
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+room.ID, alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword)), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/live", "", nil, nil), http.StatusOK, "")
body := map[string]string{"username": "bob", "display_name": "Bob", "password": testPassword}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusCreated, "")
}
func TestPostgresOutageAnswers503(t *testing.T) {
ts, pg, _ := newIsolatedTester(t, 5*time.Second)
alice := ts.user("alice", "Алиса")
if err := pg.Stop(context.Background()); err != nil {
t.Fatal(err)
}
ts.expect(ts.do(http.MethodGet, "/api/v1/chats", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword)), http.StatusServiceUnavailable, "unavailable")
body := map[string]string{"username": "bob", "display_name": "Bob", "password": testPassword}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
}
// A database that accepts connections but never answers must not hold the
// request: the request deadline turns it into a 503.
func TestHungPostgresAnswers503WithinTheRequestTimeout(t *testing.T) {
ts, pg, _ := newIsolatedTester(t, 300*time.Millisecond)
alice := ts.user("alice", "Алиса")
ctx := context.Background()
if err := pg.Pause(ctx); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pg.Unpause(ctx) })
for _, path := range []string{"/api/v1/chats", "/health/ready"} {
start := time.Now()
ts.expect(ts.do(http.MethodGet, path, alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("%s took %v with a hung database, want it bounded", path, elapsed)
}
}
}