"""HTTP skin for `travelodge` and `rowing`. Caddy strips /py, so routes are relative to "/" and --root-path keeps /py/docs working. Field names in the hotel models are a contract with vue/src/views/hotels/. /internal/ routes are for the Go backend only. """ import json import re import threading from datetime import date, datetime, timedelta, timezone from typing import Literal, Optional from zoneinfo import ZoneInfo from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field, field_validator, model_validator from . import claude, rowing, travelodge app = FastAPI( title="Python API", version="0.6.0", docs_url="/docs", openapi_url="/openapi.json", ) class Health(BaseModel): """Liveness payload: a fixed status string and the server's UTC time.""" status: str time: datetime class Greeting(BaseModel): """A single human-readable message.""" message: str @app.get("/", response_model=Greeting, summary="Service index") def index() -> Greeting: """Point a curious caller at the docs (which live at /py/docs via Caddy).""" return Greeting(message="Python API is running. See /py/docs for the schema.") @app.get("/health", response_model=Health, summary="Liveness check") def health() -> Health: """Liveness check; always 200 while the process is up.""" return Health(status="ok", time=datetime.now(timezone.utc)) @app.get("/hello/{name}", response_model=Greeting, summary="Greet a caller") def hello(name: str) -> Greeting: """Echo a greeting back. Demo route, nothing depends on it.""" return Greeting(message=f"Hello, {name}!") # --------------------------------------------------------------------------- # # Cheap Travelodge finder # --------------------------------------------------------------------------- # MAX_ROOMS = 4 MAX_ADULTS = 8 MAX_CHILDREN = 8 MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS CACHE_TTL_S = 10 * 60 CACHE_MAX = 200 # Dates are London dates, whatever the server's timezone. LONDON_TZ = ZoneInfo("Europe/London") def london_today() -> date: """Today's date in London, the reference for "today or later" validation.""" return datetime.now(LONDON_TZ).date() # One run at a time: a run can use the whole anonymous TfL budget. Others get # an immediate "try again". _search_slot = threading.Semaphore(1) # Bounded because one response holds every row of a scan. _cache = travelodge.TTLCache(CACHE_TTL_S, max_entries=CACHE_MAX) class Origin(BaseModel): """One selectable travel origin, as offered to the UI's dropdown.""" key: str name: str lat: float lon: float class HotelRequestBase(BaseModel): """Fields shared by the single-stay search and the date-range scan.""" location: str = Field("Central London", min_length=1, max_length=80, description="Travelodge search text") guests: str = Field("1", max_length=40, description='Rooms/guests e.g. "1", "2+1", "2,2+2"') railcard_holders: int = Field(1, ge=0, le=MAX_ADULTS, description="Adults with a Railcard (1/3 off off-peak rail)") origin: str = Field("clapham junction", max_length=60, description="Known station key or 'lat,lon'") depart: str = Field("19:30", description="Outbound departure time HH:MM") max_miles: Optional[float] = Field(None, gt=0, le=50, description="Drop hotels further than this from the search") max_travel_min: int = Field(75, ge=10, le=240, description="Ignore slower routes than this when picking cheapest") @field_validator("location") @classmethod def _strip_location(cls, v: str) -> str: v = v.strip() if not v: raise ValueError("location cannot be empty") return v @field_validator("depart") @classmethod def _check_depart(cls, v: str) -> str: if not re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", v.strip()): raise ValueError("depart must be HH:MM") return v.strip() @field_validator("guests") @classmethod def _check_guests(cls, v: str) -> str: try: rooms = travelodge.parse_guests(v) except ValueError as e: raise ValueError(f"invalid guests spec: {e}") from None if len(rooms) > MAX_ROOMS: raise ValueError(f"at most {MAX_ROOMS} rooms") if sum(a for a, _ in rooms) > MAX_ADULTS: raise ValueError(f"at most {MAX_ADULTS} adults") if sum(c for _, c in rooms) > MAX_CHILDREN: raise ValueError(f"at most {MAX_CHILDREN} children") return v.strip() @field_validator("origin") @classmethod def _check_origin(cls, v: str) -> str: travelodge.parse_origin(v) # raises ValueError with a useful message return v.strip() def shared_kwargs(self) -> dict: """Translate the validated request into travelodge.run_* keyword args. Parsing runs a second time here (the validators above only checked validity and discarded the result), which is cheap and keeps the model holding exactly what the client sent. """ origin_name, origin = travelodge.parse_origin(self.origin) return { "location": self.location, "rooms": travelodge.parse_guests(self.guests), "railcard_holders": self.railcard_holders, "origin_name": origin_name, "origin": origin, "depart": self.depart, "max_miles": self.max_miles, "max_travel_min": self.max_travel_min, } class HotelSearchRequest(HotelRequestBase): """One stay on known dates: rank hotels by room price plus transport.""" checkin: date = Field(..., description="Check-in date (today or later)") checkout: Optional[date] = Field(None, description="Check-out date; overrides nights") nights: int = Field(1, ge=1, le=14, description="Used when checkout is not given") top: int = Field(20, ge=1, le=40, description="Price transport for the N cheapest stays only") @model_validator(mode="after") def _check_dates(self): """Resolve checkout/nights into a consistent pair and bound the stay. `checkout` wins when both are given; otherwise it is derived from `nights`. Both fields are then written back so downstream code can trust either one. "Today" is London's date (see :func:`london_today`), not the server's, so the answer does not depend on the container's timezone. """ if self.checkin < london_today(): raise ValueError("checkin must be today or later") checkout = self.checkout or self.checkin + timedelta(days=self.nights) if checkout <= self.checkin: raise ValueError("checkout must be after checkin") if (checkout - self.checkin).days > 14: raise ValueError("stays are limited to 14 nights") self.checkout = checkout self.nights = (checkout - self.checkin).days return self class HotelScanRequest(HotelRequestBase): """A range of candidate check-in dates: find the cheapest night to stay.""" start: date = Field(..., description="First candidate check-in date (today or later)") end: date = Field(..., description=f"Last candidate check-in date, at most {MAX_SCAN_DAYS} days after start") weekdays: list[int] = Field( default_factory=lambda: list(range(7)), description="Check-in weekdays to consider, 0=Mon .. 6=Sun (default all)", ) nights: int = Field(1, ge=1, le=7, description="Length of each candidate stay") per_night: int = Field(5, ge=1, le=10, description="Keep the N cheapest hotels for each night") @field_validator("weekdays") @classmethod def _check_weekdays(cls, v: list[int]) -> list[int]: """Validate and de-duplicate the weekday filter, preserving input order. Order is preserved (rather than using a set) so the echoed summary and the cache key stay deterministic for a given request body. """ days = [] for d in v: if d < 0 or d > 6: raise ValueError("weekdays must be 0 (Mon) to 6 (Sun)") if d not in days: days.append(d) if not days: raise ValueError("pick at least one weekday") return days @model_validator(mode="after") def _check_dates(self): """Bound the range and reject one that no candidate date can satisfy. The final check actually enumerates the candidates, so a range like "Mondays only" over a Tuesday-to-Thursday window fails here with a clear message instead of producing an empty scan. """ if self.start < london_today(): # London's date, see london_today() raise ValueError("start must be today or later") if self.end < self.start: raise ValueError("end must be on or after start") if (self.end - self.start).days > MAX_SCAN_DAYS: raise ValueError(f"scans are limited to {MAX_SCAN_DAYS} days") if not travelodge.candidate_checkins(self.start, self.end, set(self.weekdays), self.nights): raise ValueError("no dates in the range match those weekdays") return self class HotelRow(BaseModel): """One hotel in a result list. Prices are pounds. Transport fields are None until the matching "transport" event arrives, and `route` carries the reason when they stay None ("pricing…", "no TfL fare found", "not priced (time limit)"). Field names are consumed verbatim by the Vue frontend - do not rename. """ code: Optional[str] = None name: Optional[str] = None lat: Optional[float] = None lon: Optional[float] = None room_price: Optional[float] = None room_code: Optional[str] = None available: bool = True low_availability: bool = False distance_from_search_mi: Optional[float] = None rating: Optional[float] = None url: str transport_out: Optional[float] = None transport_return: Optional[float] = None transport_total: Optional[float] = None travel_minutes: Optional[int] = None route: str fastest_minutes: Optional[int] = None fastest_total: Optional[float] = None fastest_route: Optional[str] = None total: Optional[float] = None cycle_minutes: Optional[int] = None cycle_km: Optional[float] = None cycle_source: str = "estimate" class HotelSearchSummary(BaseModel): """Counts and echoed parameters for a search; `truncated` means the time budget ran out before every shortlisted hotel was priced.""" location: str checkin: date checkout: date nights: int rooms: int adults: int children: int railcard_holders: int origin_name: str origin_lat: float origin_lon: float depart: datetime max_travel_min: int hotels_found: int hotels_available: int hotels_priced: int hotels_shortlisted: int = 0 tfl_rate_per_min: int = 0 truncated: bool = False class HotelSearchResponse(BaseModel): """Final result of the blocking search endpoint.""" summary: HotelSearchSummary rows: list[HotelRow] cached: bool = False @app.get("/hotels/origins", response_model=list[Origin], summary="Known origin stations") def hotel_origins() -> list[Origin]: """List the built-in origin stations the UI offers (plus free "lat,lon").""" return [Origin(key=k, name=n, lat=lat, lon=lon) for k, (n, lat, lon) in travelodge.ORIGINS.items()] class HotelSearchEvent(BaseModel): """One line of the NDJSON stream from /hotels/search/stream.""" event: str = Field(..., description='"hotels", "transport", "done" or "error"') summary: Optional[HotelSearchSummary] = None rows: Optional[list[HotelRow]] = None row: Optional[HotelRow] = None cached: bool = False detail: Optional[str] = None class TransportFields(BaseModel): """Transport and cycling columns for one hotel, independent of the night.""" code: str transport_out: Optional[float] = None transport_return: Optional[float] = None transport_total: Optional[float] = None travel_minutes: Optional[int] = None route: str fastest_minutes: Optional[int] = None fastest_total: Optional[float] = None fastest_route: Optional[str] = None cycle_minutes: Optional[int] = None cycle_km: Optional[float] = None cycle_source: str = "estimate" class NightRow(BaseModel): """One candidate night in a scan, with its cheapest hotels.""" checkin: date checkout: date status: str = Field("pending", description='"pending", "ok", "failed" or "skipped"') detail: Optional[str] = Field(None, description="Why a night failed or was skipped") hotels_available: int = 0 hotels: list[HotelRow] = Field(default_factory=list, description="Cheapest per_night hotels for this night") best_total: Optional[float] = None best_room: Optional[float] = None best_code: Optional[str] = None class HotelScanSummary(BaseModel): """Counts and echoed parameters for a scan; `truncated` means some nights were skipped or some hotels left unpriced when time ran out.""" location: str start: date end: date weekdays: list[int] nights: int per_night: int rooms: int adults: int children: int railcard_holders: int origin_name: str origin_lat: float origin_lon: float depart: datetime max_travel_min: int nights_candidate: int nights_fetched: int = 0 nights_failed: int = 0 nights_skipped: int = 0 hotels_unique: int = 0 hotels_priced: int = 0 tfl_rate_per_min: int = 0 truncated: bool = False class HotelScanEvent(BaseModel): """One line of the NDJSON stream from /hotels/scan/stream.""" event: str = Field(..., description='"scan", "night", "transport", "done" or "error"') summary: Optional[HotelScanSummary] = None nights: Optional[list[NightRow]] = None night: Optional[NightRow] = None transport: Optional[TransportFields] = None cached: bool = False detail: Optional[str] = None ALREADY_RUNNING = "A search is already running, try again in a minute." def _guarded(run, make_error): """Run a live search generator while holding the single search slot. Upstream failures are reported as a final "error" event rather than raised, so a stream that has already started can still tell the client what went wrong. """ if not _search_slot.acquire(blocking=False): yield make_error(ALREADY_RUNNING) return try: yield from run() except travelodge.UpstreamError as e: yield make_error(str(e)) except (KeyError, TypeError) as e: yield make_error(f"Unexpected upstream response: {e}") except ValueError as e: yield make_error(str(e)) finally: _search_slot.release() def _run_events(*, req, prefix, model, make_gen, first_event, list_key, row_keys): """Shared body of the two streaming endpoints, differing only in their types. Searches and scans have the same shape: build a cache key from the request, replay a finished result as two lines if it is cached, otherwise run the travelodge generator under the single-search guard and wrap each upstream event in a Pydantic event model. Args: req: the validated request; its canonical JSON is the cache key, which makes the key exact but also means a cosmetically different body (a different `top`, say) misses. prefix: cache-key namespace ("search:"/"scan:") so the two endpoints cannot collide. model: the event model to emit (HotelSearchEvent or HotelScanEvent). make_gen: zero-argument callable returning the travelodge generator. Called inside the guard so that anything it raises while binding its arguments becomes an "error" event rather than a 500. first_event: name of the opening list event ("hotels"/"scan"). A cache hit replays it followed by "done", both carrying the finished result, so the client's streaming reader needs no special case and the `cached` flag is the only difference it can observe. list_key: model field holding the whole list ("rows"/"nights"); only the final "done" event is worth caching. row_keys: kind -> model field for the per-item events, e.g. {"transport": "row"} for a search. Upstream events are 3-tuples of (kind, summary, payload) except run_search's "transport", which is a 2-tuple of (kind, row); that one is normalised to a None summary here, and `exclude_none=True` at serialisation time drops the key exactly as before. """ key = prefix + json.dumps(req.model_dump(mode="json"), sort_keys=True) hit = _cache.get(key) if hit: yield model(event=first_event, cached=True, **hit) yield model(event="done", cached=True, **hit) return def run(): for ev in make_gen(): kind, summary, payload = (ev[0], None, ev[1]) if len(ev) == 2 else ev if kind in row_keys: yield model(event=kind, summary=summary, **{row_keys[kind]: payload}) else: if kind == "done": _cache.set(key, {"summary": summary, list_key: payload}) yield model(event=kind, summary=summary, **{list_key: payload}) yield from _guarded(run, lambda detail: model(event="error", detail=detail)) def _search_events(req: HotelSearchRequest): """Yield HotelSearchEvent objects for a request, serving from cache when possible.""" return _run_events( req=req, prefix="search:", model=HotelSearchEvent, make_gen=lambda: travelodge.run_search( checkin=req.checkin, checkout=req.checkout, top=req.top, **req.shared_kwargs(), ), first_event="hotels", list_key="rows", row_keys={"transport": "row"}, ) def _scan_events(req: HotelScanRequest): """Yield HotelScanEvent objects for a scan, serving from cache when possible.""" return _run_events( req=req, prefix="scan:", model=HotelScanEvent, make_gen=lambda: travelodge.run_scan( start=req.start, end=req.end, weekdays=set(req.weekdays), nights=req.nights, per_night=req.per_night, **req.shared_kwargs(), ), first_event="scan", list_key="nights", row_keys={"night": "night", "transport": "transport"}, ) _SEARCH_DESCRIPTION = ( "Pulls live Travelodge prices, then prices a round trip on TfL for the cheapest `top` hotels. " "TfL allows 50 lookups a minute without an app key (two per hotel), so a full run takes up to " "about a minute. Only one live search or scan runs at a time; identical requests are cached for ten minutes." ) _SCAN_DESCRIPTION = ( "Searches Travelodge once per candidate check-in date in `start`..`end` (filtered by `weekdays`), keeps the " "`per_night` cheapest hotels for each, then prices TfL transport once per unique hotel at the first " "night's departure time and reuses it for every night. Up to about three months; a scan can take a few " "minutes and shares the single live-search slot with /hotels/search. Identical scans are cached for ten minutes." ) def _ndjson(events) -> StreamingResponse: """Frame an iterable of Pydantic events as newline-delimited JSON. NDJSON rather than SSE: the client just splits on "\n" and JSON-parses each line, with no event-type framing to strip. `exclude_none=True` keeps the lines small, so absent keys must be treated as null by the reader. X-Accel-Buffering: no tells an nginx-style proxy not to buffer the response; without it the user would see nothing until the search finished, defeating the point of streaming. Caddy, the edge now, ignores the header and passes a chunked response on as it is written (its /py/hotels route also sets flush_interval -1), so the header is insurance for whatever proxy might sit here next. Cache-Control: no-cache stops any intermediary storing a partial stream. """ return StreamingResponse( (ev.model_dump_json(exclude_none=True) + "\n" for ev in events), media_type="application/x-ndjson", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) @app.post( "/hotels/search", response_model=HotelSearchResponse, summary="Rank Travelodges by room price plus TfL transport", description="Blocking form of the search: returns once every hotel is priced. " + _SEARCH_DESCRIPTION, responses={429: {"description": "Another search is already running"}, 502: {"description": "Upstream API failed"}}, ) def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse: """Run a search to completion and return the final result. Drains the same event generator the streaming endpoint uses and keeps only the "done" event. Because the status code must be chosen before anything is written, an "error" event becomes an HTTPException here: 429 when the single search slot was busy, 502 for anything upstream. Raises: HTTPException: 429 (busy) or 502 (upstream failure, or a stream that ended without a result). """ final = None for ev in _search_events(req): if ev.event == "error": status = 429 if ev.detail == ALREADY_RUNNING else 502 raise HTTPException(status_code=status, detail=ev.detail) if ev.event == "done": final = ev if final is None: raise HTTPException(status_code=502, detail="Search ended without a result") return HotelSearchResponse(summary=final.summary, rows=final.rows, cached=final.cached) @app.post( "/hotels/search/stream", summary="Streaming form of /hotels/search", description=( "Newline-delimited JSON (`application/x-ndjson`). Each line is a `HotelSearchEvent`: first " '`hotels` (every shortlisted hotel with room price and cycling time), then one `transport` ' "line per hotel as TfL fares arrive, then `done` (rows sorted by total). An `error` line " "ends a failed stream. " + _SEARCH_DESCRIPTION ), response_class=StreamingResponse, responses={200: {"content": {"application/x-ndjson": {"schema": HotelSearchEvent.model_json_schema()}}}}, ) def hotel_search_stream(req: HotelSearchRequest) -> StreamingResponse: """Stream the search as NDJSON. Always 200: the response starts before the work does, so failures (including the busy-slot case that the blocking endpoint reports as 429) arrive as a final "error" line instead of a status code. """ return _ndjson(_search_events(req)) @app.post( "/hotels/scan/stream", summary="Find the cheapest night to stay across a date range", description=( "Newline-delimited JSON (`application/x-ndjson`). Each line is a `HotelScanEvent`: first `scan` " "(every candidate night, pending), then one `night` line per date as Travelodge answers (its cheapest " "hotels, transport unpriced), then one `transport` line per unique hotel as TfL fares arrive (apply it " "to every night containing that hotel code), then `done` (totals filled in, nights sorted by best " "total). An `error` line ends a failed stream. " + _SCAN_DESCRIPTION ), response_class=StreamingResponse, responses={200: {"content": {"application/x-ndjson": {"schema": HotelScanEvent.model_json_schema()}}}}, ) def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse: """Stream the cheapest-night scan as NDJSON. Transport is emitted once per unique hotel code, not once per row: the client is expected to apply each "transport" line to every night containing that code. Like the search stream this is always 200, with failures carried as a final "error" line. """ return _ndjson(_scan_events(req)) # --------------------------------------------------------------------------- # # Internal: the routes the Go backend calls # --------------------------------------------------------------------------- # def _internal_only(request: Request) -> None: """Refuse a request that arrived through the edge proxy (Caddy). Every other route in this service is public, but the internal ones spend a paid Claude call per request and have no auth of their own - the admin or token check happens in the Go backend, which calls this container directly over app-network. Two layers keep the outside world off it, because either alone is one config edit away from being lost: 1. Caddy answers /py/internal/ with a 404 (caddy/routes.caddy, dev and production alike). 2. Caddy stamps X-Real-IP and X-Forwarded-For on everything it proxies here (the `proxy` snippet), and a client cannot make it omit them; the Go backend sends neither. So their presence means the request came from outside. 404 rather than 403, so the route is indistinguishable from one that does not exist. """ if "x-real-ip" in request.headers or "x-forwarded-for" in request.headers: raise HTTPException(status_code=404, detail="Not Found") def _internal_claude_route(path: str, **kwargs): """`app.post` for a route that makes a Claude call on the Go backend's behalf. Adds the two things every such route needs, so a new one cannot forget either: the `_internal_only` guard, and the 502/503 entries in the docs. The handler itself then only calls its module and returns the result - the errors it can raise are turned into those responses by `_claude_failed` below. The guard is a dependency rather than a call in the handler because dependencies are resolved before the body is validated: a request from outside gets the 404 whatever it posted, instead of a 422 that confirms the route exists and describes its fields. """ return app.post( path, dependencies=[Depends(_internal_only)], responses={ 502: {"description": "Claude failed, or its reply was not the expected JSON"}, 503: {"description": "CLAUDE_API_KEY is not set"}, }, **kwargs, ) @app.exception_handler(claude.ReadError) def _claude_failed(request: Request, exc: claude.ReadError) -> JSONResponse: """Turn a Claude module's failure into the response the Go backend expects. 503 when the API key is missing (NotConfigured, a ReadError subclass, so one handler sees both), 502 for everything else. The body is the same `{"detail": ...}` an HTTPException produces, and the detail is one of the module's fixed messages - the Go handlers pass it on to their own caller verbatim, which is why nothing from the API or the model's reply is ever put in it. """ status = 503 if isinstance(exc, claude.NotConfigured) else 502 return JSONResponse(status_code=status, content={"detail": str(exc)}) # --------------------------------------------------------------------------- # # Internal: rowing display reader # --------------------------------------------------------------------------- # # 10MB of image (the Go handler's upload cap) once base64-encoded, rounded up. MAX_IMAGE_B64_CHARS = 14_000_000 class RowingReadRequest(BaseModel): """An image for Claude to read, as the Go backend sends it.""" # The Anthropic API's image types; the Go handler checks them first. media_type: Literal["image/jpeg", "image/png", "image/gif", "image/webp"] data: str = Field(..., min_length=1, max_length=MAX_IMAGE_B64_CHARS, description="Base64 image bytes") @_internal_claude_route( "/internal/rowing/read", response_model=rowing.RowingReading, summary="Read time and distance off a rowing machine display", description=( "Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through Caddy. " "Sends the image to Claude and returns the three numbers it read. No plausibility checking " "happens here - the caller owns the sanity bounds." ), ) def rowing_read(req: RowingReadRequest) -> rowing.RowingReading: """Read a rowing display photo. A plain `def`, so FastAPI runs it in the threadpool and the blocking Claude call does not stall the event loop the hotel streams are served from. Responds 404 (came through Caddy), 503 (no API key) or 502 (Claude failed or returned something unparseable) by way of `_internal_claude_route`. The 502 detail is one of rowing.read_display's fixed messages, which the Go handler passes on to the admin verbatim. """ return rowing.read_display(req.media_type, req.data)