Refactor periodic tasks to use injected scheduler resources
This commit is contained in:
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import aiosqlite
|
||||
from app.config import Settings
|
||||
|
||||
import structlog
|
||||
|
||||
@@ -34,8 +35,7 @@ HISTORY_SYNC_INTERVAL: int = 300
|
||||
BACKFILL_WINDOW: int = 648000
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -48,10 +48,9 @@ async def _get_last_archive_ts(db) -> int | None:
|
||||
return int(row[0])
|
||||
|
||||
|
||||
async def _run_sync(app: FastAPI) -> None:
|
||||
settings = get_effective_settings(app)
|
||||
async def _run_sync_with_settings(settings: "Settings") -> None:
|
||||
socket_path: str = settings.fail2ban_socket
|
||||
db, close_db = await _get_db(app)
|
||||
db, close_db = await _get_db(settings)
|
||||
|
||||
try:
|
||||
last_ts = await _get_last_archive_ts(db)
|
||||
@@ -107,16 +106,21 @@ async def _run_sync(app: FastAPI) -> None:
|
||||
await db.close()
|
||||
|
||||
|
||||
async def _run_sync(app: FastAPI) -> None:
|
||||
await _run_sync_with_settings(get_effective_settings(app))
|
||||
|
||||
|
||||
def register(app: FastAPI) -> None:
|
||||
"""Register the history sync periodic job.
|
||||
|
||||
Should be called after scheduler startup, from the lifespan handler.
|
||||
"""
|
||||
settings = get_effective_settings(app)
|
||||
app.state.scheduler.add_job(
|
||||
_run_sync,
|
||||
_run_sync_with_settings,
|
||||
trigger="interval",
|
||||
seconds=HISTORY_SYNC_INTERVAL,
|
||||
kwargs={"app": app},
|
||||
kwargs={"settings": settings},
|
||||
id=JOB_ID,
|
||||
replace_existing=True,
|
||||
next_run_time=datetime.datetime.now(tz=datetime.UTC),
|
||||
|
||||
Reference in New Issue
Block a user