Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
+45 -168
View File
@@ -1,63 +1,10 @@
"""Cheapest Travelodge (room + TfL transport) for a stay in London.
Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged;
the plumbing around it has been rewritten for speed:
* Travelodge result pages are fetched in parallel batches.
* TfL journeys are fetched by one flat worker pool (every hotel/query pair is
submitted to it and results gathered per hotel), throttled to the anonymous API
limit (50 requests/min; 500/min with TFL_APP_KEY) and cached for a while
so repeat searches don't spend the budget again.
* `run_search` is a generator that yields the hotel list first and then one
event per priced hotel, so callers can stream progress to a browser.
Data sources
* Travelodge's own search JSON API -> live room prices for every hotel
matching a location search.
* TfL Journey Planner API -> route + pay-as-you-go fare from the origin to
each hotel.
Method
1. Pull every hotel for the search, drop ones with no availability, sort by
cheapest room price and keep only the cheapest `top` hotels.
2. For each, ask TfL for (a) the fastest route and (b) a bus-only route at
the given departure time. Pick the cheapest that isn't slower than
`max_travel_min`.
3. Apply a Railcard discount (1/3 off) to OFF-PEAK rail/tube fares. Buses
are never discounted.
4. Assume the return journey the next morning costs the off-peak equivalent
of the outbound.
5. Rank by room + round-trip transport. Cycling time is reported separately
(TfL cycle routing with an app key, otherwise a distance-based estimate).
Fragility
Neither API is a documented public contract for this use. Travelodge's
/api/v2/hotel endpoint is the JSON feed its own search page calls; the query
parameter names ("q", "checkIn", "rooms[0][adults]", the undocumented
"action=hotel_amend") and the response field names consumed in
`normalise_hotel` are whatever the site happens to send today. If Travelodge
reshapes its search page, every price here silently becomes None rather than
raising. Same for TfL's fare JSON: `price_journey` reads `fare.fares[].cost`
/ `peak` / `offPeak` / `chargeLevel`, and falls back to "no fare found" if the
shape changes. There is no HTML parsing anywhere in this module - both
upstreams are JSON - so there are no CSS/XPath selectors to break, but the
key names play the same role.
Concurrency
Everything here is thread-based (requests is blocking), not asyncio. Module
state - the two :class:`TTLCache` response caches, the rate limiters and the shared
requests.Session - is process-global and guarded by plain locks, so it is
shared across concurrent FastAPI requests. main.py additionally allows only
one live search at a time, which is what keeps the TfL budget spendable by a
single run.
Time budgets
Every network path takes an optional `deadline` (a time.monotonic() value).
Passing it down instead of using a wall-clock timeout lets a long run degrade
gracefully: work already done is returned with summary["truncated"] = True
instead of the whole request being cut off by a proxy timeout. (nginx cut at
300s; Caddy sets no upstream timeout, but the budgets below still bound a
run, and Cloudflare gives up on an origin that sends nothing for 100s.)
The pricing method and the upstream fragility points are in python/README.md.
Both APIs are undocumented JSON, read tolerantly: a renamed field becomes None,
not an error. Thread-based, with process-global caches, rate limiters and
session. Every network path takes a time.monotonic() `deadline`, so a long run
returns partial work (summary["truncated"]) instead of being cut off.
"""
import logging
@@ -71,19 +18,15 @@ from datetime import date, datetime, timedelta
import requests
# Every upstream field is read tolerantly, so a Travelodge schema change would
# otherwise be indistinguishable from genuinely sold-out inventory. This logger
# is the only signal that the difference exists - see `hotels_for`.
# Fields are read tolerantly, so this logger is the only way to tell a schema
# change from sold-out inventory (see `hotels_for`).
log = logging.getLogger(__name__)
TL_API = "https://www.travelodge.co.uk/api/v2/hotel"
TL_SITE = "https://www.travelodge.co.uk"
TFL_API = "https://api.tfl.gov.uk/Journey/JourneyResults/{frm}/to/{to}"
# A browser User-Agent is sent because Travelodge's edge rejects or throttles
# obviously-scripted clients (python-requests/x.y). The Chrome version is
# arbitrary and is never checked for freshness; if requests start coming back
# as 403 or as a challenge page, this is the first thing to bump. The same
# headers are reused for TfL, where they are harmless.
# Travelodge's edge throttles scripted User-Agents. If 403s or challenge pages
# appear, bump the Chrome version first.
HEADERS = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36",
"Accept": "application/json",
@@ -104,49 +47,39 @@ ORIGINS = {
# Rough Greater London bounding box for custom "lat,lon" origins.
LONDON_BOX = (51.25, 51.75, -0.55, 0.35) # min lat, max lat, min lon, max lon
# Wall-clock budget for one run_search call. Set when nginx cut the connection
# at 300s: stop pricing transport well before that and return what we have.
# Caddy has no such cut, but the budget still keeps a run bounded.
# Wall-clock budget for one run_search call.
SEARCH_DEADLINE_S = 200
# A date-range scan fetches one Travelodge search per candidate night, then
# prices TfL once per unique hotel. Stop starting new date fetches after the
# soft deadline; stop TfL pricing at the hard one and return what we have.
# Scans stop starting date fetches at the soft deadline and stop TfL pricing
# at the hard one.
SCAN_FETCH_DEADLINE_S = 150
SCAN_DEADLINE_S = 240
SCAN_DATE_WORKERS = int(os.environ.get("TL_SCAN_WORKERS", "4"))
SCAN_MAX_DAYS = 91
# Normalised Travelodge results are cached per (location, dates, rooms) so a
# re-scan with different weekday/transport settings is free on the Travelodge
# side. Prices may therefore be up to TL_CACHE_TTL_S old.
# Lets a re-scan with different settings skip Travelodge.
TL_CACHE_TTL_S = 30 * 60
TL_CACHE_MAX = 600
# Travelodge returns 10 hotels per page whatever you ask for; fetch pages in
# parallel batches until a batch comes back with nothing new.
# Travelodge returns 10 per page regardless; batches stop when nothing is new.
TL_PAGE_SIZE = 10
TL_PAGE_BATCH = 6
TL_MAX_START = 500
# TfL: anonymous callers get 50 requests/min, keyed callers 500/min. A call
# normally takes 1-5s; the odd one hangs, so time out early and retry.
# TfL allows 50 req/min anonymous, 500 keyed. The odd call hangs, so time out
# early and retry.
TFL_WORKERS = 12
TFL_TIMEOUT_S = 15
TFL_RATE_ANON = 48
TFL_RATE_KEYED = 450
TFL_CACHE_TTL_S = 2 * 60 * 60
# Cycling estimate when TfL cycle routing isn't used: straight-line distance
# times a road-winding factor, at a relaxed London pace.
# Fallback cycling estimate: straight-line distance times a winding factor.
CYCLE_ROUTE_FACTOR = 1.3
CYCLE_KMH = 14.0
# One process-wide Session so TLS handshakes and any cookies the upstreams set
# are reused across requests (a fresh Session per call roughly doubles latency).
# pool_maxsize must cover the widest possible fan-out - TfL workers plus every
# scan date worker running its own batch of Travelodge page fetches - otherwise
# urllib3 starts discarding connections and logging pool-full warnings.
# One shared Session reuses TLS connections. pool_maxsize must cover the widest
# fan-out (TfL workers plus every scan worker's page fetches).
_session = requests.Session()
_session.mount(
"https://",
@@ -316,8 +249,7 @@ def _fetch_page(params: dict, start: int, deadline: float | None = None) -> list
r.raise_for_status()
return r.json().get("results") or []
except (requests.RequestException, ValueError, AttributeError) as e:
# ValueError covers r.json() on a non-JSON body; AttributeError covers a
# JSON body that is a list or scalar rather than an object (no .get).
# ValueError: non-JSON body. AttributeError: JSON that isn't an object.
raise UpstreamError(f"Travelodge search failed: {e}") from e
@@ -371,11 +303,8 @@ def fetch_hotels(location, checkin, checkout, rooms, deadline=None) -> list[dict
if not absorb(first) or len(first) < TL_PAGE_SIZE:
return hotels
# Fetch TL_PAGE_BATCH pages at a time and stop on the first batch that is
# either short (a page with fewer than TL_PAGE_SIZE results is the last one)
# or wholly duplicate. Requesting speculatively overshoots by up to a batch,
# but a strictly sequential walk of ~50 pages would blow the time budget.
# TL_MAX_START is a hard stop in case the API ever pages forever.
# Batches stop on a short page or an all-duplicate batch; sequential paging
# would blow the time budget. TL_MAX_START guards against endless paging.
start = TL_PAGE_SIZE
with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex:
while start <= TL_MAX_START:
@@ -420,8 +349,6 @@ def normalise_hotel(h: dict) -> dict:
}
# (location, checkin, checkout, rooms) -> [normalised hotel dicts]. Bounded by
# count, and expired entries are swept on every write (the cache is small).
_tl_cache = TTLCache(TL_CACHE_TTL_S, max_entries=TL_CACHE_MAX)
@@ -430,25 +357,17 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
Failures are not cached. Callers must treat the returned dicts as read-only.
"""
# Case/whitespace-insensitive location so "Central London" and
# "central london " share one cache entry; rooms must be hashable, hence
# the tuple.
key = (location.strip().lower(), checkin, checkout, tuple(rooms))
hit = _tl_cache.get(key)
if hit is not None:
return hit
# The fetch deliberately happens outside any cache lock: a slow upstream
# must not block other threads reading the cache. Two threads racing on the
# same key both fetch and the second write wins, which is harmless.
# Fetched outside any lock; a racing duplicate fetch is harmless.
raw = fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)
hotels = [normalise_hotel(h) for h in raw]
# A response that parsed but yielded nothing usable is the fingerprint of a
# renamed upstream field: the tolerant .get()s in `normalise_hotel` turn a
# schema change into "no hotels available", which looks exactly like a
# sold-out search. Genuine sold-out inventory still carries names and codes,
# so warn only when the shape itself came back empty.
# Sold-out results still carry names and codes, so an empty shape means a
# renamed upstream field.
if raw and not any(h["code"] and h["name"] for h in hotels):
log.warning(
"Travelodge returned %d hotels for %r (%s..%s) but none had a usable "
@@ -539,9 +458,7 @@ def price_journey(journey, adults=1, railcard_holders=1):
if not non_walk: # walking only
return 0, 0, "walk"
# TfL omits the fare block entirely for some journeys (e.g. ones involving
# a mode it cannot price). Returning None makes the caller drop this option
# rather than treat it as free.
# No fare block means unpriceable: drop the option rather than call it free.
if not fare or not fare.get("fares"):
return None
@@ -549,11 +466,8 @@ def price_journey(journey, adults=1, railcard_holders=1):
for f in fare["fares"]:
cost = f.get("cost") or 0
peak, offpeak = f.get("peak") or 0, f.get("offPeak") or 0
# Two independent bus tests, because TfL is inconsistent about which
# it provides: a fare with neither a peak nor an off-peak price is a
# flat bus fare by construction, and otherwise the tap records name the
# mode outright. Getting this wrong would apply a Railcard discount to
# a bus fare, which does not exist.
# TfL marks buses inconsistently, so test both ways; a Railcard
# discount must never reach a bus fare.
is_bus = (peak == 0 and offpeak == 0) or any(
(t.get("tapDetails") or {}).get("modeType") == "Bus" for t in (f.get("taps") or [])
)
@@ -562,13 +476,9 @@ def price_journey(journey, adults=1, railcard_holders=1):
out += cost * adults
ret += cost * adults
else:
# Railcards give 1/3 off *off-peak* rail/tube fares only, so the
# outbound is discounted only when this fare is off-peak. That is
# detected two ways because chargeLevel is free text that has
# historically read "Off Peak", "Off-peak" or been absent: a
# substring match on "off", or the cost simply equalling the
# off-peak price. The return is always treated as off-peak (see the
# docstring), so it is always discounted for railcard holders.
# Railcards discount off-peak rail/tube only. chargeLevel is free
# text that has varied, so also match cost == off-peak price. The
# return leg is always treated as off-peak.
level = (f.get("chargeLevel") or "").lower()
out_full = cost
ret_full = offpeak or cost # next-day return assumed off-peak
@@ -577,9 +487,7 @@ def price_journey(journey, adults=1, railcard_holders=1):
out += out_full * full_fare + out_disc * railcard_holders
ret += ret_full * full_fare + ret_disc * railcard_holders
# Short human summary of the route, e.g. "rail > tube Victoria". Walking
# legs are dropped as noise, and "national-rail" is shortened purely to fit
# the column in the UI.
# e.g. "rail > tube Victoria", with walking legs dropped.
parts = []
for l in legs:
m = (l.get("mode") or {}).get("id")
@@ -648,9 +556,7 @@ def _limiter(app_key: str | None) -> RateLimiter:
return lim
# journey key -> journeys. Unbounded on purpose (entries are small and a long
# scan wants them all), so expired entries are only swept once it is large,
# keeping the common write O(1).
# Unbounded on purpose (a long scan wants every entry); swept only when large.
_tfl_cache = TTLCache(TFL_CACHE_TTL_S, sweep_above=5000)
@@ -700,9 +606,7 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
}
if extra:
params.update(extra)
# Coordinates are rounded to 5dp (~1m) so that floating-point noise in
# otherwise identical requests still hits the cache. app_key is excluded
# from the key on purpose: the route and fare do not depend on it.
# 5dp (~1m) absorbs float noise. app_key doesn't affect the answer.
key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"],
tuple(sorted((extra or {}).items())))
hit = _tfl_cache.get(key)
@@ -714,14 +618,8 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}")
limiter = _limiter(app_key)
journeys = None
# Retry policy, all deadline-aware (a skipped sleep means the deadline is
# too close, so stop rather than hammer):
# network error -> wait 2s
# 429 rate limited -> linear backoff, 5s then 10s then 15s
# 5xx -> wait 2s
# any other non-200 (notably 300 "disambiguation", meaning TfL wants the
# caller to pick between candidate locations) -> treat as "no route",
# do not retry, and cache the empty result
# Deadline-aware retries: network error or 5xx wait 2s, 429 backs off
# linearly, any other non-200 (e.g. 300 disambiguation) is cached as no route.
for attempt in range(retries):
remaining = TFL_TIMEOUT_S if deadline is None else deadline - time.monotonic()
if remaining < 1 or not limiter.acquire(deadline):
@@ -749,13 +647,9 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
journeys = []
break
# journeys is still None only if every attempt was abandoned; return empty
# without caching so a later, less rushed call can try again. An empty list
# from a *successful* response is cached - "no route" is a real answer.
# Only a successful empty answer is cached; abandoned attempts can retry later.
if journeys is None:
return [], True
# TFL_CACHE_TTL_S is long because journey times and fares for a fixed
# date/time do not change.
_tfl_cache.set(key, journeys)
return journeys, False
@@ -786,10 +680,8 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
return _tfl_journeys(frm, to, when, extra, app_key, retries, deadline)[0]
# Two journey queries per hotel, because TfL's default "LeastTime" answer is
# usually a tube fare and the cheapest option is very often a slower bus. The
# bus query has to name "walking" alongside "bus" or TfL refuses routes that
# need a walk to the stop.
# A second, bus-only query because TfL's fastest route is rarely the cheapest.
# "walking" is required alongside "bus" or routes needing a walk are refused.
TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
CYCLE_QUERY = {"mode": "cycle"}
@@ -913,9 +805,8 @@ def cycle_time(origin, hotel, when, app_key, deadline=None, journeys=None):
# --------------------------------------------------------------------------- #
# Search
# --------------------------------------------------------------------------- #
# Every transport column blanked out. Splatted into a row to reset it, so
# adding a transport field means adding it here too or it will leak a stale
# value from a previous night when rows are reused in a scan.
# Resets a reused row's transport fields; a new transport field must be added
# here or a scan leaks a stale value between nights.
_UNPRICED = {
"transport_out": None,
"transport_return": None,
@@ -1044,8 +935,7 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
fut = pool.submit(_tfl_journeys, origin, dest, depart_dt, extra, app_key, deadline=deadline)
owner[fut] = (code, label)
if app_key:
# Cycle routing costs a third rate-limited request, so it is
# only asked for when a key lifts the anonymous budget.
# A third rate-limited request, so only with an API key.
entry["cycle"] = pool.submit(
_tfl_journeys, origin, dest, depart_dt, CYCLE_QUERY, app_key, 1, deadline
)
@@ -1066,9 +956,6 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
abandoned = any(entry["fares"][lbl][1] for lbl, _ in TRANSPORT_QUERIES)
cyc = None
if entry["cycle"] is not None:
# Already submitted above, so this wait is usually over by
# now; waiting here (in the consumer, never in a worker) is
# safe with a single flat pool.
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline,
journeys=entry["cycle"].result()[0])
yield code, t, cyc, (t is None and abandoned)
@@ -1289,11 +1176,7 @@ def _scan_order(night_list):
best[code] = key
if code not in coords:
coords[code] = {"code": code, "lat": row["lat"], "lon": row["lon"]}
# The estimate is a pure function of the coordinates, so any
# night's row carries the same values.
cycle_base[code] = {k: row[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")}
# sorted() is stable and `best` is in first-seen order, matching the old
# index-based ordering exactly.
ordered = [coords[code] for code in sorted(best, key=lambda c: best[c])]
return ordered, cycle_base
@@ -1309,9 +1192,7 @@ def _scan_transport(*, ordered, cycle_base, transport, summary, origin, depart_d
for code, t, cyc, timed_out in _price_hotels(
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
):
# Transport here is night-independent, so there is no room price to add:
# a dummy 0 is passed and the resulting "total" discarded. Each night
# computes its own total in phase 3.
# Night-independent: the dummy total is discarded.
fields = _transport_fields({"room_price": 0}, t)
fields.pop("total", None)
if timed_out:
@@ -1320,9 +1201,7 @@ def _scan_transport(*, ordered, cycle_base, transport, summary, origin, depart_d
if cyc:
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
else:
# No TfL cycle result: keep the local estimate computed when the
# rows were built, since these fields are copied wholesale onto
# every night's copy of this hotel.
# Keep the local estimate; these fields are copied to every night.
fields.update(cycle_base.get(code, {}))
fields["code"] = code
transport[code] = fields
@@ -1361,9 +1240,7 @@ def _scan_totals(night_list, transport, summary) -> None:
n["best_code"] = best["code"]
n["best_room"] = min(r["room_price"] for r in n["hotels"])
# Cheapest night first; nights with no total (failed, skipped, or unpriced)
# fall to the bottom, ordered by best room price and then by date so the
# list is still deterministic.
# Cheapest first; unpriced nights last, then by room price and date.
night_list.sort(
key=lambda n: (
n["best_total"] is None,