Refactor backend to use request-scoped SQLite connections

This commit is contained in:
2026-04-05 23:14:46 +02:00
parent fde4c480fa
commit 42c030c706
13 changed files with 250 additions and 116 deletions

View File

@@ -15,6 +15,10 @@ from typing import TYPE_CHECKING, Any
import structlog
from app.db import open_db
if TYPE_CHECKING:
import aiosqlite
from app.services import geo_service
if TYPE_CHECKING:
@@ -29,6 +33,15 @@ GEO_FLUSH_INTERVAL: int = 60
JOB_ID: str = "geo_cache_flush"
async def _get_db(app: Any) -> tuple[aiosqlite.Connection, bool]:
existing_db = getattr(app.state, "db", None)
if existing_db is not None:
return existing_db, False
db = await open_db(app.state.settings.database_path)
return db, True
async def _run_flush(app: Any) -> None:
"""Flush the geo service dirty set to the application database.
@@ -39,8 +52,13 @@ async def _run_flush(app: Any) -> None:
app: The :class:`fastapi.FastAPI` application instance passed via
APScheduler ``kwargs``.
"""
db = app.state.db
count = await geo_service.flush_dirty(db)
db, close_db = await _get_db(app)
try:
count = await geo_service.flush_dirty(db)
finally:
if close_db:
await db.close()
if count > 0:
log.debug("geo_cache_flush_ran", flushed=count)