Document task DB access and unify background task DB handling

This commit is contained in:
2026-04-17 17:18:49 +02:00
parent 16687b0520
commit 5e5d7c34b2
12 changed files with 139 additions and 90 deletions

View File

@@ -17,12 +17,11 @@ from typing import TYPE_CHECKING, Any
import structlog
from app.db import open_db
from app.services import ban_service, blocklist_service
from app.tasks.db import task_db
from app.utils.runtime_state import get_effective_settings
if TYPE_CHECKING:
import aiosqlite
from aiohttp import ClientSession
from fastapi import FastAPI
@@ -34,11 +33,6 @@ log: structlog.stdlib.BoundLogger = structlog.get_logger()
JOB_ID: str = "blocklist_import"
async def _get_db(settings: Settings) -> tuple[aiosqlite.Connection, bool]:
db = await open_db(settings.database_path)
return db, True
async def _run_import_with_resources(settings: Settings, http_session: ClientSession) -> None:
"""APScheduler callback that imports all enabled blocklist sources.
@@ -46,17 +40,17 @@ async def _run_import_with_resources(settings: Settings, http_session: ClientSes
settings: The resolved application settings used for database access.
http_session: The shared aiohttp session used for blocklist downloads.
"""
db, close_db = await _get_db(settings)
socket_path: str = settings.fail2ban_socket
log.info("blocklist_import_starting")
try:
result = await blocklist_service.import_all(
db,
http_session,
socket_path,
ban_ip=ban_service.ban_ip,
)
async with task_db(settings) as db:
result = await blocklist_service.import_all(
db,
http_session,
socket_path,
ban_ip=ban_service.ban_ip,
)
log.info(
"blocklist_import_finished",
total_imported=result.total_imported,
@@ -65,9 +59,6 @@ async def _run_import_with_resources(settings: Settings, http_session: ClientSes
)
except Exception:
log.exception("blocklist_import_unexpected_error")
finally:
if close_db:
await db.close()
run_import_with_resources = _run_import_with_resources
@@ -91,12 +82,8 @@ async def register(app: FastAPI) -> None:
``app.state.scheduler`` will receive the job.
"""
settings = get_effective_settings(app)
db, close_db = await _get_db(settings)
try:
async with task_db(settings) as db:
config = await blocklist_service.get_schedule(db)
finally:
if close_db:
await db.close()
_apply_schedule(app, config)
@@ -114,12 +101,8 @@ def reschedule(app: FastAPI) -> None:
async def _do_reschedule() -> None:
settings = get_effective_settings(app)
db, close_db = await _get_db(settings)
try:
async with task_db(settings) as db:
config = await blocklist_service.get_schedule(db)
finally:
if close_db:
await db.close()
_apply_schedule(app, config)
asyncio.ensure_future(_do_reschedule())