package postgres import ( "context" "fmt" "time" ) const ( expiredStatePruneEvery = 128 expiredStatePruneBatch = 256 ) // maybePruneExpiredState bounds session/idempotency table growth without adding // a cleanup round trip to every request. The first operation after process // start prunes immediately; later operations amortize one bounded indexed // delete per expiredStatePruneEvery writes. func (s *PostgreSQLStore) maybePruneExpiredState(ctx context.Context, now time.Time) error { iteration := s.expiredStatePruneCounter.Add(1) if iteration != 1 && iteration%expiredStatePruneEvery != 0 { return nil } queryContext, cancel := s.withTimeout(ctx) defer cancel() _, err := s.pool.Exec(queryContext, ` WITH stale_sessions AS ( SELECT token_hash FROM sessions WHERE expires_at <= $1 ORDER BY expires_at LIMIT $2 FOR UPDATE SKIP LOCKED ), deleted_sessions AS ( DELETE FROM sessions AS target USING stale_sessions AS stale WHERE target.token_hash = stale.token_hash RETURNING 1 ), stale_idempotency AS ( SELECT user_id, method, canonical_path, idempotency_key FROM message_idempotency WHERE expires_at <= $1 ORDER BY expires_at LIMIT $2 FOR UPDATE SKIP LOCKED ), deleted_idempotency AS ( DELETE FROM message_idempotency AS target USING stale_idempotency AS stale WHERE target.user_id = stale.user_id AND target.method = stale.method AND target.canonical_path = stale.canonical_path AND target.idempotency_key = stale.idempotency_key RETURNING 1 ) SELECT (SELECT count(*) FROM deleted_sessions), (SELECT count(*) FROM deleted_idempotency) `, now.UTC(), expiredStatePruneBatch) if err != nil { return fmt.Errorf("prune expired auth state: %w", err) } return nil } // maybePruneExpiredLoginRateState uses the configured limiter window as the // cutoff. Comparing with now directly would delete active windows and weaken // the limiter whenever maintenance runs. func (s *PostgreSQLStore) maybePruneExpiredLoginRateState( ctx context.Context, now time.Time, window time.Duration, ) error { iteration := s.loginRatePruneCounter.Add(1) if iteration != 1 && iteration%expiredStatePruneEvery != 0 { return nil } queryContext, cancel := s.withTimeout(ctx) defer cancel() _, err := s.pool.Exec(queryContext, ` WITH stale_login_limits AS ( SELECT identifier_hash FROM login_rate_limits WHERE window_started_at <= $1 ORDER BY window_started_at LIMIT $2 FOR UPDATE SKIP LOCKED ) DELETE FROM login_rate_limits AS target USING stale_login_limits AS stale WHERE target.identifier_hash = stale.identifier_hash `, now.UTC().Add(-window), expiredStatePruneBatch) if err != nil { return fmt.Errorf("prune expired login rate state: %w", err) } return nil }