package auth_tests import ( "context" "errors" "net/http" "net/http/httptest" "net/url" "os" "strconv" "testing" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "highload/internal/database" "highload/internal/database/sqlc" "highload/internal/repository" "highload/internal/repository/postgres" ) func operationBudget(t *testing.T) time.Duration { t.Helper() value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS") if value == "" { t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending") return 3 * time.Second } n, err := strconv.Atoi(value) if err != nil || n < 500 || n > 10000 { t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000") } return time.Duration(n) * time.Millisecond } func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool { t.Helper() u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL")) if err != nil { t.Fatal("invalid test URL") } q := u.Query() q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"]) u.RawQuery = q.Encode() // Actual production constructor: never inherit fixture statement_timeout. pool, err := database.NewPostgres(f.ctx, u.String()) if err != nil { t.Fatal("application pool unavailable") } f.pool.Close() f.pool = pool f.queries = sqlc.New(pool) return pool } func blockOperation(t *testing.T, f *fixture, mode string) func() { t.Helper() if mode == "blocked_query" { tx, err := f.admin.Begin(f.ctx) if err != nil { t.Fatal("lock transaction failed") } table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize() if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil { t.Fatal("isolated table lock failed") } return func() { ctx, c := context.WithTimeout(context.Background(), 2*time.Second) defer c() _ = tx.Rollback(ctx) } } max := f.pool.Config().MaxConns if max <= 0 || max > 128 { t.Fatal("test refuses unbounded/oversized pool") } held := make([]*pgxpool.Conn, 0, max) for range max { conn, err := f.pool.Acquire(f.ctx) if err != nil { for _, h := range held { h.Release() } t.Fatal("pool saturation failed") } held = append(held, conn) } return func() { for _, h := range held { h.Release() } } } func TestPostgresOperationsHaveBoundedWaits(t *testing.T) { budget := operationBudget(t) for _, mode := range []string{"blocked_query", "exhausted_pool"} { for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} { t.Run(mode+"/"+scenario, func(t *testing.T) { f := newFixture(t) user, password := f.user(t) session := f.session(t, user, password) applicationPool(t, f) release := blockOperation(t, f, mode) released := false defer func() { if !released { release() } }() safety := budget + 2*time.Second if scenario == "shorter_caller_deadline" { safety = 150 * time.Millisecond } ctx, cancel := context.WithTimeout(context.Background(), safety) defer cancel() request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx) request.Header.Set("Authorization", "Bearer "+session.Token) recorder := httptest.NewRecorder() done := make(chan struct{}) started := time.Now() go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }() if scenario == "released_before_budget" { time.Sleep(100 * time.Millisecond) release() released = true } <-done elapsed := time.Since(started) t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil) switch scenario { case "application_budget": if ctx.Err() != nil || elapsed > budget+250*time.Millisecond { t.Error("application did not independently enforce its operation budget before test safety cancellation") } assertContractError(t, recorder, 503, "unavailable") case "shorter_caller_deadline": if elapsed > 750*time.Millisecond { t.Error("short caller deadline was not honored") } assertContractError(t, recorder, 503, "unavailable") case "released_before_budget": if recorder.Code != 200 || elapsed >= budget { t.Error("unblocked operation failed or missed the declared budget") } } if !released { release() released = true } recovery := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v1/users/me", nil) req.Header.Set("Authorization", "Bearer "+session.Token) recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second) defer c() redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx)) if recovery.Code != 200 { t.Error("service did not recover after releasing lock/pool") } if f.pool.Stat().AcquiredConns() != 0 { t.Error("application pool leaked an acquired connection") } }) } } } func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) { f := newFixture(t) user, _ := f.user(t) applicationPool(t, f) tx, err := f.admin.Begin(f.ctx) if err != nil { t.Fatal("cannot start membership blocker") } released := false defer func() { if !released { _ = tx.Rollback(context.Background()) } }() table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize() if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil { t.Fatal("cannot block membership insertion") } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() repo := postgres.NewChatRepository(f.queries, f.pool) _, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID}) if !errors.Is(err, repository.ErrServiceUnavailable) { t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err) } // The membership INSERT cannot finish while this lock is held, so COMMIT // has not been reached. No ambiguous-commit inference is made here. _ = tx.Rollback(context.Background()) released = true for _, name := range []string{"chats", "chat_members"} { var count int if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 { t.Error("pre-commit cancellation left partial chat data") } } if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil { t.Error("chat repository failed to recover") } if f.pool.Stat().AcquiredConns() != 0 { t.Error("chat cancellation leaked a connection") } }