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

90 lines
3.2 KiB
Python

"""Nexus — Script & ScriptExecution Repository (Async SQLAlchemy)"""
from typing import Optional, List, Tuple
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from server.domain.models import Script, ScriptExecution
class ScriptRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[Script]:
result = await self.session.execute(select(Script).where(Script.id == id))
return result.scalar_one_or_none()
async def get_all(self) -> List[Script]:
result = await self.session.execute(select(Script).order_by(Script.id))
return list(result.scalars().all())
async def get_by_category(self, category: str) -> List[Script]:
result = await self.session.execute(
select(Script).where(Script.category == category).order_by(Script.id)
)
return list(result.scalars().all())
async def create(self, script: Script) -> Script:
self.session.add(script)
await self.session.commit()
return script
async def update(self, script: Script) -> Script:
await self.session.commit()
return script
async def delete(self, id: int) -> bool:
script = await self.get_by_id(id)
if script:
await self.session.delete(script)
await self.session.commit()
return True
return False
class ScriptExecutionRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[ScriptExecution]:
result = await self.session.execute(
select(ScriptExecution).where(ScriptExecution.id == id)
)
return result.scalar_one_or_none()
async def create(self, execution: ScriptExecution) -> ScriptExecution:
self.session.add(execution)
await self.session.commit()
return execution
async def list_recent(
self,
limit: int = 50,
offset: int = 0,
status: Optional[str] = None,
) -> Tuple[List[ScriptExecution], int]:
filters = []
if status:
filters.append(ScriptExecution.status == status)
count_stmt = select(func.count(ScriptExecution.id))
if filters:
count_stmt = count_stmt.where(*filters)
total = int((await self.session.execute(count_stmt)).scalar() or 0)
stmt = select(ScriptExecution).order_by(ScriptExecution.started_at.desc())
if filters:
stmt = stmt.where(*filters)
result = await self.session.execute(stmt.limit(limit).offset(offset))
return list(result.scalars().all()), total
async def update_status(self, id: int, status: str, results: str) -> Optional[ScriptExecution]:
from datetime import datetime, timezone
execution = await self.session.get(ScriptExecution, id)
if execution:
execution.status = status
execution.results = results
if status != "running" and execution.completed_at is None:
execution.completed_at = datetime.now(timezone.utc)
await self.session.commit()
return execution