From 9d97afe53818dcd42e1ee2fc0a78844ed669c23b Mon Sep 17 00:00:00 2001 From: Dasemu Date: Fri, 13 Mar 2026 09:36:18 +0100 Subject: [PATCH] feat(api): add FastAPI backend with JWT authentication REST API serving forecast data with HS256 JWT auth (14-day tokens). Public: /health, /auth/register, /auth/login. Protected: /stations, /forecast, /forecast/history, /forecast/{id}, /status. Includes APScheduler for periodic forecasts and Telegram bot subprocess. --- API_SPEC.md | 276 +++++++++++++++++++++++++++++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/auth.py | 132 ++++++++++++++++++ app/api/routes.py | 277 ++++++++++++++++++++++++++++++++++++++ app/api/schemas.py | 111 +++++++++++++++ app/main.py | 191 ++++++++++++++++++++++++++ app/scheduler/__init__.py | 0 app/scheduler/tasks.py | 276 +++++++++++++++++++++++++++++++++++++ requirements.txt | 6 + start.sh | 22 +-- storage/__init__.py | 6 + storage/sqlite_store.py | 231 +++++++++++++++++++++++++++++++ tests/test_auth.py | 113 ++++++++++++++++ 14 files changed, 1631 insertions(+), 10 deletions(-) create mode 100644 API_SPEC.md create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/auth.py create mode 100644 app/api/routes.py create mode 100644 app/api/schemas.py create mode 100644 app/main.py create mode 100644 app/scheduler/__init__.py create mode 100644 app/scheduler/tasks.py create mode 100644 tests/test_auth.py diff --git a/API_SPEC.md b/API_SPEC.md new file mode 100644 index 0000000..22ec142 --- /dev/null +++ b/API_SPEC.md @@ -0,0 +1,276 @@ +# SkiPredictor API Specification v1 + +Base URL: `/api/v1` + +All responses use JSON. Dates use ISO 8601 format (`YYYY-MM-DD`). Timestamps use ISO 8601 with timezone (`YYYY-MM-DDTHH:MM:SS+HH:MM`). + +--- + +## Stations + +### `GET /api/v1/stations` + +List all tracked ski stations with metadata. + +**Response 200:** +```json +{ + "stations": [ + { + "station_id": "pajares", + "name": "Valgrande-Pajares", + "max_km": 22.0, + "latitude": 43.05, + "longitude": -5.77, + "altitude": 1505, + "wind_closure_threshold_kmh": 80, + "min_snow_depth_cm": 30 + }, + { + "station_id": "sanisidro", + "name": "San Isidro", + "max_km": 31.0, + "latitude": 43.07, + "longitude": -5.37, + "altitude": 1500, + "wind_closure_threshold_kmh": 80, + "min_snow_depth_cm": 30 + }, + { + "station_id": "fuentes", + "name": "Fuentes de Invierno", + "max_km": 8.6, + "latitude": 43.08, + "longitude": -5.93, + "altitude": 1500, + "wind_closure_threshold_kmh": 80, + "min_snow_depth_cm": 30 + } + ] +} +``` + +--- + +## Forecasts + +### `GET /api/v1/forecast` + +Get the latest forecast for **all stations**. Returns today + next 7 days per station. + +**Response 200:** +```json +{ + "generated_at": "2026-03-13T10:00:00+01:00", + "run_hour": 10, + "stations": { + "pajares": { + "station_id": "pajares", + "name": "Valgrande-Pajares", + "days": [ + { + "date": "2026-03-13", + "open_probability": 0.85, + "open_label": "Abierta", + "km_open": 18.5, + "max_km": 22.0, + "crowd_level": "medium", + "weather_summary": "Nieve ligera, -2°C, viento 25 km/h", + "rule_notes": [], + "prediction_source": "hybrid" + }, + { + "date": "2026-03-14", + "open_probability": 0.72, + "open_label": "Abierta", + "km_open": 15.0, + "max_km": 22.0, + "crowd_level": "high", + "weather_summary": "Soleado, 3°C, viento 15 km/h", + "rule_notes": ["Fin de semana + nieve reciente"], + "prediction_source": "hybrid" + } + ] + }, + "sanisidro": { "...same structure..." }, + "fuentes": { "...same structure..." } + } +} +``` + +**Notes:** +- `open_label`: `"Abierta"` (>=0.70), `"Probable apertura"` (>=0.40), `"Cerrada"` (<0.40) +- At run hours 15 and 20, `days[0]` is tomorrow (today is omitted) +- At run hours 00, 05, and 10, `days[0]` is today + +--- + +### `GET /api/v1/forecast/{station_id}` + +Get the latest forecast for a **single station**. Same structure as above but only one station. + +**Path parameters:** +- `station_id`: `pajares` | `sanisidro` | `fuentes` + +**Response 200:** +```json +{ + "generated_at": "2026-03-13T10:00:00+01:00", + "run_hour": 10, + "station_id": "pajares", + "name": "Valgrande-Pajares", + "days": [ + { + "date": "2026-03-13", + "open_probability": 0.85, + "open_label": "Abierta", + "km_open": 18.5, + "max_km": 22.0, + "crowd_level": "medium", + "weather_summary": "Nieve ligera, -2°C, viento 25 km/h", + "rule_notes": [], + "prediction_source": "hybrid" + } + ] +} +``` + +**Response 404:** +```json +{ + "detail": "Station 'xyz' not found. Valid: pajares, sanisidro, fuentes" +} +``` + +--- + +### `GET /api/v1/forecast/history` + +Get past forecast runs (archived when a new run replaces them). + +**Query parameters:** +- `station_id` (optional): filter by station +- `date_from` (optional): earliest prediction date (`YYYY-MM-DD`) +- `date_to` (optional): latest prediction date (`YYYY-MM-DD`) +- `limit` (optional, default 50, max 200): number of runs to return +- `offset` (optional, default 0): pagination offset + +**Response 200:** +```json +{ + "total": 150, + "limit": 50, + "offset": 0, + "runs": [ + { + "generated_at": "2026-03-13T05:00:00+01:00", + "run_hour": 5, + "prediction_date": "2026-03-13", + "station_id": "pajares", + "open_probability": 0.85, + "km_open": 18.5, + "crowd_level": "medium", + "prediction_source": "hybrid" + } + ] +} +``` + +--- + +## System + +### `GET /api/v1/health` + +Health check endpoint. + +**Response 200:** +```json +{ + "status": "ok", + "timestamp": "2026-03-13T10:15:00+01:00" +} +``` + +--- + +### `GET /api/v1/status` + +System status: last forecast run, next scheduled run, model info. + +**Response 200:** +```json +{ + "last_forecast_run": "2026-03-13T10:00:00+01:00", + "next_forecast_run": "2026-03-13T15:00:00+01:00", + "last_training_run": "2026-03-10T03:00:00+01:00", + "next_training_run": "2026-03-17T03:00:00+01:00", + "models": { + "station_open": "RandomForestClassifier", + "km_open": "GradientBoostingRegressor", + "crowd_level": "LGBMClassifier" + }, + "telegram_bot_active": true, + "stations_count": 3, + "database_size_mb": 8.1 +} +``` + +--- + +## Schedule (internal, not exposed as API) + +The backend orchestrates these tasks internally: + +| Hour (Europe/Madrid) | Task | +|---|---| +| 00:00 | Forecast run: today + 7 days | +| 05:00 | Forecast run: today + 7 days | +| 10:00 | Forecast run: today + 7 days | +| 15:00 | Forecast run: tomorrow + 6 days (skip today) | +| 20:00 | Forecast run: tomorrow + 6 days (skip today) + scrape today's actual | +| Weekly (Monday 03:00) | ML model retraining | + +Each forecast run: +1. Archives current forecasts → `past_forecasts` table +2. Fetches fresh weather data from Open-Meteo +3. Generates new predictions via HybridPredictor +4. Stores in `current_forecasts` table + +--- + +## Database Tables (new/modified) + +### `current_forecasts` +Active predictions served by the API. + +| Column | Type | Description | +|---|---|---| +| id | INTEGER PK | Auto-increment | +| generated_at | TEXT | When this forecast was created | +| run_hour | INTEGER | Hour of the run (0, 5, 10, 15, 20) | +| station_id | TEXT | pajares/sanisidro/fuentes | +| prediction_date | TEXT | The date being predicted | +| open_probability | REAL | 0.0 - 1.0 | +| km_open | REAL | Predicted km open | +| crowd_level | TEXT | low/medium/high | +| weather_summary | TEXT | Human-readable weather | +| rule_notes_json | TEXT | JSON array of rule notes | +| prediction_source | TEXT | rules/ml/hybrid | + +### `past_forecasts` +Archived forecasts (same schema as `current_forecasts`). + +### `historical_actuals` +Actual station data scraped from infonieve at 20:00. + +| Column | Type | Description | +|---|---|---| +| id | INTEGER PK | Auto-increment | +| date | TEXT | The actual date | +| station_id | TEXT | pajares/sanisidro/fuentes | +| open_status | INTEGER | 0 or 1 | +| km_open | REAL | Actual km open | +| lifts_open | INTEGER | Number of lifts open | +| snow_depth | REAL | Snow depth cm | +| scraped_at | TEXT | When data was scraped | diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/auth.py b/app/api/auth.py new file mode 100644 index 0000000..b6e8f25 --- /dev/null +++ b/app/api/auth.py @@ -0,0 +1,132 @@ +"""JWT authentication: register, login, and token validation.""" + +from __future__ import annotations + +import logging +import os +from datetime import datetime, timedelta, timezone + +import jwt +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm +from passlib.context import CryptContext + +from app.api.schemas import TokenResponse, UserCreate, UserResponse +from storage import SQLiteStore + +logger = logging.getLogger(__name__) + +_TOKEN_EXPIRE_DAYS = 14 +_ALGORITHM = "HS256" + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") + +auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) + + +def _get_secret_key() -> str: + key = os.environ.get("JWT_SECRET_KEY") + if not key: + raise RuntimeError("JWT_SECRET_KEY environment variable is not set") + return key + + +def _create_token(user_id: int, email: str) -> str: + now = datetime.now(timezone.utc) + payload = { + "sub": str(user_id), + "email": email, + "iat": now, + "exp": now + timedelta(days=_TOKEN_EXPIRE_DAYS), + } + return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM) + + +def get_current_user(token: str = Depends(oauth2_scheme)) -> dict: + """FastAPI dependency that validates the JWT and returns user info.""" + try: + payload = jwt.decode( + token, _get_secret_key(), algorithms=[_ALGORITHM] + ) + user_id = payload.get("sub") + email = payload.get("email") + if user_id is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="login required", + ) + return {"user_id": int(user_id), "email": email} + except jwt.ExpiredSignatureError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="login required", + ) + except jwt.InvalidTokenError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="login required", + ) + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + + +@auth_router.post( + "/register", + response_model=UserResponse, + status_code=status.HTTP_201_CREATED, +) +def register(body: UserCreate) -> UserResponse: + """Create a new user account.""" + store = SQLiteStore() + hashed = pwd_context.hash(body.password) + now_iso = datetime.now(timezone.utc).isoformat() + + with store.connect() as conn: + existing = conn.execute( + "SELECT id FROM users WHERE email = ?", (body.email,) + ).fetchone() + if existing: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="email already registered", + ) + cursor = conn.execute( + """ + INSERT INTO users (email, password_hash, created_at) + VALUES (?, ?, ?) + """, + (body.email, hashed, now_iso), + ) + user_id = cursor.lastrowid + + return UserResponse(id=user_id, email=body.email) + + +@auth_router.post("/login", response_model=TokenResponse) +def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse: + """Authenticate and return a JWT token.""" + store = SQLiteStore() + + with store.connect() as conn: + row = conn.execute( + "SELECT id, email, password_hash FROM users WHERE email = ?", + (form.username,), + ).fetchone() + + if row is None or not pwd_context.verify(form.password, row["password_hash"]): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid credentials", + ) + + conn.execute( + "UPDATE users SET last_login_at = ? WHERE id = ?", + (datetime.now(timezone.utc).isoformat(), row["id"]), + ) + + token = _create_token(row["id"], row["email"]) + return TokenResponse(access_token=token) diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000..908e088 --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,277 @@ +"""REST API endpoints for the SkiPredictor backend.""" + +from __future__ import annotations + +import json +import logging +from datetime import datetime +from pathlib import Path +from typing import Any + +import yaml +from fastapi import APIRouter, Depends, HTTPException, Query + +from app.api.auth import get_current_user +from app.api.schemas import ( + DayForecast, + ForecastAllResponse, + ForecastHistoryResponse, + ForecastHistoryRun, + ForecastStationResponse, + HealthResponse, + StationForecast, + StationInfo, + StationsResponse, + StatusResponse, +) +from storage import SQLiteStore + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/v1") + +_PROJECT_ROOT = Path(__file__).resolve().parents[2] +_STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml" + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +_VALID_STATION_IDS: set[str] | None = None + + +def _load_stations_config() -> dict[str, Any]: + """Load and cache the stations YAML configuration.""" + with open(_STATIONS_YAML) as fh: + return yaml.safe_load(fh)["stations"] + + +def _valid_station_ids() -> set[str]: + global _VALID_STATION_IDS + if _VALID_STATION_IDS is None: + _VALID_STATION_IDS = set(_load_stations_config().keys()) + return _VALID_STATION_IDS + + +def _open_label(probability: float) -> str: + if probability >= 0.70: + return "Abierta" + if probability >= 0.40: + return "Probable apertura" + return "Cerrada" + + +def _get_store() -> SQLiteStore: + return SQLiteStore() + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + + +@router.get("/stations", response_model=StationsResponse) +def get_stations(user: dict = Depends(get_current_user)) -> StationsResponse: + """List all tracked ski stations with metadata.""" + cfg = _load_stations_config() + stations = [] + for sid, data in cfg.items(): + stations.append( + StationInfo( + station_id=sid, + name=data["name"], + max_km=data["max_km_skiable"], + latitude=data["latitude"], + longitude=data["longitude"], + altitude=data["altitude"], + wind_closure_threshold_kmh=data["wind_closure_threshold"], + min_snow_depth_cm=data["minimum_snow_depth"], + ) + ) + return StationsResponse(stations=stations) + + +@router.get("/forecast", response_model=ForecastAllResponse) +def get_forecast_all(user: dict = Depends(get_current_user)) -> ForecastAllResponse: + """Get the latest forecast for all stations.""" + store = _get_store() + rows = store.load_current_forecasts() + return _build_forecast_all(rows) + + +@router.get("/forecast/history", response_model=ForecastHistoryResponse) +def get_forecast_history( + station_id: str | None = Query(None), + date_from: str | None = Query(None), + date_to: str | None = Query(None), + limit: int = Query(50, ge=1, le=200), + offset: int = Query(0, ge=0), + user: dict = Depends(get_current_user), +) -> ForecastHistoryResponse: + """Get past forecast runs with pagination.""" + store = _get_store() + total = store.count_past_forecasts( + station_id=station_id, date_from=date_from, date_to=date_to + ) + rows = store.load_past_forecasts( + station_id=station_id, + date_from=date_from, + date_to=date_to, + limit=limit, + offset=offset, + ) + runs = [ + ForecastHistoryRun( + generated_at=r["generated_at"], + run_hour=r["run_hour"], + prediction_date=r["prediction_date"], + station_id=r["station_id"], + open_probability=r.get("open_probability"), + km_open=r.get("km_open"), + crowd_level=r.get("crowd_level"), + prediction_source=r.get("prediction_source"), + ) + for r in rows + ] + return ForecastHistoryResponse( + total=total, limit=limit, offset=offset, runs=runs + ) + + +@router.get("/forecast/{station_id}", response_model=ForecastStationResponse) +def get_forecast_station(station_id: str, user: dict = Depends(get_current_user)) -> ForecastStationResponse: + """Get the latest forecast for a single station.""" + valid = _valid_station_ids() + if station_id not in valid: + raise HTTPException( + status_code=404, + detail=f"Station '{station_id}' not found. Valid: {', '.join(sorted(valid))}", + ) + + store = _get_store() + rows = store.load_current_forecasts(station_id=station_id) + cfg = _load_stations_config() + + generated_at = rows[0]["generated_at"] if rows else None + run_hour = rows[0]["run_hour"] if rows else None + station_cfg = cfg[station_id] + max_km = station_cfg["max_km_skiable"] + + days = _rows_to_day_forecasts(rows, max_km) + return ForecastStationResponse( + generated_at=generated_at, + run_hour=run_hour, + station_id=station_id, + name=station_cfg["name"], + days=days, + ) + + +@router.get("/health", response_model=HealthResponse) +def get_health() -> HealthResponse: + """Health check endpoint.""" + return HealthResponse( + status="ok", + timestamp=datetime.now().astimezone().isoformat(), + ) + + +@router.get("/status", response_model=StatusResponse) +def get_status(user: dict = Depends(get_current_user)) -> StatusResponse: + """System status: last/next forecast run, training info, bot status.""" + from app.main import app_state + + store = _get_store() + + # Last forecast run + forecasts = store.load_current_forecasts() + last_forecast = forecasts[0]["generated_at"] if forecasts else None + + # Last training run + last_training: str | None = None + with store.connect() as conn: + row = conn.execute( + "SELECT completed_at FROM training_runs ORDER BY completed_at DESC LIMIT 1" + ).fetchone() + if row: + last_training = row["completed_at"] + + # Model info + models: dict[str, str] = {} + model_dir = _PROJECT_ROOT / "ml" / "models" + if model_dir.exists(): + for model_file in model_dir.glob("*.joblib"): + target = model_file.stem + models[target] = target + + # Database size + db_size_mb = 0.0 + if store.db_path.exists(): + db_size_mb = round(store.db_path.stat().st_size / (1024 * 1024), 1) + + return StatusResponse( + last_forecast_run=last_forecast, + next_forecast_run=app_state.get("next_forecast_run"), + last_training_run=last_training, + next_training_run=app_state.get("next_training_run"), + models=models, + telegram_bot_active=app_state.get("bot_active", False), + stations_count=len(_valid_station_ids()), + database_size_mb=db_size_mb, + ) + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + + +def _rows_to_day_forecasts( + rows: list[dict[str, Any]], max_km: float +) -> list[DayForecast]: + """Convert raw DB rows into DayForecast models.""" + days = [] + for r in rows: + prob = r.get("open_probability") + notes_raw = r.get("rule_notes_json") or "[]" + notes = json.loads(notes_raw) if isinstance(notes_raw, str) else notes_raw + days.append( + DayForecast( + date=r["prediction_date"], + open_probability=prob, + open_label=_open_label(prob) if prob is not None else None, + km_open=r.get("km_open"), + max_km=max_km, + crowd_level=r.get("crowd_level"), + weather_summary=r.get("weather_summary"), + rule_notes=notes, + prediction_source=r.get("prediction_source"), + ) + ) + return days + + +def _build_forecast_all(rows: list[dict[str, Any]]) -> ForecastAllResponse: + """Group raw DB rows by station into the all-stations response.""" + cfg = _load_stations_config() + + generated_at = rows[0]["generated_at"] if rows else None + run_hour = rows[0]["run_hour"] if rows else None + + by_station: dict[str, list[dict[str, Any]]] = {} + for r in rows: + by_station.setdefault(r["station_id"], []).append(r) + + stations: dict[str, StationForecast] = {} + for sid, station_rows in by_station.items(): + station_cfg = cfg.get(sid, {}) + max_km = station_cfg.get("max_km_skiable", 0.0) + stations[sid] = StationForecast( + station_id=sid, + name=station_cfg.get("name", sid), + days=_rows_to_day_forecasts(station_rows, max_km), + ) + + return ForecastAllResponse( + generated_at=generated_at, run_hour=run_hour, stations=stations + ) diff --git a/app/api/schemas.py b/app/api/schemas.py new file mode 100644 index 0000000..d370938 --- /dev/null +++ b/app/api/schemas.py @@ -0,0 +1,111 @@ +"""Pydantic response models for the SkiPredictor REST API.""" + +from __future__ import annotations + +from pydantic import BaseModel, Field + + +# -- Stations --------------------------------------------------------------- + +class StationInfo(BaseModel): + station_id: str + name: str + max_km: float + latitude: float + longitude: float + altitude: int + wind_closure_threshold_kmh: int + min_snow_depth_cm: int + + +class StationsResponse(BaseModel): + stations: list[StationInfo] + + +# -- Forecasts --------------------------------------------------------------- + +class DayForecast(BaseModel): + date: str + open_probability: float | None = None + open_label: str | None = None + km_open: float | None = None + max_km: float | None = None + crowd_level: str | None = None + weather_summary: str | None = None + rule_notes: list[str] = Field(default_factory=list) + prediction_source: str | None = None + + +class StationForecast(BaseModel): + station_id: str + name: str + days: list[DayForecast] + + +class ForecastAllResponse(BaseModel): + generated_at: str | None = None + run_hour: int | None = None + stations: dict[str, StationForecast] + + +class ForecastStationResponse(BaseModel): + generated_at: str | None = None + run_hour: int | None = None + station_id: str + name: str + days: list[DayForecast] + + +# -- Forecast history -------------------------------------------------------- + +class ForecastHistoryRun(BaseModel): + generated_at: str + run_hour: int + prediction_date: str + station_id: str + open_probability: float | None = None + km_open: float | None = None + crowd_level: str | None = None + prediction_source: str | None = None + + +class ForecastHistoryResponse(BaseModel): + total: int + limit: int + offset: int + runs: list[ForecastHistoryRun] + + +# -- System ------------------------------------------------------------------ + +class HealthResponse(BaseModel): + status: str + timestamp: str + + +class StatusResponse(BaseModel): + last_forecast_run: str | None = None + next_forecast_run: str | None = None + last_training_run: str | None = None + next_training_run: str | None = None + models: dict[str, str] = Field(default_factory=dict) + telegram_bot_active: bool = False + stations_count: int = 0 + database_size_mb: float = 0.0 + + +# -- Auth ------------------------------------------------------------------- + +class UserCreate(BaseModel): + email: str = Field(..., min_length=3) + password: str = Field(..., min_length=8) + + +class UserResponse(BaseModel): + id: int + email: str + + +class TokenResponse(BaseModel): + access_token: str + token_type: str = "bearer" diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..1f39e48 --- /dev/null +++ b/app/main.py @@ -0,0 +1,191 @@ +"""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) diff --git a/app/scheduler/__init__.py b/app/scheduler/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/scheduler/tasks.py b/app/scheduler/tasks.py new file mode 100644 index 0000000..97e3373 --- /dev/null +++ b/app/scheduler/tasks.py @@ -0,0 +1,276 @@ +"""Scheduled tasks for forecast generation and model retraining. + +These functions are invoked by APScheduler from the FastAPI lifespan and +reuse the same pipeline components as ``scripts/collect_daily_data.py``. +""" + +from __future__ import annotations + +import logging +from datetime import date, datetime, timedelta, timezone +from typing import Any + +import pandas as pd + +from data_sources.station_scraper import StationScraper +from data_sources.weather_api import WeatherCollector +from pipeline.build_dataset import DatasetBuilder +from pipeline.feature_engineering import FeatureEngineer +from predictor.hybrid_predictor import HybridPredictor +from scripts.collect_daily_data import ( + _load_prediction_feature_base, + _select_feature_anchor_row, +) +from scripts.retrain_model import main as retrain_main +from storage import ( + LATEST_WEATHER_TABLE, + RUNTIME_DATASET_TABLE, + RUNTIME_FEATURED_TABLE, + SQLiteStore, +) + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Forecast cycle +# --------------------------------------------------------------------------- + + +def run_forecast_cycle(run_hour: int) -> None: + """Execute a full forecast cycle for a given run hour. + + Steps: + 1. Archive current forecasts into past_forecasts. + 2. Fetch weather forecasts via Open-Meteo. + 3. Scrape current station status. + 4. Append to runtime dataset + feature engineering. + 5. Generate predictions for each station x each forecast day. + 6. Save results to current_forecasts. + 7. At hour 20, scrape today's actual data into historical_actuals. + """ + logger.info("=== Forecast cycle started (run_hour=%d) ===", run_hour) + store = SQLiteStore() + + # 1. Archive previous forecasts + store.archive_current_forecasts() + + # 2. Collect weather + weather_collector = WeatherCollector() + weather_by_station: dict[str, pd.DataFrame] = {} + for station_id, cfg in weather_collector.stations.items(): + try: + df = weather_collector.get_forecast( + station_id, cfg["latitude"], cfg["longitude"] + ) + weather_by_station[station_id] = df + logger.info("Weather OK: %s (%d rows)", station_id, len(df)) + except Exception as exc: + logger.error("Weather failed for %s: %s", station_id, exc) + + if not weather_by_station: + logger.error("No weather data collected. Aborting forecast cycle.") + return + + # 3. Scrape station status + scraper = StationScraper() + station_records: list[dict[str, Any]] = [] + for station_id in scraper._stations: + try: + record = scraper.scrape_station(station_id) + station_records.append(record) + except Exception as exc: + logger.error("Scraping failed for %s: %s", station_id, exc) + + # 4. Dataset append + feature engineering + builder = DatasetBuilder(store=store) + engineer = FeatureEngineer() + station_map = {r["station_id"]: r for r in station_records} + today = pd.Timestamp(date.today()) + + for station_id, weather_df in weather_by_station.items(): + station_rec = station_map.get(station_id) + if station_rec is None: + continue + today_rows = weather_df[pd.to_datetime(weather_df["date"]) == today] + if today_rows.empty: + today_rows = weather_df.head(1) + try: + builder.append_daily( + weather_data=today_rows.iloc[0].to_dict(), + station_data=station_rec, + ) + except Exception as exc: + logger.error("Dataset append failed for %s: %s", station_id, exc) + + # Save weather snapshot + if weather_by_station: + snapshot = pd.concat(weather_by_station.values(), ignore_index=True) + store.save_weather_snapshot(snapshot, table_name=LATEST_WEATHER_TABLE) + + runtime_df = store.read_dataframe(RUNTIME_DATASET_TABLE, parse_dates=("date",)) + featured_df = pd.DataFrame() + if not runtime_df.empty: + featured_df = engineer.transform(runtime_df) + store.replace_dataframe(RUNTIME_FEATURED_TABLE, featured_df) + + # 5. Determine forecast dates + base_date = date.today() + if run_hour >= 15: + # Skip today, start from tomorrow + forecast_dates = [base_date + timedelta(days=d) for d in range(1, 8)] + else: + # Include today + forecast_dates = [base_date + timedelta(days=d) for d in range(8)] + + # 6. Generate predictions + predictor = HybridPredictor() + feature_base_df = _load_prediction_feature_base(store, featured_df) + all_forecasts: list[dict[str, Any]] = [] + + for station_id, weather_df in weather_by_station.items(): + station_rec = station_map.get(station_id, {}) + for target_date in forecast_dates: + days_ahead = (target_date - base_date).days + target_rows = weather_df[weather_df["date"] == target_date] + if target_rows.empty: + idx = max(0, min(days_ahead, len(weather_df) - 1)) + target_rows = weather_df.iloc[idx : idx + 1] + if target_rows.empty: + continue + + weather_data = target_rows.iloc[0].to_dict() + + # Build feature row + features_df = None + if not feature_base_df.empty: + anchor = _select_feature_anchor_row( + feature_base_df, station_id, target_date + ) + if anchor is not None: + features_df = anchor.copy() + features_df["date"] = pd.Timestamp(target_date) + for col in weather_data: + if col in features_df.columns and col not in ( + "date", + "station_id", + ): + features_df[col] = weather_data[col] + if station_rec.get("snow_depth") is not None: + features_df["snow_depth"] = station_rec["snow_depth"] + if station_rec.get("lifts_open") is not None: + features_df["lifts_open"] = station_rec["lifts_open"] + + if station_rec.get("snow_depth") is not None: + weather_data["snow_depth"] = station_rec["snow_depth"] + + try: + result = predictor.predict(station_id, weather_data, features_df) + all_forecasts.append( + { + "station_id": station_id, + "prediction_date": target_date.isoformat(), + "open_probability": result["open_probability"], + "km_open": result["km_open"], + "crowd_level": result["crowd_level"], + "weather_summary": result.get("weather_summary"), + "rule_notes": result.get("rule_overrides", []), + "prediction_source": result["prediction_source"], + } + ) + except Exception as exc: + logger.error( + "Prediction failed for %s on %s: %s", + station_id, + target_date.isoformat(), + exc, + ) + + # 7. Save to current_forecasts + if all_forecasts: + store.save_current_forecasts(all_forecasts, run_hour) + + # Also save as a published prediction run for the bot's existing flow + # (one run per distinct target date, same as collect_daily_data.py) + _save_as_prediction_runs(store, all_forecasts, run_hour) + + # 8. At hour 20: scrape today's actual data + if run_hour == 20: + _scrape_daily_actuals(store, scraper) + + logger.info( + "=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===", + run_hour, + len(all_forecasts), + ) + + +def _save_as_prediction_runs( + store: SQLiteStore, + forecasts: list[dict[str, Any]], + run_hour: int, +) -> None: + """Persist forecasts as published prediction_runs for bot compatibility.""" + by_date: dict[str, dict[str, Any]] = {} + for f in forecasts: + by_date.setdefault(f["prediction_date"], {})[f["station_id"]] = { + "station_name": f["station_id"], + "open_probability": f["open_probability"], + "km_open": f["km_open"], + "crowd_level": f["crowd_level"], + "weather_summary": f.get("weather_summary"), + "rule_overrides": f.get("rule_notes", []), + "prediction_source": f["prediction_source"], + } + + for pred_date, stations in by_date.items(): + payload = { + "generated_at": datetime.now(timezone.utc).isoformat(), + "prediction_date": pred_date, + "stations": stations, + } + store.save_prediction_run(payload, run_kind="published") + + +def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None: + """Scrape today's actual station data and save to historical_actuals.""" + logger.info("Scraping today's actual station data.") + today_iso = date.today().isoformat() + records: list[dict[str, Any]] = [] + + for station_id in scraper._stations: + try: + data = scraper.scrape_station(station_id) + records.append( + { + "date": today_iso, + "station_id": station_id, + "open_status": int(data["open_status"]) if data.get("open_status") is not None else None, + "km_open": data.get("km_open"), + "lifts_open": data.get("lifts_open"), + "snow_depth": data.get("snow_depth"), + } + ) + except Exception as exc: + logger.error("Actual scrape failed for %s: %s", station_id, exc) + + if records: + store.save_historical_actual(records) + + +# --------------------------------------------------------------------------- +# Retrain +# --------------------------------------------------------------------------- + + +def run_retrain() -> None: + """Run the full model retraining pipeline.""" + logger.info("=== Model retraining triggered by scheduler ===") + try: + exit_code = retrain_main() + if exit_code != 0: + logger.error("Retraining finished with exit code %d.", exit_code) + else: + logger.info("=== Model retraining completed successfully ===") + except Exception as exc: + logger.error("Retraining failed: %s", exc, exc_info=True) diff --git a/requirements.txt b/requirements.txt index 7ebedf3..d5b10a3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,3 +11,9 @@ schedule>=1.2.0 joblib>=1.3.0 ultralytics>=8.0.0 opencv-python-headless>=4.8.0 +fastapi>=0.115.0 +uvicorn[standard]>=0.30.0 +apscheduler>=3.10.0 +PyJWT>=2.8.0 +passlib[bcrypt]>=1.7.4 +python-multipart>=0.0.9 diff --git a/start.sh b/start.sh index 568a19d..3a759f2 100755 --- a/start.sh +++ b/start.sh @@ -97,7 +97,7 @@ if [ "$DO_COLLECT" = true ]; then fi # --------------------------------------------------------------- -# 6. Start Telegram bot +# 6. Start FastAPI backend (includes scheduler + bot subprocess) # --------------------------------------------------------------- if [ "$DO_BOT" = true ]; then if [ -z "${TELEGRAM_BOT_TOKEN:-}" ]; then @@ -106,19 +106,20 @@ if [ "$DO_BOT" = true ]; then exit 1 fi - # Kill existing bot process if running - if pgrep -f "bot/telegram_bot.py|bot\\.telegram_bot" > /dev/null 2>&1; then - warn "Killing existing bot process..." - pkill -f "bot/telegram_bot.py|bot\\.telegram_bot" || true + # Kill existing processes if running + if pgrep -f "uvicorn app.main:app|bot/telegram_bot.py|bot\\.telegram_bot" > /dev/null 2>&1; then + warn "Killing existing processes..." + pkill -f "uvicorn app.main:app|bot/telegram_bot.py|bot\\.telegram_bot" || true sleep 1 fi - info "Starting Telegram bot..." + info "Starting FastAPI backend (scheduler + Telegram bot)..." : > "$DATA_DIR/bot.log" - nohup env PYTHONPATH="$SCRIPT_DIR" "$PYTHON" -m bot.telegram_bot \ + nohup env PYTHONPATH="$SCRIPT_DIR" "$VENV/bin/uvicorn" app.main:app \ + --host 0.0.0.0 --port 8000 \ > "$DATA_DIR/bot.log" 2>&1 & - BOT_PID=$! - info "Bot started (PID: $BOT_PID). Logs: $DATA_DIR/bot.log" + SERVER_PID=$! + info "Backend started (PID: $SERVER_PID). Logs: $DATA_DIR/bot.log" fi # --------------------------------------------------------------- @@ -133,7 +134,8 @@ if [ "$DO_CRON" = true ]; then echo " Cron: Daily at 22:00" fi if [ "$DO_BOT" = true ]; then - echo " Bot PID: $BOT_PID" + echo " Server PID: $SERVER_PID" + echo " API: http://0.0.0.0:8000/api/v1" fi echo "" info "Done." diff --git a/storage/__init__.py b/storage/__init__.py index 21d8c98..5a70a22 100644 --- a/storage/__init__.py +++ b/storage/__init__.py @@ -3,15 +3,18 @@ from storage.sqlite_store import ( AD_HOC_RUN_KIND, CROWD_ANALYSIS_TABLE, + CURRENT_FORECASTS_TABLE, DEFAULT_DB_PATH, EVALUATION_RUNS_TABLE, FEATURE_IMPORTANCE_TABLE, + HISTORICAL_ACTUALS_TABLE, HISTORICAL_FEATURED_TABLE, HISTORICAL_MERGED_TABLE, HISTORICAL_STATION_TABLE, HISTORICAL_WEATHER_TABLE, LATEST_STATION_STATUS_TABLE, LATEST_WEATHER_TABLE, + PAST_FORECASTS_TABLE, PUBLISHED_RUN_KIND, RUNTIME_DATASET_TABLE, RUNTIME_FEATURED_TABLE, @@ -21,15 +24,18 @@ from storage.sqlite_store import ( __all__ = [ "AD_HOC_RUN_KIND", "CROWD_ANALYSIS_TABLE", + "CURRENT_FORECASTS_TABLE", "DEFAULT_DB_PATH", "EVALUATION_RUNS_TABLE", "FEATURE_IMPORTANCE_TABLE", + "HISTORICAL_ACTUALS_TABLE", "HISTORICAL_FEATURED_TABLE", "HISTORICAL_MERGED_TABLE", "HISTORICAL_STATION_TABLE", "HISTORICAL_WEATHER_TABLE", "LATEST_STATION_STATUS_TABLE", "LATEST_WEATHER_TABLE", + "PAST_FORECASTS_TABLE", "PUBLISHED_RUN_KIND", "RUNTIME_DATASET_TABLE", "RUNTIME_FEATURED_TABLE", diff --git a/storage/sqlite_store.py b/storage/sqlite_store.py index 2364893..276e169 100644 --- a/storage/sqlite_store.py +++ b/storage/sqlite_store.py @@ -47,6 +47,9 @@ RUNTIME_FEATURED_TABLE = "runtime_featured_dataset" CROWD_ANALYSIS_TABLE = "crowd_analysis" FEATURE_IMPORTANCE_TABLE = "feature_importances" EVALUATION_RUNS_TABLE = "evaluation_runs" +CURRENT_FORECASTS_TABLE = "current_forecasts" +PAST_FORECASTS_TABLE = "past_forecasts" +HISTORICAL_ACTUALS_TABLE = "historical_actuals" PUBLISHED_RUN_KIND = "published" AD_HOC_RUN_KIND = "adhoc" @@ -500,6 +503,186 @@ class SQLiteStore: ) return df.drop(columns=["confidence_scores_json"]) + # ------------------------------------------------------------------ + # Current / Past forecasts (API-oriented) + # ------------------------------------------------------------------ + + def save_current_forecasts( + self, + forecasts: list[dict[str, Any]], + run_hour: int, + ) -> None: + """Clear current_forecasts and insert new rows.""" + generated_at = self._now_iso() + with self.connect() as conn: + conn.execute(f"DELETE FROM {CURRENT_FORECASTS_TABLE}") + conn.executemany( + f""" + INSERT INTO {CURRENT_FORECASTS_TABLE} ( + generated_at, run_hour, station_id, prediction_date, + open_probability, km_open, crowd_level, + weather_summary, rule_notes_json, prediction_source + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + [ + ( + generated_at, + run_hour, + f["station_id"], + f["prediction_date"], + self._coerce_float(f.get("open_probability")), + self._coerce_float(f.get("km_open")), + f.get("crowd_level"), + f.get("weather_summary"), + json.dumps(f.get("rule_notes") or [], ensure_ascii=False), + f.get("prediction_source"), + ) + for f in forecasts + ], + ) + logger.info( + "Saved %d current forecasts (run_hour=%d).", len(forecasts), run_hour + ) + + def archive_current_forecasts(self) -> int: + """Move all current_forecasts rows into past_forecasts. Return count.""" + with self.connect() as conn: + cursor = conn.execute( + f""" + INSERT INTO {PAST_FORECASTS_TABLE} ( + generated_at, run_hour, station_id, prediction_date, + open_probability, km_open, crowd_level, + weather_summary, rule_notes_json, prediction_source + ) + SELECT + generated_at, run_hour, station_id, prediction_date, + open_probability, km_open, crowd_level, + weather_summary, rule_notes_json, prediction_source + FROM {CURRENT_FORECASTS_TABLE} + """ + ) + archived = cursor.rowcount + conn.execute(f"DELETE FROM {CURRENT_FORECASTS_TABLE}") + if archived: + logger.info("Archived %d forecast rows to past_forecasts.", archived) + return archived + + def load_current_forecasts( + self, + station_id: str | None = None, + ) -> list[dict[str, Any]]: + """Return current forecast rows, optionally filtered by station.""" + query = f"SELECT * FROM {CURRENT_FORECASTS_TABLE}" + params: list[str] = [] + if station_id is not None: + query += " WHERE station_id = ?" + params.append(station_id) + query += " ORDER BY station_id, prediction_date" + + with self.connect() as conn: + rows = conn.execute(query, params).fetchall() + return [dict(row) for row in rows] + + def load_past_forecasts( + self, + station_id: str | None = None, + date_from: str | None = None, + date_to: str | None = None, + limit: int = 50, + offset: int = 0, + ) -> list[dict[str, Any]]: + """Return past forecast rows with optional filters and pagination.""" + clauses: list[str] = [] + params: list[Any] = [] + + if station_id is not None: + clauses.append("station_id = ?") + params.append(station_id) + if date_from is not None: + clauses.append("prediction_date >= ?") + params.append(date_from) + if date_to is not None: + clauses.append("prediction_date <= ?") + params.append(date_to) + + where = "" + if clauses: + where = "WHERE " + " AND ".join(clauses) + + query = f""" + SELECT * FROM {PAST_FORECASTS_TABLE} + {where} + ORDER BY generated_at DESC, id DESC + LIMIT ? OFFSET ? + """ + params.extend([limit, offset]) + + with self.connect() as conn: + rows = conn.execute(query, params).fetchall() + return [dict(row) for row in rows] + + def count_past_forecasts( + self, + station_id: str | None = None, + date_from: str | None = None, + date_to: str | None = None, + ) -> int: + """Return total count of past forecast rows matching filters.""" + clauses: list[str] = [] + params: list[Any] = [] + + if station_id is not None: + clauses.append("station_id = ?") + params.append(station_id) + if date_from is not None: + clauses.append("prediction_date >= ?") + params.append(date_from) + if date_to is not None: + clauses.append("prediction_date <= ?") + params.append(date_to) + + where = "" + if clauses: + where = "WHERE " + " AND ".join(clauses) + + query = f"SELECT COUNT(*) FROM {PAST_FORECASTS_TABLE} {where}" + + with self.connect() as conn: + row = conn.execute(query, params).fetchone() + return int(row[0]) + + def save_historical_actual(self, records: Sequence[dict[str, Any]]) -> None: + """Upsert actual station data scraped at end of day.""" + scraped_at = self._now_iso() + with self.connect() as conn: + for rec in records: + conn.execute( + f""" + INSERT INTO {HISTORICAL_ACTUALS_TABLE} ( + date, station_id, open_status, km_open, + lifts_open, snow_depth, scraped_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(date, station_id) DO UPDATE SET + open_status = excluded.open_status, + km_open = excluded.km_open, + lifts_open = excluded.lifts_open, + snow_depth = excluded.snow_depth, + scraped_at = excluded.scraped_at + """, + ( + rec["date"], + rec["station_id"], + rec.get("open_status"), + self._coerce_float(rec.get("km_open")), + rec.get("lifts_open"), + self._coerce_float(rec.get("snow_depth")), + scraped_at, + ), + ) + logger.info("Saved %d historical actual records.", len(records)) + # ------------------------------------------------------------------ # Generic DataFrame helpers # ------------------------------------------------------------------ @@ -604,6 +787,54 @@ class SQLiteStore: crowd_density TEXT NOT NULL, confidence_scores_json TEXT NOT NULL ); + + CREATE TABLE IF NOT EXISTS current_forecasts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + generated_at TEXT NOT NULL, + run_hour INTEGER NOT NULL, + station_id TEXT NOT NULL, + prediction_date TEXT NOT NULL, + open_probability REAL, + km_open REAL, + crowd_level TEXT, + weather_summary TEXT, + rule_notes_json TEXT, + prediction_source TEXT + ); + + CREATE TABLE IF NOT EXISTS past_forecasts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + generated_at TEXT NOT NULL, + run_hour INTEGER NOT NULL, + station_id TEXT NOT NULL, + prediction_date TEXT NOT NULL, + open_probability REAL, + km_open REAL, + crowd_level TEXT, + weather_summary TEXT, + rule_notes_json TEXT, + prediction_source TEXT + ); + + CREATE TABLE IF NOT EXISTS historical_actuals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + station_id TEXT NOT NULL, + open_status INTEGER, + km_open REAL, + lifts_open INTEGER, + snow_depth REAL, + scraped_at TEXT NOT NULL, + UNIQUE(date, station_id) + ); + + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + last_login_at TEXT + ); """ ) diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..7bd1e78 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,113 @@ +"""Integration tests for JWT authentication.""" + +from __future__ import annotations + +import os + +import pytest +from fastapi.testclient import TestClient + +# Ensure JWT_SECRET_KEY is set before importing the app +os.environ.setdefault("JWT_SECRET_KEY", "test-secret-key-for-testing-only") + +from app.main import app # noqa: E402 + +client = TestClient(app, raise_server_exceptions=False) + +_TEST_EMAIL = "test@example.com" +_TEST_PASSWORD = "securepassword123" + + +@pytest.fixture(autouse=True) +def _fresh_db(tmp_path, monkeypatch): + """Use a temporary database for every test.""" + monkeypatch.setenv("SKIPREDICTOR_DB_PATH", str(tmp_path / "test.db")) + # Force re-import to pick up new path + from storage import sqlite_store + + sqlite_store.DEFAULT_DB_PATH = tmp_path / "test.db" + + +def _register(email: str = _TEST_EMAIL, password: str = _TEST_PASSWORD): + return client.post( + "/api/v1/auth/register", + json={"email": email, "password": password}, + ) + + +def _login(email: str = _TEST_EMAIL, password: str = _TEST_PASSWORD): + return client.post( + "/api/v1/auth/login", + data={"username": email, "password": password}, + ) + + +def _auth_header(token: str) -> dict: + return {"Authorization": f"Bearer {token}"} + + +# -- Tests ------------------------------------------------------------------ + + +def test_register_and_login(): + """Register a user, then login to get a token.""" + resp = _register() + assert resp.status_code == 201 + data = resp.json() + assert data["email"] == _TEST_EMAIL + assert "id" in data + + resp = _login() + assert resp.status_code == 200 + data = resp.json() + assert "access_token" in data + assert data["token_type"] == "bearer" + + +def test_duplicate_email_returns_409(): + """Registering the same email twice returns 409.""" + _register() + resp = _register() + assert resp.status_code == 409 + + +def test_protected_endpoint_without_token_returns_401(): + """Accessing a protected endpoint without a token returns 401.""" + resp = client.get("/api/v1/stations") + assert resp.status_code == 401 + + +def test_protected_endpoint_with_valid_token(): + """Accessing a protected endpoint with a valid token succeeds.""" + _register() + token = _login().json()["access_token"] + resp = client.get("/api/v1/stations", headers=_auth_header(token)) + assert resp.status_code == 200 + + +def test_health_stays_public(): + """/health does not require authentication.""" + resp = client.get("/api/v1/health") + assert resp.status_code == 200 + + +def test_invalid_token_returns_401(): + """A malformed token returns 401.""" + resp = client.get( + "/api/v1/stations", + headers=_auth_header("not.a.valid.token"), + ) + assert resp.status_code == 401 + + +def test_wrong_password_returns_401(): + """Login with wrong password returns 401.""" + _register() + resp = _login(password="wrongpassword1") + assert resp.status_code == 401 + + +def test_login_nonexistent_user_returns_401(): + """Login with an email that doesn't exist returns 401.""" + resp = _login(email="nobody@example.com") + assert resp.status_code == 401