"""Standalone background worker entrypoint for split API/worker deployments.""" from __future__ import annotations import asyncio from contextlib import suppress import signal from app.core.config import settings, validate_production_security from app.core.logging import configure_logging, get_logger from app.core.websocket.broadcaster import broadcaster from app.core.websocket.manager import manager from app.db.session import init_db from app.services.data_jobs import start_data_job_worker, stop_data_job_worker from app.services.earth_news_worker import ( start_earth_news_target_worker, stop_earth_news_target_worker, ) from app.services.scheduler import ( acquire_scheduler_leader_lock, cleanup_stale_running_tasks, release_scheduler_leader_lock, start_scheduler, stop_scheduler, sync_scheduler_with_datasources, ) LEADER_RETRY_SECONDS = 5.0 logger = get_logger(__name__, service="worker") async def run_worker(stop_event: asyncio.Event | None = None) -> None: """Run scheduler and async queue workers with PostgreSQL leader election.""" configure_logging() validate_production_security(settings) await init_db() active_stop = stop_event or asyncio.Event() pubsub_started = False leader_lock_acquired = False scheduler_started = False workers_started = False broadcaster_started = False try: await manager.start_pubsub(publish_only=True) pubsub_started = True while not active_stop.is_set(): if not settings.should_run_scheduler: break if await acquire_scheduler_leader_lock(): leader_lock_acquired = True break logger.info_event( "Waiting for scheduler leader advisory lock", event="worker.leader_lock.waiting", ) with suppress(TimeoutError): await asyncio.wait_for(active_stop.wait(), timeout=LEADER_RETRY_SECONDS) if active_stop.is_set(): return if settings.should_run_scheduler: await cleanup_stale_running_tasks() start_scheduler() scheduler_started = True await sync_scheduler_with_datasources() broadcaster.start() broadcaster_started = True start_data_job_worker() start_earth_news_target_worker() workers_started = True logger.info_event( "Background worker started", event="worker.started", context={"role": settings.normalized_role, "scheduler": scheduler_started}, ) await active_stop.wait() finally: if broadcaster_started: try: broadcaster.stop() except Exception as exc: logger.warning_event( "Failed stopping broadcaster during worker shutdown", event="worker.shutdown.broadcaster_error", context={"error": str(exc)}, ) if workers_started: try: await stop_earth_news_target_worker() except Exception as exc: logger.warning_event( "Failed stopping earth news worker during worker shutdown", event="worker.shutdown.earth_news_error", context={"error": str(exc)}, ) try: await stop_data_job_worker() except Exception as exc: logger.warning_event( "Failed stopping data job worker during worker shutdown", event="worker.shutdown.data_job_error", context={"error": str(exc)}, ) if scheduler_started: try: stop_scheduler() except Exception as exc: logger.warning_event( "Failed stopping scheduler during worker shutdown", event="worker.shutdown.scheduler_error", context={"error": str(exc)}, ) if leader_lock_acquired: try: await release_scheduler_leader_lock() except Exception as exc: logger.warning_event( "Failed releasing scheduler leader lock during worker shutdown", event="worker.shutdown.leader_lock_error", context={"error": str(exc)}, ) if pubsub_started: try: await manager.stop_pubsub() except Exception as exc: logger.warning_event( "Failed stopping pubsub during worker shutdown", event="worker.shutdown.pubsub_error", context={"error": str(exc)}, ) logger.info_event("Background worker stopped", event="worker.stopped") async def _main() -> None: stop_event = asyncio.Event() loop = asyncio.get_running_loop() for sig in (signal.SIGINT, signal.SIGTERM): with suppress(NotImplementedError): loop.add_signal_handler(sig, stop_event.set) await run_worker(stop_event) if __name__ == "__main__": asyncio.run(_main())