Files
Nexus/server/infrastructure/database/setting_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

32 lines
1.1 KiB
Python

"""Nexus — Setting Repository (Async SQLAlchemy)"""
from typing import Optional, List
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from server.domain.models import Setting
class SettingRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get(self, key: str) -> Optional[str]:
result = await self.session.execute(select(Setting).where(Setting.key == key))
setting = result.scalar_one_or_none()
return setting.value if setting else None
async def set(self, key: str, value: str) -> Setting:
result = await self.session.execute(select(Setting).where(Setting.key == key))
setting = result.scalar_one_or_none()
if setting:
setting.value = value
else:
setting = Setting(key=key, value=value)
self.session.add(setting)
await self.session.commit()
return setting
async def get_all(self) -> List[Setting]:
result = await self.session.execute(select(Setting).order_by(Setting.key))
return list(result.scalars().all())