"""Application startup helpers. This module contains shared startup logic extracted from ``app.main`` so that initialisation is easier to reason about and unit test. The lifespan handler in ``app.main`` delegates resource creation and task registration here. """ from __future__ import annotations from pathlib import Path import aiohttp import structlog from apscheduler.schedulers.asyncio import AsyncIOScheduler # type: ignore[import-untyped] from fastapi import FastAPI from app.config import Settings from app.db import init_db, open_db from app.services import geo_service, setup_service from app.tasks import blocklist_import, geo_cache_flush, geo_re_resolve, health_check, history_sync from app.utils.jail_config import ensure_jail_configs from app.utils.setup_state import set_setup_complete_cache log: structlog.stdlib.BoundLogger = structlog.get_logger() async def startup_shared_resources( app: FastAPI, settings: Settings, ) -> tuple[aiohttp.ClientSession, AsyncIOScheduler]: """Create shared resources needed during the application lifespan. Args: app: The FastAPI application instance. settings: Resolved application settings. Returns: A tuple of ``(http_session, scheduler)``. """ ensure_jail_configs(Path(settings.fail2ban_config_dir) / "jail.d") db_path: Path = Path(settings.database_path) db_path.parent.mkdir(parents=True, exist_ok=True) log.debug("database_directory_ensured", directory=str(db_path.parent)) startup_db = await open_db(settings.database_path) try: await init_db(startup_db) await geo_service.load_cache_from_db(startup_db) unresolved_count = await geo_service.count_unresolved(startup_db) setup_complete = await setup_service.is_setup_complete(startup_db) set_setup_complete_cache(app, setup_complete) log.debug("setup_completion_cached", completed=setup_complete) finally: await startup_db.close() if unresolved_count > 0: log.warning("geo_cache_unresolved_ips", unresolved=unresolved_count) http_session: aiohttp.ClientSession = aiohttp.ClientSession() geo_service.init_geoip(settings.geoip_db_path) scheduler: AsyncIOScheduler = AsyncIOScheduler(timezone="UTC") scheduler.start() health_check.register(app) blocklist_import.register(app) geo_cache_flush.register(app) geo_re_resolve.register(app) history_sync.register(app) return http_session, scheduler