fix: 优雅停机时主动 dispose 连接池,消除 SQLite 后台连接被 GC 丢弃的 SAWarning

Ctrl+C 停服时 aiosqlite 后台线程上的连接若未归还池会被 GC 直接丢弃,
表现为 shutdown 时的 non-checked-in connection SAWarning。在 lifespan 关闭
阶段调用 engine.dispose() 主动清理(数据不受影响,纯停机噪音修复)。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-10-25 03:28:49 +08:00
co-authored by Claude Code
parent 2cda214170
commit bbf4cebd90
+7 -2
View File
@@ -8,7 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.core.config import settings
from app.core.database import init_db, Base
from app.core.database import init_db, Base, engine
from app.core.security import verify_token
from app.api.books import router as books_router
from app.api.chat import router as chat_router
@@ -25,7 +25,12 @@ from app.models.mcp_server import McpServer
@asynccontextmanager
async def lifespan(app: FastAPI):
await init_db()
yield
try:
yield
finally:
# 优雅停机:主动销毁连接池,避免 SQLite 后台线程的连接被 GC 丢弃
# (表现为 shutdown 时 SAWarning:non-checked-in connection ... dropped)
await engine.dispose()
app = FastAPI(title="BookMate", version="0.1.0", lifespan=lifespan)