"""Request validation for the chart API. Symbol, date and alert-payload rules live here instead of in the router. They raise HTTP 4xx directly because they are the boundary for these rules; the router only calls them. The symbol rule is deliberately strict: a symbol is interpolated into a cache filename and used as an upstream query key, so a value carrying `/` or `..` is a bad request, not a symbol to look up. """ import re from datetime import datetime as dt from fastapi import HTTPException from core.domain.schemas import ChartAlertIn from core.ohlc import OPTION_TIMEFRAMES from core.shared.ny_time import NY _VALID_SYMBOL_RE = re.compile(r"^[A-Z0-9][A-Z0-9.^-]{0,19}$") def clean_symbol(symbol: str) -> str: """Uppercase/strip a symbol and reject one that is not a plain ticker.""" clean = (symbol or "").strip().upper() if not clean: raise HTTPException(status_code=400, detail="symbol is required") if not _VALID_SYMBOL_RE.match(clean): raise HTTPException( status_code=400, detail="symbol must be a ticker of letters, digits, '.', '-' or '^'", ) return clean def validate_symbol_date_timeframe(symbol: str, date: str | None, timeframe: str) -> tuple[str, str]: """Normalize symbol/date/timeframe; raise the same 400s both overlays use.""" symbol = clean_symbol(symbol) if timeframe not in OPTION_TIMEFRAMES: raise HTTPException( status_code=400, detail=f"timeframe must be one of {sorted(OPTION_TIMEFRAMES)}", ) if date is None: date = dt.now(NY).date().isoformat() try: dt.strptime(date, "%Y-%m-%d") except ValueError: raise HTTPException(status_code=400, detail="date must be YYYY-MM-DD") from None return symbol, date def sanitize_alert(alert: ChartAlertIn) -> ChartAlertIn: """Normalize symbol casing and reject blank ids.""" alert.symbol = alert.symbol.strip().upper() alert.id = alert.id.strip() if not alert.id: raise HTTPException(status_code=422, detail="alert id must not be blank") if not alert.symbol: raise HTTPException(status_code=422, detail="alert symbol must not be blank") return alert