"""FastAPI application for the SkiPredictor backend. Manages: - REST API serving forecast data - APScheduler for periodic forecast generation and retraining - Telegram bot as a subprocess """ from __future__ import annotations import logging import os import signal import subprocess import sys from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path from typing import Any, AsyncIterator from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from fastapi import FastAPI from app.api.auth import auth_router from app.api.routes import router from app.scheduler.tasks import run_forecast_cycle, run_retrain logger = logging.getLogger(__name__) _PROJECT_ROOT = Path(__file__).resolve().parents[1] _TIMEZONE = "Europe/Madrid" # Shared mutable state visible to the /status endpoint app_state: dict[str, Any] = { "bot_active": False, "next_forecast_run": None, "next_training_run": None, } # --------------------------------------------------------------------------- # Lifespan # --------------------------------------------------------------------------- def _start_scheduler() -> BackgroundScheduler: """Configure and start the APScheduler instance.""" scheduler = BackgroundScheduler(timezone=_TIMEZONE) # Forecast runs: 00, 05, 10, 15, 20 Europe/Madrid for hour in (0, 5, 10, 15, 20): scheduler.add_job( run_forecast_cycle, trigger=CronTrigger(hour=hour, minute=0, timezone=_TIMEZONE), args=[hour], id=f"forecast_{hour:02d}", name=f"Forecast run {hour:02d}:00", replace_existing=True, ) # Weekly retrain: Monday 03:00 scheduler.add_job( run_retrain, trigger=CronTrigger(day_of_week="mon", hour=3, minute=0, timezone=_TIMEZONE), id="retrain_weekly", name="Weekly model retrain", replace_existing=True, ) scheduler.start() logger.info("APScheduler started with %d jobs.", len(scheduler.get_jobs())) # Populate next-run info for /status _update_next_runs(scheduler) return scheduler def _update_next_runs(scheduler: BackgroundScheduler) -> None: """Refresh next_forecast_run and next_training_run in app_state.""" forecast_next: datetime | None = None training_next: datetime | None = None for job in scheduler.get_jobs(): nrt = job.next_run_time if nrt is None: continue if job.id.startswith("forecast_"): if forecast_next is None or nrt < forecast_next: forecast_next = nrt elif job.id == "retrain_weekly": training_next = nrt app_state["next_forecast_run"] = ( forecast_next.isoformat() if forecast_next else None ) app_state["next_training_run"] = ( training_next.isoformat() if training_next else None ) def _start_bot_subprocess() -> subprocess.Popen | None: """Launch the Telegram bot as a subprocess.""" token = os.environ.get("TELEGRAM_BOT_TOKEN") if not token: logger.warning( "TELEGRAM_BOT_TOKEN not set. Telegram bot will NOT start." ) return None env = {**os.environ, "PYTHONPATH": str(_PROJECT_ROOT)} try: proc = subprocess.Popen( [sys.executable, "-m", "bot.telegram_bot"], cwd=str(_PROJECT_ROOT), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) logger.info("Telegram bot subprocess started (PID=%d).", proc.pid) app_state["bot_active"] = True return proc except Exception as exc: logger.error("Failed to start Telegram bot subprocess: %s", exc) return None def _stop_bot_subprocess(proc: subprocess.Popen | None) -> None: """Gracefully terminate the Telegram bot subprocess.""" if proc is None: return app_state["bot_active"] = False try: proc.send_signal(signal.SIGTERM) proc.wait(timeout=10) logger.info("Telegram bot subprocess stopped.") except subprocess.TimeoutExpired: proc.kill() logger.warning("Telegram bot subprocess killed after timeout.") except Exception as exc: logger.error("Error stopping bot subprocess: %s", exc) @asynccontextmanager async def lifespan(application: FastAPI) -> AsyncIterator[None]: """Manage startup and shutdown of scheduler and bot subprocess.""" scheduler = _start_scheduler() bot_proc = _start_bot_subprocess() yield logger.info("Shutting down scheduler and bot subprocess...") scheduler.shutdown(wait=False) _stop_bot_subprocess(bot_proc) # --------------------------------------------------------------------------- # App # --------------------------------------------------------------------------- _DESCRIPTION = """\ Forecast API for ski stations in northern Spain. ## Authentication All endpoints except `/health` require a valid JWT bearer token. Register a user and login to obtain one (valid for 14 days). ## Endpoints | Method | Path | Auth | Description | |--------|------|------|-------------| | POST | `/api/v1/auth/register` | No | Create user account | | POST | `/api/v1/auth/login` | No | Obtain JWT (14 days) | | GET | `/api/v1/health` | No | Health check | | GET | `/api/v1/stations` | **Yes** | List tracked stations | | GET | `/api/v1/forecast` | **Yes** | Latest forecast (all stations) | | GET | `/api/v1/forecast/history` | **Yes** | Past forecast runs | | GET | `/api/v1/forecast/{station_id}` | **Yes** | Forecast for one station | | GET | `/api/v1/status` | **Yes** | System status | """ app = FastAPI( title="SkiPredictor API", version="1.0.0", description=_DESCRIPTION, lifespan=lifespan, ) app.include_router(router) app.include_router(auth_router)