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

@@ -21,18 +21,16 @@ from typing import TYPE_CHECKING
import structlog
from app.db import open_db
from app.services import geo_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 app.config import Settings
from app.services import geo_service
if TYPE_CHECKING:
from fastapi import FastAPI
from app.config import Settings
log: structlog.stdlib.BoundLogger = structlog.get_logger()
#: How often the re-resolve job fires (seconds). 10 minutes.
@@ -42,21 +40,14 @@ GEO_RE_RESOLVE_INTERVAL: int = 600
JOB_ID: str = "geo_re_resolve"
async def _get_db(settings: "Settings") -> tuple[aiosqlite.Connection, bool]:
db = await open_db(settings.database_path)
return db, True
async def _run_re_resolve_with_resources(settings: "Settings", http_session: "ClientSession") -> None:
async def _run_re_resolve_with_resources(settings: Settings, http_session: ClientSession) -> None:
"""Query NULL-country IPs from the database and re-resolve them.
Args:
settings: The resolved application settings used for database access.
http_session: The shared aiohttp session used for external lookups.
"""
db, close_db = await _get_db(settings)
try:
async with task_db(settings) as db:
# Fetch all IPs with NULL country_code from the persistent cache.
unresolved_ips = await geo_service.get_unresolved_ips(db)
@@ -73,17 +64,14 @@ async def _run_re_resolve_with_resources(settings: "Settings", http_session: "Cl
# passed. This is a background task so DB writes are allowed.
results = await geo_service.lookup_batch(unresolved_ips, http_session, db=db)
resolved_count: int = sum(
1 for info in results.values() if info.country_code is not None
)
log.info(
"geo_re_resolve_complete",
retried=len(unresolved_ips),
resolved=resolved_count,
)
finally:
if close_db:
await db.close()
resolved_count: int = sum(
1 for info in results.values() if info.country_code is not None
)
log.info(
"geo_re_resolve_complete",
retried=len(unresolved_ips),
resolved=resolved_count,
)
async def _run_re_resolve(app: FastAPI) -> None: