Trim comments to the non-obvious why
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:
+11
-38
@@ -1,13 +1,6 @@
|
||||
"""The Anthropic client and the one call every Claude caller here makes.
|
||||
"""The Anthropic client and `ask_json`: one prompt for bare JSON, one parsed reply.
|
||||
|
||||
`rowing` (a photo in, three numbers out) is a call of a general shape: one
|
||||
prompt asking for bare JSON, one reply to parse. That whole sequence is
|
||||
`ask_json` below, so a caller is a prompt, a pydantic model and three error
|
||||
strings, and another caller would get the same handling around the call. Also
|
||||
here: the lazily built client and the two exception types `main` maps to 502
|
||||
and 503.
|
||||
|
||||
Like the modules that use it, this never imports FastAPI.
|
||||
The two exception types map to 502 and 503 in `main`. Never imports FastAPI.
|
||||
"""
|
||||
|
||||
import functools
|
||||
@@ -22,37 +15,21 @@ log = logging.getLogger(__name__)
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
# Which model every call uses. CLAUDE_MODEL comes from .env; changing it means
|
||||
# recreating this container, which is why reading it once at import is enough.
|
||||
# Blank means the default.
|
||||
#
|
||||
# The ids listed in .env.example are the ones this module has been written for. Another
|
||||
# id is passed through as it is, treated as a model that thinks (see below);
|
||||
# if the API does not know it, every call fails with its `failed` message and
|
||||
# the reason is in this service's log.
|
||||
# Read once at import; blank means the default. Unknown ids are passed
|
||||
# through and treated as thinking models.
|
||||
DEFAULT_MODEL = "claude-sonnet-5-5"
|
||||
MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL
|
||||
|
||||
# Models that take no `output_config.effort` and do not think unless asked to.
|
||||
# Everything newer thinks by default, and that changes two things in the
|
||||
# request - see _model_options.
|
||||
# Models that take no effort setting and don't think unless asked.
|
||||
_NO_EFFORT_PREFIXES = ("claude-haiku-4-5",)
|
||||
|
||||
# Thinking is billed against `max_tokens` like the reply is, and the callers'
|
||||
# ceilings are sized for the reply alone (a few hundred tokens of JSON). On a
|
||||
# model that thinks, this is added on top so that a posting worth a moment's
|
||||
# thought cannot use the whole allowance and leave no room for the answer.
|
||||
# Thinking counts against max_tokens, and callers size theirs for the reply.
|
||||
THINKING_HEADROOM = 4000
|
||||
|
||||
# Every call here is extraction or classification: read something, return a
|
||||
# small JSON object. "low" is the level meant for that - the model skips
|
||||
# thinking on most simple requests - and it is set explicitly because the
|
||||
# default differs between models.
|
||||
# Set explicitly because the default differs between models.
|
||||
EFFORT = "low"
|
||||
|
||||
# Seconds per attempt. The SDK retries twice on top (429/5xx/connection), so
|
||||
# the worst case is roughly three of these plus backoff; the Go callers' own
|
||||
# timeout is set above that so they see this side's error, not their own.
|
||||
# Per attempt; the SDK retries twice. The Go caller's timeout sits above that.
|
||||
TIMEOUT_S = 30.0
|
||||
|
||||
|
||||
@@ -149,8 +126,7 @@ def ask_json(
|
||||
if system is not None:
|
||||
request["system"] = system
|
||||
|
||||
# Outside the try: NotConfigured is not an API failure and must reach
|
||||
# `main` as itself, to become the 503.
|
||||
# Outside the try so NotConfigured reaches `main` and becomes the 503.
|
||||
api = (get_client or client)()
|
||||
try:
|
||||
message = api.messages.create(**request)
|
||||
@@ -161,15 +137,12 @@ def ask_json(
|
||||
log.warning("Claude API unreachable: %s", e)
|
||||
raise ReadError(failed) from e
|
||||
|
||||
# A refusal is an ordinary 200 whose content is not the answer. Say so in
|
||||
# the log rather than letting it surface as an "empty" or "unparseable"
|
||||
# reply, which would point at the prompt instead of at the classifier.
|
||||
# A refusal is a 200; log it as such rather than as an unparseable reply.
|
||||
if getattr(message, "stop_reason", None) == "refusal":
|
||||
log.warning("Claude declined the request: %s", getattr(message, "stop_details", None))
|
||||
raise ReadError(failed)
|
||||
|
||||
# By type, not position: on a model that thinks, the first block can be a
|
||||
# (possibly empty) thinking block.
|
||||
# By type: on a thinking model the first block may be a thinking block.
|
||||
text = next((block.text for block in message.content if block.type == "text"), None)
|
||||
if text is None:
|
||||
if getattr(message, "stop_reason", None) == "max_tokens":
|
||||
|
||||
+9
-39
@@ -1,29 +1,8 @@
|
||||
"""Small Python API service.
|
||||
"""HTTP skin for `travelodge` and `rowing`.
|
||||
|
||||
Caddy proxies https://www.<DOMAIN>/py/... to this container and strips the
|
||||
/py prefix, so routes here are defined relative to "/". FastAPI's root_path
|
||||
(set via --root-path on the uvicorn command line) keeps the generated docs
|
||||
at /py/docs working behind the proxy.
|
||||
|
||||
Endpoints
|
||||
GET / service index
|
||||
GET /health liveness probe
|
||||
GET /hello/{name} demo route
|
||||
GET /hotels/origins the known travel origins the UI offers
|
||||
POST /hotels/search blocking cheapest-Travelodge search
|
||||
POST /hotels/search/stream same search, streamed as NDJSON
|
||||
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
|
||||
POST /internal/rowing/read read a rowing display photo with Claude
|
||||
(Go backend only - not reachable through Caddy)
|
||||
|
||||
All the hotel work lives in `travelodge`; this module is the HTTP skin around
|
||||
it - request validation, a response cache, the one-search-at-a-time guard, and
|
||||
the NDJSON framing. The rowing reader (`rowing`) is the one route here that
|
||||
is not public: see the "Internal" sections at the bottom, which open with the
|
||||
wrapper it is registered through. The hotel routes are consumed by
|
||||
vue/src/views/hotels/ (SingleStayPanel.vue,
|
||||
CheapestNightPanel.vue, useHotelForm.js), which fetch these paths with the /py
|
||||
prefix. Field names in the models below are part of that contract.
|
||||
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
|
||||
@@ -88,10 +67,7 @@ MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS
|
||||
CACHE_TTL_S = 10 * 60
|
||||
CACHE_MAX = 200
|
||||
|
||||
# The service prices London hotels and London transport, so "today" means today
|
||||
# in London - not on whatever timezone the server happens to be set to. Using
|
||||
# the server's local date refused a check-in that was still today for a user
|
||||
# west of it (and, on a UTC server during BST, accepted one an hour late).
|
||||
# Dates are London dates, whatever the server's timezone.
|
||||
LONDON_TZ = ZoneInfo("Europe/London")
|
||||
|
||||
|
||||
@@ -99,15 +75,10 @@ def london_today() -> date:
|
||||
"""Today's date in London, the reference for "today or later" validation."""
|
||||
return datetime.now(LONDON_TZ).date()
|
||||
|
||||
# Only one live search or scan may run at a time, process-wide. A run can spend
|
||||
# the entire anonymous TfL budget (50 requests/min), so two concurrent runs
|
||||
# would simply starve each other into rate-limit backoff. Callers that find the
|
||||
# slot taken get an immediate "try again" rather than queueing.
|
||||
# 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)
|
||||
# Finished responses, keyed by the canonical request body. Bounded as well as
|
||||
# swept: the one-at-a-time guard makes growth slow, but "slow" is not "never",
|
||||
# and a response holds every row of a scan. Eviction is insertion order, so a
|
||||
# repeatedly-requested entry still ages out and is refetched.
|
||||
# Bounded because one response holds every row of a scan.
|
||||
_cache = travelodge.TTLCache(CACHE_TTL_S, max_entries=CACHE_MAX)
|
||||
|
||||
|
||||
@@ -726,8 +697,7 @@ MAX_IMAGE_B64_CHARS = 14_000_000
|
||||
class RowingReadRequest(BaseModel):
|
||||
"""An image for Claude to read, as the Go backend sends it."""
|
||||
|
||||
# The types the Anthropic API accepts for an image block. The Go handler
|
||||
# checks the same list first so the admin gets its friendlier 400.
|
||||
# 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")
|
||||
|
||||
|
||||
+5
-13
@@ -1,20 +1,12 @@
|
||||
"""Read a rowing machine display from a photo with Claude.
|
||||
|
||||
This is the image half of the Go backend's admin-only POST /rowing. The Go
|
||||
handler keeps everything that needs the database or the session cookie - the
|
||||
admin gate, the EXIF date, the duplicate check, the sanity bounds, the insert -
|
||||
and hands the image here only once it has decided the Claude call is worth
|
||||
paying for. This module just turns pixels into three numbers.
|
||||
|
||||
Like `travelodge`, it never imports FastAPI; `main` is the HTTP skin.
|
||||
The Go handler does auth, EXIF, dedup and bounds; this only turns pixels into
|
||||
three numbers.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# Re-exported under the names this module has always had: the tests reach the
|
||||
# exceptions and the fence stripping through `rowing`. `_client` is the seam
|
||||
# they replace to fake the API, which is why it is handed to ask_json below
|
||||
# rather than left to its default.
|
||||
# `_client` is the seam the tests replace.
|
||||
from .claude import MODEL, NotConfigured, ReadError, ask_json, strip_markdown_fence
|
||||
from .claude import client as _client
|
||||
|
||||
@@ -23,8 +15,8 @@ __all__ = ["MODEL", "NotConfigured", "ReadError", "RowingReading", "read_display
|
||||
# The answer is a three-key JSON object, so this is a ceiling, not a target.
|
||||
MAX_TOKENS = 256
|
||||
|
||||
# The keys named here are the JSON contract: RowingReading's field names below
|
||||
# and ExtractedRowingData in backend/handlers/handle_rowing.go must match them.
|
||||
# Keys must match RowingReading below and ExtractedRowingData in
|
||||
# backend/handlers/handle_rowing.go.
|
||||
PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance.
|
||||
|
||||
Return ONLY a JSON object with these exact keys and numeric values:
|
||||
|
||||
+45
-168
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user