Refactor backend to use request-scoped SQLite connections
This commit is contained in:
@@ -9,8 +9,12 @@ from __future__ import annotations
|
||||
import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import aiosqlite
|
||||
|
||||
import structlog
|
||||
|
||||
from app.db import open_db
|
||||
from app.repositories import fail2ban_db_repo
|
||||
from app.utils.fail2ban_db_utils import get_fail2ban_db_path
|
||||
|
||||
@@ -29,6 +33,15 @@ HISTORY_SYNC_INTERVAL: int = 300
|
||||
BACKFILL_WINDOW: int = 648000
|
||||
|
||||
|
||||
async def _get_db(app: FastAPI) -> 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 _get_last_archive_ts(db) -> int | None:
|
||||
async with db.execute("SELECT MAX(timeofban) FROM history_archive") as cur:
|
||||
row = await cur.fetchone()
|
||||
@@ -38,8 +51,8 @@ async def _get_last_archive_ts(db) -> int | None:
|
||||
|
||||
|
||||
async def _run_sync(app: FastAPI) -> None:
|
||||
db = app.state.db
|
||||
socket_path: str = app.state.settings.fail2ban_socket
|
||||
db, close_db = await _get_db(app)
|
||||
|
||||
try:
|
||||
last_ts = await _get_last_archive_ts(db)
|
||||
@@ -90,6 +103,9 @@ async def _run_sync(app: FastAPI) -> None:
|
||||
|
||||
except Exception:
|
||||
log.exception("history_sync_failed")
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
|
||||
|
||||
def register(app: FastAPI) -> None:
|
||||
|
||||
Reference in New Issue
Block a user