"""Task Scheduler for running collection jobs.""" import asyncio from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta import time from typing import Any, Dict, Optional import weakref from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.date import DateTrigger from apscheduler.triggers.interval import IntervalTrigger import asyncpg from sqlalchemy import select from app.core.config import settings from app.core.enums import JobStatus from app.core.logging import get_logger from app.db.session import async_session_factory from app.core.time import to_iso8601_utc from app.models.datasource import DataSource from app.models.task import CollectionTask from app.services.business_logs import ( emit_business_log, emit_business_log_background, exception_context, ) from app.services.collectors.registry import collector_registry from app.services.datasource_connectivity import ( build_builtin_connectivity_checksum, get_builtin_effective_candidate, save_connectivity_success, ) from app.services.earth_news_refresh import ( REFRESH_INTERVAL_SECONDS as EARTH_NEWS_REFRESH_INTERVAL_SECONDS, create_earth_news_refresh_status, refresh_earth_news_all_regions, refresh_earth_news_region, set_earth_news_refresh_status, touch_earth_news_refresh_status, REFRESH_STATUS_HEARTBEAT_SECONDS as EARTH_NEWS_STATUS_HEARTBEAT_SECONDS, ) from app.services.earth_news import REGION_ANCHORS from app.services.storage_maintenance import run_storage_retention_maintenance logger = get_logger(__name__) scheduler = AsyncIOScheduler() RUNNING_TASK_GUARD_TIMEOUT_MINUTES = 90 RUNNING_COLLECTOR_TASKS: dict[str, asyncio.Task[Any]] = {} HEAVY_COLLECTOR_SOURCES: frozenset[str] = frozenset( {"iptoasn_prefix_geo", "nro_delegated_prefix_geo"} ) _COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[ asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore] ] = weakref.WeakKeyDictionary() _HEAVY_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[ asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore] ] = weakref.WeakKeyDictionary() EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh" STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance" STORAGE_RETENTION_INTERVAL_HOURS = 6 COMPUTE_PRESENTATION_RETRY_JOB_ID = "compute_revision_presentation_retry" COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES = 5 SCHEDULER_LEADER_LOCK_KEY = (17001613, 3) _leader_lock_conn: Optional[asyncpg.Connection] = None _pending_earth_news_refreshes: dict[str, dict[str, Any]] = {} _running_earth_news_refreshes: set[str] = set() _rerun_earth_news_refreshes: dict[str, dict[str, Any]] = {} EARTH_NEWS_REFRESH_WAIT_SECONDS = 300 EARTH_NEWS_REFRESH_POLL_SECONDS = 1 EARTH_NEWS_REFRESH_PUBLIC_ERRORS = { "source_unavailable": "No news source could be refreshed for this region. Please retry.", "timeout": "News sources timed out. Please try again.", "refresh_failed": "Could not refresh news. Please try again.", } def _get_loop_semaphore( registry: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]], limit: int, ) -> asyncio.Semaphore: bounded_limit = max(1, int(limit)) loop = asyncio.get_running_loop() existing = registry.get(loop) if existing is None or existing[0] != bounded_limit: semaphore = asyncio.Semaphore(bounded_limit) registry[loop] = (bounded_limit, semaphore) return semaphore return existing[1] def _get_collector_semaphore() -> asyncio.Semaphore: return _get_loop_semaphore(_COLLECTOR_SEMAPHORES, settings.COLLECTOR_MAX_CONCURRENCY) def _get_heavy_collector_semaphore() -> asyncio.Semaphore: return _get_loop_semaphore( _HEAVY_COLLECTOR_SEMAPHORES, settings.COLLECTOR_HEAVY_CONCURRENCY ) @asynccontextmanager async def _acquire_collector_slots(collector_name: str): """Serialize heavy collectors first so lightweight collectors are not starved.""" heavy_semaphore = ( _get_heavy_collector_semaphore() if collector_name in HEAVY_COLLECTOR_SOURCES else None ) if heavy_semaphore is not None: async with heavy_semaphore: async with _get_collector_semaphore(): yield else: async with _get_collector_semaphore(): yield def _collector_task_name(collector_name: str) -> str: return f"collector:{collector_name}" def get_running_collector_task(collector_name: str) -> asyncio.Task[Any] | None: task = RUNNING_COLLECTOR_TASKS.get(collector_name) if task is not None and not task.done(): return task if task is not None and task.done(): RUNNING_COLLECTOR_TASKS.pop(collector_name, None) target_name = _collector_task_name(collector_name) for candidate in asyncio.all_tasks(): if candidate.done(): continue if candidate.get_name() == target_name: RUNNING_COLLECTOR_TASKS[collector_name] = candidate return candidate return None async def _update_next_run_at(datasource: DataSource, session) -> None: job = scheduler.get_job(datasource.source) datasource.next_run_at = job.next_run_time if job else None await session.commit() async def _apply_datasource_schedule(datasource: DataSource, session) -> None: collector = collector_registry.get(datasource.source) if not collector: logger.warning_event( "Collector not found for datasource", event="collector.schedule.collector_missing", context={"collector_name": datasource.source}, ) return collector_registry.set_active(datasource.source, datasource.is_active) existing_job = scheduler.get_job(datasource.source) if existing_job: scheduler.remove_job(datasource.source) if datasource.is_active: scheduler.add_job( run_collector_task, trigger=IntervalTrigger(minutes=max(1, datasource.frequency_minutes)), id=datasource.source, name=datasource.name, replace_existing=True, max_instances=1, coalesce=True, misfire_grace_time=300, kwargs={"collector_name": datasource.source}, ) logger.info_event( "Scheduled collector", event="collector.schedule.updated", context={ "collector_name": datasource.source, "frequency_minutes": datasource.frequency_minutes, }, ) else: logger.info_event( "Collector disabled", event="collector.schedule.disabled", context={"collector_name": datasource.source}, ) await _update_next_run_at(datasource, session) async def run_collector_task(collector_name: str): """Run a single collector task.""" collector = collector_registry.get(collector_name) if not collector: logger.error_event( "Collector not found", event="collector.run.collector_missing", context={"collector_name": collector_name}, ) return async with async_session_factory() as db: result = await db.execute(select(DataSource).where(DataSource.source == collector_name)) datasource = result.scalar_one_or_none() if not datasource: logger.error_event( "Datasource not found for collector", event="collector.run.datasource_missing", context={"collector_name": collector_name}, ) return if not datasource.is_active: logger.info_event( "Skipping disabled collector", event="collector.run.skipped_disabled", context={"collector_name": collector_name}, ) await emit_business_log( logger, event="collector.run.skipped_disabled", message="Skipping disabled collector", category="collector", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource.id, "status": "skipped", }, ) return running_result = await db.execute( select(CollectionTask) .where( CollectionTask.datasource_id == datasource.id, CollectionTask.status == JobStatus.RUNNING.value, ) .order_by(CollectionTask.started_at.desc(), CollectionTask.id.desc()) .limit(1) ) existing_running = running_result.scalar_one_or_none() if existing_running is not None: now = datetime.now(UTC) started_at = existing_running.started_at if started_at is not None and started_at.tzinfo is None: started_at = started_at.replace(tzinfo=UTC) is_stale = started_at is not None and (now - started_at) > timedelta( minutes=RUNNING_TASK_GUARD_TIMEOUT_MINUTES ) if not is_stale: logger.warning_event( "Skipping collector trigger because task is already running", event="collector.run.skipped_already_running", context={"collector_name": collector_name, "task_id": existing_running.id}, ) await emit_business_log( logger, event="collector.run.skipped_already_running", message="Skipping collector trigger because task is already running", category="collector", level="warning", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource.id, "task_id": existing_running.id, "status": "skipped", }, ) return existing_error = (existing_running.error_message or "").strip() stale_reason = ( f"Marked failed automatically after stale running timeout " f"({RUNNING_TASK_GUARD_TIMEOUT_MINUTES}m) in scheduler guard" ) existing_running.status = JobStatus.FAILED.value existing_running.phase = "failed" existing_running.completed_at = now existing_running.error_message = ( f"{existing_error}\n{stale_reason}".strip() if existing_error else stale_reason ) await db.commit() logger.warning_event( "Marked stale running task as failed before rerun", event="collector.run.stale_task_failed", context={"collector_name": collector_name, "task_id": existing_running.id}, ) await emit_business_log( logger, event="collector.run.stale_task_failed", message="Marked stale running task as failed before rerun", category="collector", level="warning", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource.id, "task_id": existing_running.id, "status": "failed", }, ) try: datasource_id = datasource.id datasource_source = datasource.source collector._datasource_id = datasource_id logger.info_event( "Running collector", event="collector.run.started", context={"collector_name": collector_name, "datasource_id": datasource_id}, ) await emit_business_log( logger, event="collector.run.scheduled_started", message="Scheduler started collector run", category="collector", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource_id, "status": "running", }, ) task_result = None async with _acquire_collector_slots(collector_name): task_result = await collector.run(db) datasource = await db.get(DataSource, datasource_id) if datasource is None: logger.error_event( "Datasource disappeared after collector run", event="collector.run.datasource_missing_after_run", context={"collector_name": collector_name, "datasource_id": datasource_id}, ) return datasource.last_run_at = datetime.now(UTC) datasource.last_status = task_result.get("status") if datasource.last_status == JobStatus.SUCCESS.value: effective_candidate = await get_builtin_effective_candidate(db, datasource_source) checksum, _credential_context = await build_builtin_connectivity_checksum( datasource_source, effective_candidate["endpoint"], effective_candidate["auth_type"], effective_candidate["headers"], effective_candidate["config"], db, ) await save_connectivity_success( db, datasource_source, checksum, {"status_code": None}, connected_by="collection", ) await _update_next_run_at(datasource, db) logger.info_event( "Collector completed", event="collector.run.completed", context={ "collector_name": collector_name, "datasource_id": datasource_id, "result": task_result, }, ) await emit_business_log( logger, event="collector.run.scheduled_completed", message="Scheduler completed collector run", category="collector", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource_id, "status": task_result.get("status"), "result": task_result, }, ) except asyncio.CancelledError: await db.rollback() datasource = await db.get(DataSource, datasource_id) datasource.last_run_at = datetime.now(UTC) datasource.last_status = JobStatus.CANCELLED.value await db.commit() logger.warning_event( "Collector cancelled by operator", event="collector.run.cancelled", context={"collector_name": collector_name, "datasource_id": datasource.id}, ) await emit_business_log( logger, event="collector.run.cancelled", message="Collector cancelled by operator", category="collector", level="warning", service="scheduler", module=__name__, context={ "collector_name": collector_name, "datasource_id": datasource.id, "status": "cancelled", }, ) raise except Exception as exc: await db.rollback() datasource = await db.get(DataSource, datasource_id) datasource.last_run_at = datetime.now(UTC) datasource.last_status = JobStatus.FAILED.value await db.commit() logger.exception_event( "Collector failed", event="collector.run.failed", context={ "collector_name": collector_name, "datasource_id": datasource.id, "error": str(exc), }, ) await emit_business_log( logger, event="collector.run.failed", message="Collector failed", category="collector", level="error", service="scheduler", module=__name__, context=exception_context( exc, { "collector_name": collector_name, "datasource_id": datasource.id, "status": "failed", }, ), ) async def cleanup_stale_running_tasks( max_age_hours: int = 2, *, include_all_running: bool = False, ) -> int: """Mark stale running tasks as failed after restarts or collector hangs.""" cutoff = datetime.now(UTC) - timedelta(hours=max_age_hours) conditions = [CollectionTask.status == JobStatus.RUNNING.value] if not include_all_running: conditions.extend( [ CollectionTask.started_at.is_not(None), CollectionTask.started_at < cutoff, ] ) async with async_session_factory() as db: result = await db.execute(select(CollectionTask).where(*conditions)) stale_tasks = result.scalars().all() cleanup_error = ( "Marked failed automatically after backend restart" if include_all_running else "Marked failed automatically after stale running task cleanup" ) for task in stale_tasks: task.status = JobStatus.FAILED.value task.phase = "failed" task.completed_at = datetime.now(UTC) existing_error = (task.error_message or "").strip() task.error_message = ( f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error ) if stale_tasks: await db.commit() logger.warning_event( "Cleaned up stale running collection tasks", event="collector.cleanup.stale_tasks_cleaned", context={ "count": len(stale_tasks), "include_all_running": include_all_running, }, ) return len(stale_tasks) async def acquire_scheduler_leader_lock() -> bool: """Acquire a PostgreSQL session advisory lock so only one instance schedules jobs.""" global _leader_lock_conn dsn = str(settings.DATABASE_URL or "").replace("postgresql+asyncpg://", "postgresql://", 1) if not dsn.startswith(("postgresql://", "postgres://")): return True if _leader_lock_conn is not None and not _leader_lock_conn.is_closed(): return True try: conn = await asyncpg.connect(dsn, timeout=5.0) acquired = bool( await conn.fetchval("SELECT pg_try_advisory_lock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY) ) if acquired: _leader_lock_conn = conn logger.info_event( "Acquired scheduler leader advisory lock", event="scheduler.leader_lock.acquired", ) return True await conn.close() return False except Exception as exc: logger.warning_event( "Failed to acquire scheduler leader lock", event="scheduler.leader_lock.error", context={"error": str(exc)}, ) return False async def release_scheduler_leader_lock() -> None: """Release the PostgreSQL scheduler leader advisory lock if held.""" global _leader_lock_conn conn = _leader_lock_conn _leader_lock_conn = None if conn is None or conn.is_closed(): return try: await conn.fetchval("SELECT pg_advisory_unlock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY) except Exception as exc: logger.warning_event( "Failed to unlock scheduler leader lock cleanly", event="scheduler.leader_lock.unlock_failed", context={"error": str(exc)}, ) finally: await conn.close() async def run_compute_presentation_retry_job() -> None: """Retry pending or failed compute revision stage presentations.""" from app.services.ai.proactive_pipeline import retry_pending_compute_presentations async with async_session_factory() as db: try: await retry_pending_compute_presentations(db) await db.commit() except Exception as exc: await db.rollback() logger.warning_event( "Scheduled compute presentation retry failed", event="compute.revision.presentation_failed", context={"phase": "scheduler", "error": str(exc)}, ) def start_scheduler() -> None: """Start the scheduler.""" if not scheduler.running: scheduler.add_job( refresh_earth_news_all_regions, trigger=IntervalTrigger(seconds=EARTH_NEWS_REFRESH_INTERVAL_SECONDS), id=EARTH_NEWS_REFRESH_JOB_ID, name="Earth news RSS refresh", replace_existing=True, next_run_time=datetime.now(UTC), max_instances=1, coalesce=True, misfire_grace_time=60, ) scheduler.add_job( run_storage_retention_maintenance, trigger=IntervalTrigger(hours=STORAGE_RETENTION_INTERVAL_HOURS), id=STORAGE_RETENTION_JOB_ID, name="Collection storage retention maintenance", replace_existing=True, max_instances=1, coalesce=True, misfire_grace_time=300, ) scheduler.add_job( run_compute_presentation_retry_job, trigger=IntervalTrigger(minutes=COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES), id=COMPUTE_PRESENTATION_RETRY_JOB_ID, name="Compute revision presentation retry", replace_existing=True, max_instances=1, coalesce=True, misfire_grace_time=120, ) scheduler.start() logger.info_event("Scheduler started", event="scheduler.started") def stop_scheduler() -> None: """Stop the scheduler.""" if scheduler.running: scheduler.shutdown(wait=False) logger.info_event("Scheduler stopped", event="scheduler.stopped") def schedule_earth_news_region_refresh( region: str, *, force: bool = False, refresh_id: str | None = None ) -> bool: """Queue one immediate, per-region RSS refresh and merge duplicate requests.""" normalized_region = str(region or "").strip().lower() if normalized_region not in REGION_ANCHORS: raise ValueError(f"Unsupported Earth news region: {region}") if normalized_region in _running_earth_news_refreshes: rerun = _rerun_earth_news_refreshes.setdefault( normalized_region, {"force": False, "refresh_id": None} ) rerun["force"] = rerun["force"] or force rerun["refresh_id"] = refresh_id or rerun["refresh_id"] return False if normalized_region in _pending_earth_news_refreshes: pending = _pending_earth_news_refreshes[normalized_region] pending["force"] = pending["force"] or force pending["refresh_id"] = refresh_id or pending["refresh_id"] return False _pending_earth_news_refreshes[normalized_region] = { "force": force, "refresh_id": refresh_id, } job_id = _earth_news_region_refresh_job_id(normalized_region) try: scheduler.add_job( _run_earth_news_region_refresh, trigger=DateTrigger(run_date=datetime.now(UTC)), id=job_id, name=f"Earth news RSS refresh: {normalized_region}", kwargs={"region": normalized_region}, replace_existing=False, max_instances=1, coalesce=True, misfire_grace_time=60, ) except Exception: _pending_earth_news_refreshes.pop(normalized_region, None) raise return True def request_earth_news_region_refresh(region: str) -> dict[str, Any]: normalized_region = str(region or "").strip().lower() if normalized_region not in REGION_ANCHORS: raise ValueError(f"Unsupported Earth news region: {region}") status, created = create_earth_news_refresh_status(normalized_region) if created: try: schedule_earth_news_region_refresh( normalized_region, force=True, refresh_id=status["refresh_id"], ) except Exception: return set_earth_news_refresh_status( status["refresh_id"], normalized_region, "failed", error={ "code": "refresh_failed", "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], }, ) return status def schedule_earth_news_refresh_for_all_regions(*, force: bool = False) -> None: for region in REGION_ANCHORS: schedule_earth_news_region_refresh(region, force=force) def _earth_news_region_refresh_job_id(region: str) -> str: return f"{EARTH_NEWS_REFRESH_JOB_ID}:{region}" async def _run_earth_news_region_refresh(region: str) -> None: request = _pending_earth_news_refreshes.pop(region, {"force": False, "refresh_id": None}) force = bool(request["force"]) refresh_id = request["refresh_id"] _running_earth_news_refreshes.add(region) status_heartbeat: asyncio.Task[None] | None = None try: if refresh_id: set_earth_news_refresh_status(refresh_id, region, "running") if not touch_earth_news_refresh_status(refresh_id, region): return status_heartbeat = asyncio.create_task( _earth_news_refresh_status_heartbeat(refresh_id, region) ) deadline = time.monotonic() + EARTH_NEWS_REFRESH_WAIT_SECONDS while True: result = await refresh_earth_news_region(region, force=force) if result["state"] != "busy": break if time.monotonic() >= deadline: set_earth_news_refresh_status( refresh_id, region, "failed", error={ "code": "refresh_failed", "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], }, ) return await asyncio.sleep(EARTH_NEWS_REFRESH_POLL_SECONDS) if result["state"] == "coordination_unavailable": error_code = "refresh_failed" elif result["state"] == "failed": error_code = result.get("error_code") or "source_unavailable" elif result["state"] == "completed" and result.get("successful_sources", 0) > 0: set_earth_news_refresh_status(refresh_id, region, "succeeded") return else: error_code = "source_unavailable" set_earth_news_refresh_status( refresh_id, region, "failed", error={ "code": error_code, "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS.get( error_code, EARTH_NEWS_REFRESH_PUBLIC_ERRORS["source_unavailable"] ), }, ) else: await refresh_earth_news_region(region, force=force) except asyncio.CancelledError: if refresh_id: set_earth_news_refresh_status( refresh_id, region, "failed", error={ "code": "refresh_failed", "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], }, ) raise except Exception as exc: logger.warning_event( "Earth news tracked refresh failed", event="earth_news.rss.tracked_refresh_failed", context={"region": region, "error": str(exc)}, ) if refresh_id: try: set_earth_news_refresh_status( refresh_id, region, "failed", error={ "code": "refresh_failed", "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], }, ) except Exception as status_exc: logger.warning_event( "Earth news refresh status update failed", event="earth_news.rss.refresh_status_update_failed", context={"region": region, "error": str(status_exc)}, ) finally: if status_heartbeat is not None: status_heartbeat.cancel() try: await status_heartbeat except asyncio.CancelledError: pass _running_earth_news_refreshes.discard(region) rerun = _rerun_earth_news_refreshes.pop(region, None) if rerun is not None and scheduler.running: schedule_earth_news_region_refresh( region, force=rerun["force"], refresh_id=rerun["refresh_id"], ) async def _earth_news_refresh_status_heartbeat(refresh_id: str, region: str) -> None: try: while True: await asyncio.sleep(EARTH_NEWS_STATUS_HEARTBEAT_SECONDS) if not touch_earth_news_refresh_status(refresh_id, region): return except asyncio.CancelledError: raise except Exception as exc: logger.warning_event( "Earth news refresh status heartbeat failed", event="earth_news.rss.refresh_status_heartbeat_failed", context={"region": region, "error": str(exc)}, ) async def sync_scheduler_with_datasources() -> None: """Synchronize scheduler jobs with datasource table.""" async with async_session_factory() as db: result = await db.execute(select(DataSource).order_by(DataSource.id)) datasources = result.scalars().all() configured_sources = {datasource.source for datasource in datasources} for job in list(scheduler.get_jobs()): is_earth_news_refresh = job.id == EARTH_NEWS_REFRESH_JOB_ID or job.id.startswith( f"{EARTH_NEWS_REFRESH_JOB_ID}:" ) if ( job.id not in configured_sources and not is_earth_news_refresh and job.id != STORAGE_RETENTION_JOB_ID and job.id != COMPUTE_PRESENTATION_RETRY_JOB_ID ): scheduler.remove_job(job.id) for datasource in datasources: await _apply_datasource_schedule(datasource, db) async def sync_datasource_job(datasource_id: int) -> bool: """Synchronize a single datasource job after settings changes.""" async with async_session_factory() as db: datasource = await db.get(DataSource, datasource_id) if not datasource: return False await _apply_datasource_schedule(datasource, db) return True def get_scheduler_jobs() -> list[Dict[str, Any]]: """Get all scheduled jobs.""" jobs = [] for job in scheduler.get_jobs(): jobs.append( { "id": job.id, "name": job.name, "next_run_time": to_iso8601_utc(job.next_run_time), "trigger": str(job.trigger), } ) return jobs async def get_latest_task_id_for_datasource(datasource_id: int) -> Optional[int]: from app.models.task import CollectionTask async with async_session_factory() as db: result = await db.execute( select(CollectionTask.id) .where(CollectionTask.datasource_id == datasource_id) .order_by(CollectionTask.created_at.desc(), CollectionTask.id.desc()) .limit(1) ) return result.scalar_one_or_none() def run_collector_now(collector_name: str) -> bool: """Run a collector immediately (not scheduled).""" collector = collector_registry.get(collector_name) if not collector: logger.error_event( "Collector not found", event="collector.trigger.collector_missing", context={"collector_name": collector_name}, ) return False existing_task = get_running_collector_task(collector_name) if existing_task is not None and not existing_task.done(): logger.warning_event( "Collector is already running in-memory; skipping duplicate trigger", event="collector.trigger.skipped_already_running", context={"collector_name": collector_name}, ) emit_business_log_background( logger, event="collector.trigger.skipped_already_running", message="Collector is already running in-memory; skipping duplicate trigger", category="collector", level="warning", service="scheduler", module=__name__, context={"collector_name": collector_name, "status": "skipped"}, ) return False try: task = asyncio.create_task( run_collector_task(collector_name), name=_collector_task_name(collector_name) ) RUNNING_COLLECTOR_TASKS[collector_name] = task def _cleanup_task(done_task: asyncio.Task[Any]) -> None: current = RUNNING_COLLECTOR_TASKS.get(collector_name) if current is done_task: RUNNING_COLLECTOR_TASKS.pop(collector_name, None) task.add_done_callback(_cleanup_task) logger.info_event( "Triggered collector", event="collector.trigger.started", context={"collector_name": collector_name}, ) emit_business_log_background( logger, event="collector.trigger.started", message="Triggered collector", category="collector", service="scheduler", module=__name__, context={"collector_name": collector_name, "status": "queued"}, ) return True except Exception as exc: logger.error_event( "Failed to trigger collector", event="collector.trigger.failed", context={"collector_name": collector_name, "error": str(exc)}, ) emit_business_log_background( logger, event="collector.trigger.failed", message="Failed to trigger collector", category="collector", level="error", service="scheduler", module=__name__, context=exception_context(exc, {"collector_name": collector_name, "status": "failed"}), ) return False def is_collector_running(collector_name: str) -> bool: task = get_running_collector_task(collector_name) return bool(task is not None and not task.done()) async def cancel_running_collector_now(collector_name: str) -> bool: task = get_running_collector_task(collector_name) if task is None or task.done(): RUNNING_COLLECTOR_TASKS.pop(collector_name, None) return False task.cancel() try: await task except asyncio.CancelledError: return True return task.cancelled()