Files
Nexus/server/infrastructure/database/admin_repo.py
T
Your Name 99201f48fd fix: MissingGreenlet error — convert all middleware to pure ASGI
Root cause: BaseHTTPMiddleware.call_next() runs the endpoint in a
separate async task, which breaks SQLAlchemy's greenlet context.
After session.commit(), the connection is released to the pool.
When session.refresh() tries to acquire a new connection for a
SELECT, it fails with MissingGreenlet because the greenlet spawn
context is not available in the call_next() task.

Fix (two-part):
1. Convert all 4 middleware classes from BaseHTTPMiddleware to pure
   ASGI middleware — eliminates call_next() entirely so the entire
   request chain runs in the same async context.
2. Set expire_on_commit=False on the session factory — after commit,
   objects retain their in-memory values instead of being expired.
   This removes the need for session.refresh() entirely.

All session.refresh() calls removed from 11 repository files.
With expire_on_commit=False, post-commit attribute access no longer
triggers lazy loads that would also fail with MissingGreenlet.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-25 15:24:15 +08:00

55 lines
2.0 KiB
Python

"""Nexus — Admin & LoginAttempt Repository (Async SQLAlchemy)"""
from typing import Optional, List
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from server.domain.models import Admin, LoginAttempt
class AdminRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.id == id))
return result.scalar_one_or_none()
async def get_by_username(self, username: str) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.username == username))
return result.scalar_one_or_none()
async def get_by_refresh_token(self, refresh_token: str) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.jwt_refresh_token == refresh_token))
return result.scalar_one_or_none()
async def create(self, admin: Admin) -> Admin:
self.session.add(admin)
await self.session.commit()
return admin
async def update(self, admin: Admin) -> Admin:
await self.session.commit()
return admin
class LoginAttemptRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def create(self, attempt: LoginAttempt) -> LoginAttempt:
self.session.add(attempt)
await self.session.commit()
return attempt
async def count_recent_failures(self, username: str, ip_address: str, minutes: int = 15) -> int:
from datetime import datetime, timedelta, timezone
cutoff = datetime.now(timezone.utc) - timedelta(minutes=minutes)
result = await self.session.execute(
select(func.count(LoginAttempt.id))
.where(LoginAttempt.username == username)
.where(LoginAttempt.ip_address == ip_address)
.where(LoginAttempt.success == False)
.where(LoginAttempt.attempted_at >= cutoff)
)
return result.scalar_one() or 0