Refactor blocklist import registration to async startup flow
This commit is contained in:
@@ -13,7 +13,6 @@ existing entry without creating duplicates.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import structlog
|
||||
@@ -76,7 +75,7 @@ async def _run_import(app: Any) -> None:
|
||||
await db.close()
|
||||
|
||||
|
||||
def register(app: FastAPI) -> None:
|
||||
async def register(app: FastAPI) -> None:
|
||||
"""Add (or replace) the blocklist import job in the application scheduler.
|
||||
|
||||
Reads the persisted :class:`~app.models.blocklist.ScheduleConfig` from
|
||||
@@ -89,30 +88,14 @@ def register(app: FastAPI) -> None:
|
||||
app: The :class:`fastapi.FastAPI` application instance whose
|
||||
``app.state.scheduler`` will receive the job.
|
||||
"""
|
||||
import asyncio # noqa: PLC0415
|
||||
|
||||
async def _do_register() -> None:
|
||||
db, close_db = await _get_db(app)
|
||||
try:
|
||||
config = await blocklist_service.get_schedule(db)
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
_apply_schedule(app, config)
|
||||
|
||||
# APScheduler is synchronous at registration time; use asyncio to read
|
||||
# the stored schedule from the DB before registering.
|
||||
coro = None
|
||||
db, close_db = await _get_db(app)
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
coro = _do_register()
|
||||
loop.run_until_complete(coro)
|
||||
except RuntimeError:
|
||||
# If the current thread already has a running loop (uvicorn), schedule
|
||||
# the registration as a coroutine.
|
||||
if coro is not None and inspect.getcoroutinestate(coro) != inspect.CORO_CLOSED:
|
||||
coro.close()
|
||||
asyncio.ensure_future(_do_register())
|
||||
config = await blocklist_service.get_schedule(db)
|
||||
finally:
|
||||
if close_db:
|
||||
await db.close()
|
||||
|
||||
_apply_schedule(app, config)
|
||||
|
||||
|
||||
def reschedule(app: FastAPI) -> None:
|
||||
|
||||
Reference in New Issue
Block a user