Refactor backend to use request-scoped SQLite connections
This commit is contained in:
@@ -17,9 +17,13 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import structlog
|
||||
|
||||
from app.db import open_db
|
||||
from app.models.blocklist import ScheduleFrequency
|
||||
from app.services import blocklist_service
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import aiosqlite
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import FastAPI
|
||||
|
||||
@@ -29,6 +33,15 @@ log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
||||
JOB_ID: str = "blocklist_import"
|
||||
|
||||
|
||||
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_import(app: Any) -> None:
|
||||
"""APScheduler callback that imports all enabled blocklist sources.
|
||||
|
||||
@@ -39,12 +52,10 @@ async def _run_import(app: Any) -> None:
|
||||
app: The :class:`fastapi.FastAPI` application instance passed via
|
||||
APScheduler ``kwargs``.
|
||||
"""
|
||||
db = app.state.db
|
||||
db, close_db = await _get_db(app)
|
||||
http_session = app.state.http_session
|
||||
socket_path: str = app.state.settings.fail2ban_socket
|
||||
|
||||
from app.services import jail_service
|
||||
|
||||
log.info("blocklist_import_starting")
|
||||
try:
|
||||
result = await blocklist_service.import_all(
|
||||
@@ -60,6 +71,9 @@ async def _run_import(app: Any) -> None:
|
||||
)
|
||||
except Exception:
|
||||
log.exception("blocklist_import_unexpected_error")
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
|
||||
|
||||
def register(app: FastAPI) -> None:
|
||||
@@ -78,7 +92,12 @@ def register(app: FastAPI) -> None:
|
||||
import asyncio # noqa: PLC0415
|
||||
|
||||
async def _do_register() -> None:
|
||||
config = await blocklist_service.get_schedule(app.state.db)
|
||||
db, close_db = await _get_db(app)
|
||||
try:
|
||||
config = await blocklist_service.get_schedule(db)
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
_apply_schedule(app, config)
|
||||
|
||||
# APScheduler is synchronous at registration time; use asyncio to read
|
||||
@@ -104,7 +123,12 @@ def reschedule(app: FastAPI) -> None:
|
||||
import asyncio # noqa: PLC0415
|
||||
|
||||
async def _do_reschedule() -> None:
|
||||
config = await blocklist_service.get_schedule(app.state.db)
|
||||
db, close_db = await _get_db(app)
|
||||
try:
|
||||
config = await blocklist_service.get_schedule(db)
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
_apply_schedule(app, config)
|
||||
|
||||
asyncio.ensure_future(_do_reschedule())
|
||||
|
||||
Reference in New Issue
Block a user