Refactor periodic tasks to use injected scheduler resources

This commit is contained in:
2026-04-11 20:32:36 +02:00
parent 9cba5a9fcb
commit ae81a8f5be
10 changed files with 122 additions and 94 deletions

View File

@@ -26,6 +26,8 @@ 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:
@@ -40,24 +42,19 @@ GEO_RE_RESOLVE_INTERVAL: int = 600
JOB_ID: str = "geo_re_resolve"
async def _get_db(app: FastAPI) -> tuple[aiosqlite.Connection, bool]:
settings = get_effective_settings(app)
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(app: FastAPI) -> 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.
Reads shared resources from ``app.state`` and delegates to
:func:`~app.services.geo_service.lookup_batch`.
Args:
app: The :class:`fastapi.FastAPI` application instance passed via
APScheduler ``kwargs``.
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(app)
http_session = app.state.http_session
db, close_db = await _get_db(settings)
try:
# Fetch all IPs with NULL country_code from the persistent cache.
@@ -89,6 +86,10 @@ async def _run_re_resolve(app: FastAPI) -> None:
await db.close()
async def _run_re_resolve(app: FastAPI) -> None:
await _run_re_resolve_with_resources(get_effective_settings(app), app.state.http_session)
def register(app: FastAPI) -> None:
"""Add (or replace) the geo re-resolve job in the application scheduler.
@@ -102,11 +103,12 @@ def register(app: FastAPI) -> None:
app: The :class:`fastapi.FastAPI` application instance whose
``app.state.scheduler`` will receive the job.
"""
settings = get_effective_settings(app)
app.state.scheduler.add_job(
_run_re_resolve,
_run_re_resolve_with_resources,
trigger="interval",
seconds=GEO_RE_RESOLVE_INTERVAL,
kwargs={"app": app},
kwargs={"settings": settings, "http_session": app.state.http_session},
id=JOB_ID,
replace_existing=True,
)