Merge gap-c-session-cleanup: periodic expired-session sweep

This commit is contained in:
Indiana
2026-07-23 00:33:26 +00:00
3 changed files with 91 additions and 2 deletions

View File

@@ -1,3 +1,5 @@
import asyncio
import contextlib
from contextlib import asynccontextmanager
from pathlib import Path
@@ -7,22 +9,49 @@ from fastapi.staticfiles import StaticFiles
import app.models # noqa: F401 — registers models on Base.metadata before create_all
from app.config import settings
from app.db import Base, engine
from app.db import Base, async_session_maker, engine
from app.routes.auth import router as auth_router
from app.routes.codex import router as codex_router
from app.routes.shop import router as shop_router
from app.session_cleanup import delete_expired_sessions
from app.ws import AUDIO_DIR
from app.ws import router as ws_router
FRONTEND_DIST = Path(__file__).resolve().parent.parent.parent / "frontend" / "dist"
SESSION_CLEANUP_INTERVAL_SECONDS = 30 * 60
async def _session_cleanup_loop() -> None:
"""Periodically sweeps expired auth_sessions rows so the table doesn't
grow forever — get_current_user already rejects expired sessions on
read, this just deletes the rows themselves."""
try:
while True:
await asyncio.sleep(SESSION_CLEANUP_INTERVAL_SECONDS)
try:
async with async_session_maker() as db:
await delete_expired_sessions(db)
except Exception:
# A transient DB hiccup shouldn't kill the sweep loop —
# just try again next interval.
pass
except asyncio.CancelledError:
pass
@asynccontextmanager
async def lifespan(app: FastAPI):
AUDIO_DIR.mkdir(parents=True, exist_ok=True)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
cleanup_task = asyncio.create_task(_session_cleanup_loop())
try:
yield
finally:
cleanup_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await cleanup_task
app = FastAPI(title="Quantumancy", lifespan=lifespan)

View File

@@ -0,0 +1,23 @@
"""Periodic sweep of expired auth_sessions rows.
get_current_user (app/deps.py) already rejects expired sessions on read, but
never deletes them — left alone, auth_sessions grows forever. The lifespan
in app/main.py runs delete_expired_sessions on a timer to keep the table
bounded.
"""
from datetime import datetime, timezone
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.auth_session import AuthSession
async def delete_expired_sessions(db: AsyncSession) -> int:
"""Deletes expired auth_sessions rows. Returns the number deleted."""
result = await db.execute(
delete(AuthSession).where(AuthSession.expires_at < datetime.now(timezone.utc))
)
await db.commit()
return result.rowcount

View File

@@ -0,0 +1,37 @@
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
from app.models.auth_session import AuthSession
from app.models.user import User
from app.security import hash_password
from app.session_cleanup import delete_expired_sessions
@pytest.mark.asyncio
async def test_delete_expired_sessions_removes_only_expired(db_session):
user = User(username="cleanup_medium", password_hash=hash_password("spookyspooky"))
db_session.add(user)
await db_session.flush()
expired = AuthSession(
user_id=user.id,
token_hash="expired-token-hash",
expires_at=datetime.now(timezone.utc) - timedelta(days=1),
)
valid = AuthSession(
user_id=user.id,
token_hash="valid-token-hash",
expires_at=datetime.now(timezone.utc) + timedelta(days=1),
)
db_session.add_all([expired, valid])
await db_session.commit()
deleted_count = await delete_expired_sessions(db_session)
assert deleted_count == 1
remaining = (await db_session.execute(select(AuthSession))).scalars().all()
remaining_ids = {session.id for session in remaining}
assert expired.id not in remaining_ids
assert valid.id in remaining_ids