Speed up cheap Travelodge finder and stream results
Deploy with Docker Compose / deploy (push) Successful in 59s
Deploy with Docker Compose / deploy (push) Successful in 59s
Backend: fetch Travelodge pages in parallel batches, price TfL journeys from a worker pool throttled to the anonymous 50/min limit (500/min with TFL_APP_KEY), cache TfL journeys for two hours, and expose a streaming NDJSON endpoint (/hotels/search/stream) that sends the hotel list first and one line per hotel as fares arrive. A 20-hotel search now takes about 10 seconds instead of minutes. Every hotel also gets a cycling time from the origin (TfL cycle routing with an app key, otherwise a distance estimate). Frontend: consume the stream so hotels appear immediately with a progress bar, show three picks (best value, cheapest room, quickest cycle) instead of one, add a rank-by toggle (stay + transport, stay only, cycle time, travel time) and a Cycle column, and raise the hotel cap to 40. Nginx: match both search routes and disable proxy buffering and gzip so the stream reaches the browser as it is produced. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
This commit is contained in:
@@ -264,11 +264,16 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
location = /py/hotels/search {
|
||||
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
@@ -181,11 +181,16 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
location = /py/hotels/search {
|
||||
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
@@ -363,11 +368,16 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
location = /py/hotels/search {
|
||||
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
+109
-28
@@ -14,13 +14,14 @@ from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from . import travelodge
|
||||
|
||||
app = FastAPI(
|
||||
title="Python API",
|
||||
version="0.2.0",
|
||||
version="0.3.0",
|
||||
docs_url="/docs",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
@@ -79,7 +80,7 @@ class HotelSearchRequest(BaseModel):
|
||||
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")
|
||||
top: int = Field(15, ge=1, le=25, description="Price transport for the N cheapest stays only")
|
||||
top: int = Field(20, ge=1, le=40, description="Price transport for the N cheapest stays only")
|
||||
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")
|
||||
|
||||
@@ -154,6 +155,9 @@ class HotelRow(BaseModel):
|
||||
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):
|
||||
@@ -173,6 +177,8 @@ class HotelSearchSummary(BaseModel):
|
||||
hotels_found: int
|
||||
hotels_available: int
|
||||
hotels_priced: int
|
||||
hotels_shortlisted: int = 0
|
||||
tfl_rate_per_min: int = 0
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
@@ -187,31 +193,55 @@ def hotel_origins() -> list[Origin]:
|
||||
return [Origin(key=k, name=n, lat=lat, lon=lon) for k, (n, lat, lon) in travelodge.ORIGINS.items()]
|
||||
|
||||
|
||||
@app.post(
|
||||
"/hotels/search",
|
||||
response_model=HotelSearchResponse,
|
||||
summary="Rank Travelodges by room price plus TfL transport",
|
||||
description=(
|
||||
"Blocking search: pulls live Travelodge prices, then prices a round trip on TfL for the "
|
||||
"cheapest `top` hotels. Takes roughly a minute. Only one search runs at a time; identical "
|
||||
"searches are cached for ten minutes."
|
||||
),
|
||||
responses={429: {"description": "Another search is already running"}, 502: {"description": "Upstream API failed"}},
|
||||
)
|
||||
def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
|
||||
key = json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
now = time.monotonic()
|
||||
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
|
||||
|
||||
|
||||
def _cache_get(key):
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
hit = _cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return HotelSearchResponse(**hit[1], cached=True)
|
||||
return hit[1]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_put(key, result):
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _cache[k]
|
||||
_cache[key] = (now + CACHE_TTL_S, result)
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible.
|
||||
|
||||
Holds the single search slot while live pricing runs. 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.
|
||||
"""
|
||||
key = json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
yield HotelSearchEvent(event="hotels", cached=True, **hit)
|
||||
yield HotelSearchEvent(event="done", cached=True, **hit)
|
||||
return
|
||||
|
||||
if not _search_slot.acquire(blocking=False):
|
||||
raise HTTPException(status_code=429, detail="A search is already running, try again in a minute.")
|
||||
yield HotelSearchEvent(event="error", detail="A search is already running, try again in a minute.")
|
||||
return
|
||||
try:
|
||||
origin_name, origin = travelodge.parse_origin(req.origin)
|
||||
result = travelodge.run_search(
|
||||
gen = travelodge.run_search(
|
||||
location=req.location,
|
||||
checkin=req.checkin,
|
||||
checkout=req.checkout,
|
||||
@@ -224,19 +254,70 @@ def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
|
||||
max_miles=req.max_miles,
|
||||
max_travel_min=req.max_travel_min,
|
||||
)
|
||||
for ev in gen:
|
||||
if ev[0] == "transport":
|
||||
yield HotelSearchEvent(event="transport", row=ev[1])
|
||||
else:
|
||||
kind, summary, rows = ev
|
||||
if kind == "done":
|
||||
_cache_put(key, {"summary": summary, "rows": rows})
|
||||
yield HotelSearchEvent(event=kind, summary=summary, rows=rows)
|
||||
except travelodge.UpstreamError as e:
|
||||
raise HTTPException(status_code=502, detail=str(e)) from e
|
||||
yield HotelSearchEvent(event="error", detail=str(e))
|
||||
except (KeyError, TypeError) as e:
|
||||
raise HTTPException(status_code=502, detail=f"Unexpected upstream response: {e}") from e
|
||||
yield HotelSearchEvent(event="error", detail=f"Unexpected upstream response: {e}")
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=422, detail=str(e)) from e
|
||||
yield HotelSearchEvent(event="error", detail=str(e))
|
||||
finally:
|
||||
_search_slot.release()
|
||||
|
||||
with _cache_lock:
|
||||
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _cache[k]
|
||||
_cache[key] = (time.monotonic() + CACHE_TTL_S, result)
|
||||
|
||||
return HotelSearchResponse(**result)
|
||||
_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 runs at a time; identical searches are cached for ten minutes."
|
||||
)
|
||||
|
||||
|
||||
@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:
|
||||
final = None
|
||||
for ev in _search_events(req):
|
||||
if ev.event == "error":
|
||||
status = 429 if "already running" in (ev.detail or "") 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):
|
||||
def lines():
|
||||
for ev in _search_events(req):
|
||||
yield ev.model_dump_json(exclude_none=True) + "\n"
|
||||
|
||||
return StreamingResponse(
|
||||
lines(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
+289
-87
@@ -1,7 +1,14 @@
|
||||
"""Cheapest Travelodge (room + TfL transport) for a stay in London.
|
||||
|
||||
Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged;
|
||||
only the CLI/report/CSV plumbing has been removed.
|
||||
the plumbing around it has been rewritten for speed:
|
||||
|
||||
* Travelodge result pages are fetched in parallel batches.
|
||||
* TfL journeys are fetched by a worker pool, 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
|
||||
@@ -19,11 +26,16 @@ Method
|
||||
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.
|
||||
5. Rank by room + round-trip transport. Cycling time is reported separately
|
||||
(TfL cycle routing with an app key, otherwise a distance-based estimate).
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import date, datetime
|
||||
|
||||
import requests
|
||||
@@ -53,7 +65,27 @@ 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. Nginx cuts the connection at
|
||||
# 300s, so stop pricing transport well before that and return what we have.
|
||||
SEARCH_DEADLINE_S = 240
|
||||
SEARCH_DEADLINE_S = 200
|
||||
|
||||
# Travelodge returns 10 hotels per page whatever you ask for; fetch pages in
|
||||
# parallel batches until a batch comes back with nothing new.
|
||||
TL_PAGE_SIZE = 10
|
||||
TL_PAGE_BATCH = 6
|
||||
TL_MAX_START = 500
|
||||
|
||||
# TfL: anonymous callers get 50 requests/min, keyed callers 500/min.
|
||||
TFL_WORKERS = 8
|
||||
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.
|
||||
CYCLE_ROUTE_FACTOR = 1.3
|
||||
CYCLE_KMH = 14.0
|
||||
|
||||
_session = requests.Session()
|
||||
_session.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=TFL_WORKERS + TL_PAGE_BATCH))
|
||||
|
||||
|
||||
class UpstreamError(Exception):
|
||||
@@ -103,41 +135,61 @@ def parse_origin(spec):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Travelodge
|
||||
# --------------------------------------------------------------------------- #
|
||||
def fetch_hotels(location, checkin, checkout, rooms, page_size=10):
|
||||
def _fetch_page(params, start):
|
||||
p = dict(params, start=start)
|
||||
try:
|
||||
r = _session.get(TL_API, params=p, headers=HEADERS, timeout=30)
|
||||
r.raise_for_status()
|
||||
return r.json().get("results") or []
|
||||
except (requests.RequestException, ValueError, AttributeError) as e:
|
||||
raise UpstreamError(f"Travelodge search failed: {e}") from e
|
||||
|
||||
|
||||
def fetch_hotels(location, checkin, checkout, rooms):
|
||||
"""Return list of hotel dicts from the Travelodge search API (all pages).
|
||||
|
||||
rooms: list of (adults, children) tuples, one per room.
|
||||
"""
|
||||
hotels, start, seen = [], 0, set()
|
||||
while True:
|
||||
params = {
|
||||
"pagination": "false",
|
||||
"checkIn": checkin.isoformat(),
|
||||
"checkOut": checkout.isoformat(),
|
||||
"q": location,
|
||||
"action": "hotel_amend",
|
||||
"start": start,
|
||||
}
|
||||
for i, (adults, children) in enumerate(rooms):
|
||||
params[f"rooms[{i}][adults]"] = adults
|
||||
params[f"rooms[{i}][children]"] = children
|
||||
try:
|
||||
r = requests.get(TL_API, params=params, headers=HEADERS, timeout=30)
|
||||
r.raise_for_status()
|
||||
results = r.json().get("results") or []
|
||||
except (requests.RequestException, ValueError, AttributeError) as e:
|
||||
raise UpstreamError(f"Travelodge search failed: {e}") from e
|
||||
if not results:
|
||||
break
|
||||
params = {
|
||||
"pagination": "false",
|
||||
"checkIn": checkin.isoformat(),
|
||||
"checkOut": checkout.isoformat(),
|
||||
"q": location,
|
||||
"action": "hotel_amend",
|
||||
}
|
||||
for i, (adults, children) in enumerate(rooms):
|
||||
params[f"rooms[{i}][adults]"] = adults
|
||||
params[f"rooms[{i}][children]"] = children
|
||||
|
||||
hotels, seen = [], set()
|
||||
|
||||
def absorb(results):
|
||||
new = [h for h in results if h.get("code") and h.get("code") not in seen]
|
||||
if not new:
|
||||
break
|
||||
for h in new:
|
||||
seen.add(h["code"])
|
||||
hotels.extend(new)
|
||||
start += page_size
|
||||
if start > 500: # safety
|
||||
break
|
||||
return bool(new)
|
||||
|
||||
# First page alone: tells us whether the search matched anything at all.
|
||||
first = _fetch_page(params, 0)
|
||||
if not absorb(first) or len(first) < TL_PAGE_SIZE:
|
||||
return hotels
|
||||
|
||||
start = TL_PAGE_SIZE
|
||||
with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex:
|
||||
while start <= TL_MAX_START:
|
||||
starts = [start + i * TL_PAGE_SIZE for i in range(TL_PAGE_BATCH)]
|
||||
pages = list(ex.map(lambda s: _fetch_page(params, s), starts))
|
||||
got_new = False
|
||||
exhausted = False
|
||||
for page in pages: # keep API order so ranking stays stable
|
||||
if absorb(page):
|
||||
got_new = True
|
||||
if len(page) < TL_PAGE_SIZE:
|
||||
exhausted = True
|
||||
if not got_new or exhausted:
|
||||
break
|
||||
start += TL_PAGE_SIZE * TL_PAGE_BATCH
|
||||
return hotels
|
||||
|
||||
|
||||
@@ -157,6 +209,22 @@ def normalise_hotel(h):
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Geometry
|
||||
# --------------------------------------------------------------------------- #
|
||||
def haversine_km(a, b):
|
||||
lat1, lon1 = map(math.radians, a)
|
||||
lat2, lon2 = map(math.radians, b)
|
||||
h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
|
||||
return 2 * 6371.0 * math.asin(math.sqrt(h))
|
||||
|
||||
|
||||
def estimate_cycle(origin, dest):
|
||||
"""(minutes, km) for cycling from origin to dest, from straight-line distance."""
|
||||
km = haversine_km(origin, dest) * CYCLE_ROUTE_FACTOR
|
||||
return max(1, round(km / CYCLE_KMH * 60)), round(km, 1)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# TfL
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -218,6 +286,47 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
return out, ret, " > ".join(parts) if parts else "walk"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""Sliding-window limiter: at most `per_minute` acquisitions in any 60s."""
|
||||
|
||||
def __init__(self, per_minute):
|
||||
self.per_minute = per_minute
|
||||
self._times = deque()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def acquire(self, deadline=None):
|
||||
"""Block until a slot is free. Returns False if `deadline` would pass first."""
|
||||
while True:
|
||||
with self._lock:
|
||||
now = time.monotonic()
|
||||
while self._times and self._times[0] <= now - 60:
|
||||
self._times.popleft()
|
||||
if len(self._times) < self.per_minute:
|
||||
self._times.append(now)
|
||||
return True
|
||||
wait = self._times[0] + 60 - now
|
||||
if deadline is not None and now + wait > deadline:
|
||||
return False
|
||||
time.sleep(min(wait, 1.0))
|
||||
|
||||
|
||||
_limiters = {}
|
||||
_limiters_lock = threading.Lock()
|
||||
|
||||
|
||||
def _limiter(app_key):
|
||||
rate = TFL_RATE_KEYED if app_key else TFL_RATE_ANON
|
||||
with _limiters_lock:
|
||||
lim = _limiters.get(rate)
|
||||
if lim is None:
|
||||
lim = _limiters[rate] = RateLimiter(rate)
|
||||
return lim
|
||||
|
||||
|
||||
_tfl_cache = {} # key -> (expires_at, journeys)
|
||||
_tfl_cache_lock = threading.Lock()
|
||||
|
||||
|
||||
def sleep_within(seconds, deadline):
|
||||
"""Sleep for `seconds` unless that would overrun `deadline` (a time.monotonic()
|
||||
value, or None for no limit). Returns False if the sleep was skipped."""
|
||||
@@ -228,6 +337,7 @@ def sleep_within(seconds, deadline):
|
||||
|
||||
|
||||
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None):
|
||||
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited."""
|
||||
params = {
|
||||
"date": when.strftime("%Y%m%d"),
|
||||
"time": when.strftime("%H%M"),
|
||||
@@ -236,43 +346,79 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
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())))
|
||||
now = time.monotonic()
|
||||
with _tfl_cache_lock:
|
||||
hit = _tfl_cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
|
||||
if app_key:
|
||||
params["app_key"] = app_key
|
||||
url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}")
|
||||
limiter = _limiter(app_key)
|
||||
journeys = None
|
||||
for attempt in range(retries):
|
||||
remaining = 40 if deadline is None else deadline - time.monotonic()
|
||||
if remaining < 1:
|
||||
return []
|
||||
if remaining < 1 or not limiter.acquire(deadline):
|
||||
break
|
||||
try:
|
||||
r = requests.get(url, params=params, headers=HEADERS, timeout=min(40, remaining))
|
||||
r = _session.get(url, params=params, headers=HEADERS, timeout=min(40, max(1, remaining)))
|
||||
except requests.RequestException:
|
||||
if not sleep_within(2, deadline):
|
||||
return []
|
||||
break
|
||||
continue
|
||||
if r.status_code == 429:
|
||||
if not sleep_within(10 * (attempt + 1), deadline):
|
||||
return []
|
||||
if not sleep_within(5 * (attempt + 1), deadline):
|
||||
break
|
||||
continue
|
||||
if r.status_code >= 500:
|
||||
if not sleep_within(2, deadline):
|
||||
return []
|
||||
break
|
||||
continue
|
||||
if r.status_code != 200:
|
||||
return []
|
||||
journeys = [] # e.g. 300 "disambiguation": no usable route
|
||||
break
|
||||
try:
|
||||
return r.json().get("journeys") or []
|
||||
journeys = r.json().get("journeys") or []
|
||||
except ValueError:
|
||||
return []
|
||||
return []
|
||||
journeys = []
|
||||
break
|
||||
|
||||
if journeys is None:
|
||||
return [] # gave up: don't cache a failure
|
||||
with _tfl_cache_lock:
|
||||
if len(_tfl_cache) > 5000:
|
||||
expired = [k for k, (exp, _) in _tfl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _tfl_cache[k]
|
||||
_tfl_cache[key] = (time.monotonic() + TFL_CACHE_TTL_S, journeys)
|
||||
return journeys
|
||||
|
||||
|
||||
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, pause=1.2, deadline=None):
|
||||
"""Cheapest acceptable round-trip transport to a hotel. Returns dict or None."""
|
||||
TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
|
||||
CYCLE_QUERY = {"mode": "cycle"}
|
||||
|
||||
|
||||
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, deadline=None, pool=None):
|
||||
"""Cheapest acceptable round-trip transport to a hotel. Returns dict or None.
|
||||
|
||||
Runs the fast and bus-only TfL queries concurrently on `pool` when given.
|
||||
"""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
|
||||
def query(q):
|
||||
return tfl_journeys(origin, dest, when, q[1], app_key, deadline=deadline)
|
||||
|
||||
if pool is not None:
|
||||
results = list(pool.map(query, TRANSPORT_QUERIES))
|
||||
else:
|
||||
results = [query(q) for q in TRANSPORT_QUERIES]
|
||||
|
||||
options = []
|
||||
queries = (("fast", None), ("bus", {"mode": "bus,walking"}))
|
||||
for i, (label, extra) in enumerate(queries):
|
||||
for j in tfl_journeys(origin, dest, when, extra, app_key, deadline=deadline):
|
||||
for (label, _), journeys in zip(TRANSPORT_QUERIES, results):
|
||||
for j in journeys:
|
||||
if not isinstance(j.get("duration"), int):
|
||||
continue
|
||||
priced = price_journey(j, adults, railcard_holders)
|
||||
@@ -287,8 +433,6 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
|
||||
"minutes": j["duration"],
|
||||
"route": desc,
|
||||
})
|
||||
if i < len(queries) - 1: # pause between TfL calls, not after the last
|
||||
sleep_within(pause, deadline)
|
||||
if not options:
|
||||
return None
|
||||
fastest = min(options, key=lambda o: o["minutes"])
|
||||
@@ -300,9 +444,54 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
|
||||
return cheapest
|
||||
|
||||
|
||||
def cycle_time(origin, hotel, when, app_key, deadline=None):
|
||||
"""(minutes, km, source) for cycling to the hotel. TfL routing only with an app key."""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
est_min, est_km = estimate_cycle(origin, dest)
|
||||
if not app_key:
|
||||
return est_min, est_km, "estimate"
|
||||
for j in tfl_journeys(origin, dest, when, CYCLE_QUERY, app_key, deadline=deadline):
|
||||
if isinstance(j.get("duration"), int):
|
||||
km = sum((l.get("distance") or 0) for l in (j.get("legs") or [])) / 1000
|
||||
return j["duration"], round(km, 1) if km else est_km, "tfl"
|
||||
return est_min, est_km, "estimate"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Search
|
||||
# --------------------------------------------------------------------------- #
|
||||
_UNPRICED = {
|
||||
"transport_out": None,
|
||||
"transport_return": None,
|
||||
"transport_total": None,
|
||||
"travel_minutes": None,
|
||||
"fastest_minutes": None,
|
||||
"fastest_total": None,
|
||||
"fastest_route": None,
|
||||
"total": None,
|
||||
}
|
||||
|
||||
|
||||
def _transport_fields(hotel, t):
|
||||
if not t:
|
||||
return dict(_UNPRICED, route="no TfL fare found")
|
||||
return {
|
||||
"transport_out": t["outbound_p"] / 100,
|
||||
"transport_return": t["return_p"] / 100,
|
||||
"transport_total": t["total_p"] / 100,
|
||||
"travel_minutes": t["minutes"],
|
||||
"route": t["route"],
|
||||
"fastest_minutes": t["fastest_minutes"],
|
||||
"fastest_total": t["fastest_total_p"] / 100,
|
||||
"fastest_route": t["fastest_route"],
|
||||
"total": round(hotel["room_price"] + t["total_p"] / 100, 2),
|
||||
}
|
||||
|
||||
|
||||
def sort_rows(rows):
|
||||
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
|
||||
|
||||
|
||||
def run_search(
|
||||
*,
|
||||
location: str,
|
||||
@@ -317,7 +506,14 @@ def run_search(
|
||||
max_miles,
|
||||
max_travel_min: int,
|
||||
):
|
||||
"""Everything main() in the original script did between parsing and reporting."""
|
||||
"""Generator of progress events for one search.
|
||||
|
||||
Yields, in order:
|
||||
("hotels", summary, rows) every shortlisted hotel with room price and
|
||||
cycling time but transport still unpriced
|
||||
("transport", row) one per hotel as TfL prices come back
|
||||
("done", summary, rows) final summary and rows sorted by total
|
||||
"""
|
||||
nights = (checkout - checkin).days
|
||||
adults = sum(a for a, _ in rooms)
|
||||
children = sum(c for _, c in rooms)
|
||||
@@ -329,7 +525,7 @@ def run_search(
|
||||
|
||||
raw = fetch_hotels(location, checkin, checkout, rooms)
|
||||
hotels = [normalise_hotel(h) for h in raw]
|
||||
avail = [h for h in hotels if h["available"] and h["room_price"]]
|
||||
avail = [h for h in hotels if h["available"] and h["room_price"] and h["lat"] is not None and h["lon"] is not None]
|
||||
if max_miles is not None:
|
||||
avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles]
|
||||
|
||||
@@ -337,42 +533,13 @@ def run_search(
|
||||
shortlist = avail[:top]
|
||||
|
||||
rows = []
|
||||
truncated = False
|
||||
by_code = {}
|
||||
for h in shortlist:
|
||||
skipped = time.monotonic() >= deadline
|
||||
if skipped:
|
||||
truncated = True
|
||||
t = None
|
||||
else:
|
||||
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline=deadline)
|
||||
row = dict(h)
|
||||
if t:
|
||||
row.update({
|
||||
"transport_out": t["outbound_p"] / 100,
|
||||
"transport_return": t["return_p"] / 100,
|
||||
"transport_total": t["total_p"] / 100,
|
||||
"travel_minutes": t["minutes"],
|
||||
"route": t["route"],
|
||||
"fastest_minutes": t["fastest_minutes"],
|
||||
"fastest_total": t["fastest_total_p"] / 100,
|
||||
"fastest_route": t["fastest_route"],
|
||||
"total": round(h["room_price"] + t["total_p"] / 100, 2),
|
||||
})
|
||||
else:
|
||||
row.update({
|
||||
"transport_out": None,
|
||||
"transport_return": None,
|
||||
"transport_total": None,
|
||||
"travel_minutes": None,
|
||||
"route": "not priced (time limit)" if skipped else "no TfL fare found",
|
||||
"fastest_minutes": None,
|
||||
"fastest_total": None,
|
||||
"fastest_route": None,
|
||||
"total": None,
|
||||
})
|
||||
row = dict(h, **_UNPRICED, route="pricing…")
|
||||
est_min, est_km = estimate_cycle(origin, (h["lat"], h["lon"]))
|
||||
row.update({"cycle_minutes": est_min, "cycle_km": est_km, "cycle_source": "estimate"})
|
||||
rows.append(row)
|
||||
|
||||
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
|
||||
by_code[row["code"]] = row
|
||||
|
||||
summary = {
|
||||
"location": location,
|
||||
@@ -390,7 +557,42 @@ def run_search(
|
||||
"max_travel_min": max_travel_min,
|
||||
"hotels_found": len(hotels),
|
||||
"hotels_available": len(avail),
|
||||
"hotels_priced": len(rows),
|
||||
"truncated": truncated,
|
||||
"hotels_priced": 0,
|
||||
"hotels_shortlisted": len(rows),
|
||||
"tfl_rate_per_min": TFL_RATE_KEYED if app_key else TFL_RATE_ANON,
|
||||
"truncated": False,
|
||||
}
|
||||
return {"summary": summary, "rows": rows}
|
||||
yield "hotels", dict(summary), [dict(r) for r in rows]
|
||||
|
||||
priced = 0
|
||||
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as tfl_pool, \
|
||||
ThreadPoolExecutor(max_workers=TFL_WORKERS // 2) as hotel_pool:
|
||||
|
||||
def price(h):
|
||||
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key,
|
||||
deadline=deadline, pool=tfl_pool)
|
||||
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline) if app_key else None
|
||||
return h["code"], t, cyc
|
||||
|
||||
# Submit cheapest rooms first so the most useful rows arrive earliest.
|
||||
futures = [hotel_pool.submit(price, h) for h in shortlist]
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
code, t, cyc = fut.result()
|
||||
row = by_code[code]
|
||||
timed_out = t is None and time.monotonic() >= deadline
|
||||
row.update(_transport_fields(row, t))
|
||||
if timed_out:
|
||||
row["route"] = "not priced (time limit)"
|
||||
summary["truncated"] = True
|
||||
if cyc:
|
||||
row["cycle_minutes"], row["cycle_km"], row["cycle_source"] = cyc
|
||||
priced += 1
|
||||
summary["hotels_priced"] = priced
|
||||
yield "transport", dict(row)
|
||||
finally:
|
||||
for f in futures:
|
||||
f.cancel()
|
||||
|
||||
sort_rows(rows)
|
||||
yield "done", dict(summary), [dict(r) for r in rows]
|
||||
|
||||
@@ -7,6 +7,13 @@ import InlineLink from "@/components/text/InlineLink.vue";
|
||||
const STORAGE_KEY = "cheap-hotels-config";
|
||||
const CUSTOM_ORIGIN = "__custom__";
|
||||
|
||||
const RANKINGS = [
|
||||
{ key: "total", label: "Stay + transport" },
|
||||
{ key: "room", label: "Stay only" },
|
||||
{ key: "cycle", label: "Cycle time" },
|
||||
{ key: "minutes", label: "Travel time" },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form state
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -25,9 +32,10 @@ const railcardHolders = ref(1);
|
||||
const originKey = ref("clapham junction");
|
||||
const customOrigin = ref("");
|
||||
const depart = ref("19:30");
|
||||
const top = ref(15);
|
||||
const top = ref(20);
|
||||
const maxMiles = ref("");
|
||||
const maxTravelMin = ref(75);
|
||||
const rankBy = ref("total");
|
||||
|
||||
const origins = ref([]);
|
||||
|
||||
@@ -36,23 +44,91 @@ const origins = ref([]);
|
||||
// ---------------------------------------------------------------------------
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const result = ref(null);
|
||||
const summary = ref(null);
|
||||
const rows = ref([]);
|
||||
const cached = ref(false);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return "Searching";
|
||||
if (result.value) return "Done";
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
});
|
||||
|
||||
const bestRow = computed(
|
||||
() => result.value?.rows.find((r) => r.total !== null) ?? null,
|
||||
const pricedCount = computed(
|
||||
() => rows.value.filter((r) => r.total !== null || r.route !== "pricing…").length,
|
||||
);
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
function byNumber(get, tiebreak) {
|
||||
return (a, b) => {
|
||||
const x = get(a);
|
||||
const y = get(b);
|
||||
const xNull = x === null || x === undefined;
|
||||
const yNull = y === null || y === undefined;
|
||||
if (xNull !== yNull) return xNull ? 1 : -1;
|
||||
if (!xNull && x !== y) return x - y;
|
||||
return tiebreak ? tiebreak(a, b) : 0;
|
||||
};
|
||||
}
|
||||
|
||||
const byRoom = byNumber((r) => r.room_price);
|
||||
const byTotal = byNumber((r) => r.total, byRoom);
|
||||
const byCycle = byNumber((r) => r.cycle_minutes, byRoom);
|
||||
const byMinutes = byNumber((r) => r.travel_minutes, byTotal);
|
||||
|
||||
const sortedRows = computed(() => {
|
||||
const cmp = { total: byTotal, room: byRoom, cycle: byCycle, minutes: byMinutes }[
|
||||
rankBy.value
|
||||
];
|
||||
return [...rows.value].sort(cmp);
|
||||
});
|
||||
|
||||
function firstBy(cmp, ok) {
|
||||
const list = rows.value.filter(ok);
|
||||
if (!list.length) return null;
|
||||
return list.reduce((best, r) => (cmp(r, best) < 0 ? r : best));
|
||||
}
|
||||
|
||||
const picks = computed(() => {
|
||||
const p = [];
|
||||
const best = firstBy(byTotal, (r) => r.total !== null);
|
||||
if (best)
|
||||
p.push({
|
||||
label: "Best value",
|
||||
row: best,
|
||||
maths: `${gbp(best.room_price)} stay + ${gbp(best.transport_total)} travel = ${gbp(best.total)}`,
|
||||
sub: `${best.travel_minutes} min by ${best.route}`,
|
||||
});
|
||||
const room = firstBy(byRoom, (r) => r.room_price !== null);
|
||||
if (room)
|
||||
p.push({
|
||||
label: "Cheapest room",
|
||||
row: room,
|
||||
maths: `${gbp(room.room_price)} for the stay`,
|
||||
sub:
|
||||
room.total !== null
|
||||
? `${gbp(room.total)} with transport (${room.travel_minutes} min)`
|
||||
: "transport not priced yet",
|
||||
});
|
||||
const cycle = firstBy(byCycle, (r) => r.cycle_minutes !== null);
|
||||
if (cycle)
|
||||
p.push({
|
||||
label: "Quickest cycle",
|
||||
row: cycle,
|
||||
maths: `${cycleText(cycle)} ride, ${gbp(cycle.room_price)} stay`,
|
||||
sub: `${cycle.cycle_km} km from ${summary.value?.origin_name ?? "origin"}`,
|
||||
});
|
||||
return p;
|
||||
});
|
||||
|
||||
const summaryText = computed(() => {
|
||||
const s = result.value?.summary;
|
||||
const s = summary.value;
|
||||
if (!s) return "";
|
||||
const party =
|
||||
`${s.adults} adult${s.adults === 1 ? "" : "s"}` +
|
||||
@@ -62,10 +138,10 @@ const summaryText = computed(() => {
|
||||
? ` (${s.railcard_holders} with railcard)`
|
||||
: "";
|
||||
return (
|
||||
`${s.hotels_priced} of ${s.hotels_available} available Travelodges near ` +
|
||||
`Cheapest ${rows.value.length} of ${s.hotels_available} available Travelodges near ` +
|
||||
`'${s.location}', ${fmtDate(s.checkin)} → ${fmtDate(s.checkout)} ` +
|
||||
`(${s.nights} night${s.nights === 1 ? "" : "s"}, ${party}), ` +
|
||||
`incl. round-trip transport from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.`
|
||||
`with round-trip transport from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.`
|
||||
);
|
||||
});
|
||||
|
||||
@@ -92,6 +168,18 @@ function fmtTime(iso) {
|
||||
});
|
||||
}
|
||||
|
||||
function cycleText(r) {
|
||||
if (r.cycle_minutes === null || r.cycle_minutes === undefined) return "";
|
||||
return `${r.cycle_source === "estimate" ? "~" : ""}${r.cycle_minutes} min`;
|
||||
}
|
||||
|
||||
function cycleTitle(r) {
|
||||
if (r.cycle_minutes === null || r.cycle_minutes === undefined) return "";
|
||||
return r.cycle_source === "estimate"
|
||||
? `about ${r.cycle_km} km; estimated from distance at a gentle pace`
|
||||
: `${r.cycle_km} km on TfL's cycle route`;
|
||||
}
|
||||
|
||||
function showFaster(r) {
|
||||
return (
|
||||
r.fastest_minutes !== null &&
|
||||
@@ -119,6 +207,7 @@ function saveConfig() {
|
||||
top: top.value,
|
||||
maxMiles: maxMiles.value,
|
||||
maxTravelMin: maxTravelMin.value,
|
||||
rankBy: rankBy.value,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
@@ -138,9 +227,10 @@ function loadConfig() {
|
||||
originKey.value = c.originKey ?? originKey.value;
|
||||
customOrigin.value = c.customOrigin ?? customOrigin.value;
|
||||
depart.value = c.depart ?? depart.value;
|
||||
top.value = c.top ?? top.value;
|
||||
top.value = Math.min(40, c.top ?? top.value);
|
||||
maxMiles.value = c.maxMiles ?? maxMiles.value;
|
||||
maxTravelMin.value = c.maxTravelMin ?? maxTravelMin.value;
|
||||
if (RANKINGS.some((r) => r.key === c.rankBy)) rankBy.value = c.rankBy;
|
||||
// Only restore the date if it is still in the future.
|
||||
if (c.checkin && c.checkin >= new Date().toISOString().slice(0, 10))
|
||||
checkin.value = c.checkin;
|
||||
@@ -175,6 +265,8 @@ function buildRequest() {
|
||||
function describeError(status, payload) {
|
||||
if (status === 429)
|
||||
return "Someone else is searching right now, try again shortly.";
|
||||
if (status === 503)
|
||||
return "Too many searches from your address, wait a minute and retry.";
|
||||
const detail = payload?.detail;
|
||||
if (Array.isArray(detail))
|
||||
return detail
|
||||
@@ -184,33 +276,99 @@ function describeError(status, payload) {
|
||||
return `Search failed (${status}).`;
|
||||
}
|
||||
|
||||
function applyEvent(ev) {
|
||||
switch (ev.event) {
|
||||
case "hotels":
|
||||
summary.value = ev.summary;
|
||||
rows.value = ev.rows;
|
||||
cached.value = !!ev.cached;
|
||||
break;
|
||||
case "transport": {
|
||||
const existing = rows.value.find((r) => r.code === ev.row.code);
|
||||
if (existing) Object.assign(existing, ev.row);
|
||||
else rows.value.push(ev.row);
|
||||
break;
|
||||
}
|
||||
case "done":
|
||||
summary.value = ev.summary;
|
||||
rows.value = ev.rows;
|
||||
cached.value = !!ev.cached;
|
||||
done.value = true;
|
||||
break;
|
||||
case "error":
|
||||
errorMsg.value = ev.detail || "Search failed.";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function readStream(res) {
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
const handleChunk = (text, final) => {
|
||||
buffer += text;
|
||||
const lines = buffer.split("\n");
|
||||
buffer = final ? "" : lines.pop();
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
applyEvent(JSON.parse(line));
|
||||
} catch {
|
||||
/* skip a malformed line rather than abort the whole search */
|
||||
}
|
||||
}
|
||||
};
|
||||
if (!res.body?.getReader) {
|
||||
handleChunk(await res.text(), true);
|
||||
return;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { value, done: finished } = await reader.read();
|
||||
if (finished) break;
|
||||
handleChunk(decoder.decode(value, { stream: true }), false);
|
||||
}
|
||||
handleChunk(decoder.decode(), true);
|
||||
}
|
||||
|
||||
async function onSearch() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
result.value = null;
|
||||
summary.value = null;
|
||||
rows.value = [];
|
||||
cached.value = false;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
saveConfig();
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
const res = await fetch("/py/hotels/search", {
|
||||
const res = await fetch("/py/hotels/search/stream", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(buildRequest()),
|
||||
signal: aborter.signal,
|
||||
});
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await res.json();
|
||||
} catch {
|
||||
/* non-JSON body (e.g. nginx timeout page) */
|
||||
if (!res.ok) {
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await res.json();
|
||||
} catch {
|
||||
/* non-JSON body (e.g. nginx error page) */
|
||||
}
|
||||
throw new Error(describeError(res.status, payload));
|
||||
}
|
||||
if (!res.ok) throw new Error(describeError(res.status, payload));
|
||||
result.value = payload;
|
||||
await readStream(res);
|
||||
if (!done.value && !errorMsg.value)
|
||||
errorMsg.value = "The search ended early; showing what came back.";
|
||||
} catch (e) {
|
||||
errorMsg.value = e.message || "Search failed.";
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || "Search failed.";
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
@@ -237,16 +395,17 @@ onMounted(() => {
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="flex justify-center px-4 py-10">
|
||||
<div class="max-w-4xl w-full flex flex-col gap-6">
|
||||
<div class="max-w-5xl w-full flex flex-col gap-6">
|
||||
<section>
|
||||
<Header>Cheap Travelodge Finder</Header>
|
||||
<Paragraph>
|
||||
Finds the cheapest Travelodge for a stay in London
|
||||
Ranks the cheapest Travelodges for a stay in London
|
||||
<em>including the cost of getting there and back</em> from
|
||||
a chosen station, so a £45 room forty minutes out can be
|
||||
compared fairly with a £90 room in Zone 1. Room prices come
|
||||
@@ -255,7 +414,8 @@ onBeforeUnmount(() => {
|
||||
href="https://tfl.gov.uk/plan-a-journey/"
|
||||
target="_blank"
|
||||
>TfL Journey Planner</InlineLink
|
||||
>.
|
||||
>. Every hotel also gets a cycling time from the origin, for
|
||||
when the bike is the cheapest transport of all.
|
||||
</Paragraph>
|
||||
</section>
|
||||
|
||||
@@ -343,10 +503,11 @@ onBeforeUnmount(() => {
|
||||
type="number"
|
||||
v-model.number="top"
|
||||
min="1"
|
||||
max="25"
|
||||
max="40"
|
||||
/>
|
||||
<span class="hint"
|
||||
>N cheapest by room rate; fewer is faster</span
|
||||
>N cheapest by room rate; TfL allows about 24
|
||||
hotels a minute</span
|
||||
>
|
||||
</label>
|
||||
<label>
|
||||
@@ -385,8 +546,8 @@ onBeforeUnmount(() => {
|
||||
>{{ elapsed }}s</span
|
||||
>
|
||||
<span class="note">
|
||||
Takes about a minute: every hotel is priced on TfL
|
||||
twice.
|
||||
Hotels appear within a couple of seconds; transport
|
||||
prices fill in as TfL answers.
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
@@ -394,94 +555,141 @@ onBeforeUnmount(() => {
|
||||
<p v-if="errorMsg" class="errorBox">{{ errorMsg }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="result" class="panel">
|
||||
<section v-if="hasResults" class="panel">
|
||||
<h2 class="panelTitle">
|
||||
Results
|
||||
<span v-if="result.cached" class="cachedTag">cached</span>
|
||||
<span v-if="cached" class="cachedTag">cached</span>
|
||||
<span v-if="summary.truncated" class="cachedTag warn"
|
||||
>time limit hit</span
|
||||
>
|
||||
</h2>
|
||||
<p class="summary">{{ summaryText }}</p>
|
||||
|
||||
<div v-if="bestRow" class="best">
|
||||
<span class="bestLabel">Best value</span>
|
||||
<span class="bestName">{{ bestRow.name }}</span>
|
||||
<span class="bestMaths">
|
||||
{{ gbp(bestRow.room_price) }} stay +
|
||||
{{ gbp(bestRow.transport_total) }} travel =
|
||||
<strong>{{ gbp(bestRow.total) }}</strong>
|
||||
<div class="progress" v-if="rows.length">
|
||||
<div class="progressBar">
|
||||
<div
|
||||
class="progressFill"
|
||||
:style="{ width: `${(100 * pricedCount) / rows.length}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<span class="progressText">
|
||||
{{ pricedCount }} / {{ rows.length }} priced on TfL
|
||||
</span>
|
||||
<a
|
||||
class="bookLink"
|
||||
:href="bestRow.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>Book →</a
|
||||
>
|
||||
</div>
|
||||
|
||||
<p v-if="!result.rows.length" class="note">
|
||||
<div v-if="picks.length" class="picks">
|
||||
<div v-for="p in picks" :key="p.label" class="pick">
|
||||
<span class="pickLabel">{{ p.label }}</span>
|
||||
<a
|
||||
class="pickName"
|
||||
:href="p.row.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ p.row.name }}</a
|
||||
>
|
||||
<span class="pickMaths">{{ p.maths }}</span>
|
||||
<span class="pickSub">{{ p.sub }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="!rows.length" class="note">
|
||||
No hotels with availability matched that search.
|
||||
</p>
|
||||
|
||||
<div v-else class="tableWrap">
|
||||
<table class="results">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th class="num">Total</th>
|
||||
<th class="num">Stay</th>
|
||||
<th class="num">Travel</th>
|
||||
<th class="num">Mins</th>
|
||||
<th>Hotel</th>
|
||||
<th>Route (cheapest acceptable)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="(r, i) in result.rows" :key="r.code">
|
||||
<tr :class="{ best: r === bestRow, unpriced: r.total === null }">
|
||||
<td class="num">{{ i + 1 }}</td>
|
||||
<td class="num total">{{ gbp(r.total) }}</td>
|
||||
<td class="num">{{ gbp(r.room_price) }}</td>
|
||||
<td class="num">{{ gbp(r.transport_total) }}</td>
|
||||
<td class="num">{{ r.travel_minutes ?? "" }}</td>
|
||||
<td>
|
||||
<a
|
||||
:href="r.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hotelLink"
|
||||
>{{ r.name }}</a
|
||||
>
|
||||
<span v-if="r.low_availability" class="lowTag"
|
||||
>low availability</span
|
||||
>
|
||||
</td>
|
||||
<td class="route">{{ r.route }}</td>
|
||||
<template v-else>
|
||||
<div class="rankBar">
|
||||
<span class="rankLabel">Rank by</span>
|
||||
<button
|
||||
v-for="r in RANKINGS"
|
||||
:key="r.key"
|
||||
type="button"
|
||||
class="rankBtn"
|
||||
:class="{ active: rankBy === r.key }"
|
||||
@click="rankBy = r.key; saveConfig()"
|
||||
>
|
||||
{{ r.label }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="tableWrap">
|
||||
<table class="results">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'total' }">Total</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'room' }">Stay</th>
|
||||
<th class="num">Travel</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'minutes' }">Mins</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'cycle' }">Cycle</th>
|
||||
<th>Hotel</th>
|
||||
<th>Route (cheapest acceptable)</th>
|
||||
</tr>
|
||||
<tr v-if="showFaster(r)" class="fasterRow">
|
||||
<td colspan="6"></td>
|
||||
<td class="route">
|
||||
faster: {{ r.fastest_minutes }} min for
|
||||
{{ gbp(r.fastest_total) }} return via
|
||||
{{ r.fastest_route }}
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="(r, i) in sortedRows" :key="r.code">
|
||||
<tr
|
||||
:class="{
|
||||
best: i === 0,
|
||||
unpriced: r.total === null,
|
||||
}"
|
||||
>
|
||||
<td class="num">{{ i + 1 }}</td>
|
||||
<td class="num total">{{ gbp(r.total) }}</td>
|
||||
<td class="num stay">{{ gbp(r.room_price) }}</td>
|
||||
<td class="num">{{ gbp(r.transport_total) }}</td>
|
||||
<td class="num">{{ r.travel_minutes ?? "" }}</td>
|
||||
<td class="num cycle" :title="cycleTitle(r)">
|
||||
{{ cycleText(r) }}
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
:href="r.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hotelLink"
|
||||
>{{ r.name }}</a
|
||||
>
|
||||
<span v-if="r.low_availability" class="lowTag"
|
||||
>low availability</span
|
||||
>
|
||||
</td>
|
||||
<td class="route" :class="{ pending: r.route === 'pricing…' }">
|
||||
{{ r.route }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="showFaster(r)" class="fasterRow">
|
||||
<td colspan="7"></td>
|
||||
<td class="route">
|
||||
faster: {{ r.fastest_minutes }} min for
|
||||
{{ gbp(r.fastest_total) }} return via
|
||||
{{ r.fastest_route }}
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<details class="help">
|
||||
<summary>Notes</summary>
|
||||
<ul>
|
||||
<li>
|
||||
Stay price is Travelodge's cheapest room(s) for the
|
||||
whole stay and all rooms.
|
||||
whole stay and all rooms. Rank by "Stay only" to
|
||||
ignore transport entirely.
|
||||
</li>
|
||||
<li>
|
||||
Transport is the TfL adult pay-as-you-go single each
|
||||
way, multiplied by adults. The return is assumed
|
||||
off-peak (next day).
|
||||
</li>
|
||||
<li>
|
||||
Cycle time is from the origin station on your own
|
||||
bike. A "~" means it is estimated from the distance
|
||||
at about 14 km/h; without a tilde it is TfL's cycle
|
||||
route.
|
||||
</li>
|
||||
<li>
|
||||
Children 10 and under travel free on TfL; 11–15s pay
|
||||
child fares with a Zip card (not included).
|
||||
@@ -528,6 +736,11 @@ onBeforeUnmount(() => {
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.cachedTag.warn {
|
||||
color: #ffd166;
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.configGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
@@ -636,55 +849,123 @@ onBeforeUnmount(() => {
|
||||
.summary {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 0.75rem;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.best {
|
||||
.progress {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.progressBar {
|
||||
flex: 1;
|
||||
height: 4px;
|
||||
background: rgba(2, 73, 66, 0.5);
|
||||
}
|
||||
|
||||
.progressFill {
|
||||
height: 100%;
|
||||
background: var(--color-primary);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.progressText {
|
||||
font-family: monospace;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.picks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.6rem;
|
||||
margin-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.pick {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
padding: 0.5rem 0.75rem;
|
||||
margin-bottom: 0.9rem;
|
||||
background: rgba(85, 255, 187, 0.06);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bestLabel {
|
||||
.pickLabel {
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-primary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.bestName {
|
||||
.pickName {
|
||||
color: #e5f4ee;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.bestMaths {
|
||||
.pickName:hover {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
|
||||
.pickMaths {
|
||||
font-family: monospace;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-secondary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.bestMaths strong {
|
||||
.pickSub {
|
||||
font-size: 0.78rem;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.rankBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.rankLabel {
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
margin-right: 0.2rem;
|
||||
}
|
||||
|
||||
.rankBtn {
|
||||
padding: 0.15rem 0.6rem;
|
||||
border: 1px solid var(--color-quaternary);
|
||||
color: var(--color-muted);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 0.15s ease,
|
||||
border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.rankBtn:hover {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.bookLink,
|
||||
.rankBtn.active {
|
||||
color: var(--color-primary);
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.hotelLink {
|
||||
color: var(--color-primary);
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.bookLink {
|
||||
margin-left: auto;
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.bookLink:hover,
|
||||
.hotelLink:hover {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
@@ -711,6 +992,11 @@ onBeforeUnmount(() => {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.results th.sorted {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.results td {
|
||||
padding: 0.3rem 0.5rem;
|
||||
border-bottom: 1px solid rgba(2, 73, 66, 0.4);
|
||||
@@ -727,11 +1013,16 @@ onBeforeUnmount(() => {
|
||||
color: var(--color-secondary);
|
||||
}
|
||||
|
||||
.results .cycle {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.results tr.best td {
|
||||
background: rgba(85, 255, 187, 0.08);
|
||||
}
|
||||
|
||||
.results tr.unpriced td {
|
||||
.results tr.unpriced td.total,
|
||||
.results tr.unpriced td.route {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
@@ -739,6 +1030,11 @@ onBeforeUnmount(() => {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.results .route.pending {
|
||||
font-style: italic;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.fasterRow td {
|
||||
border-bottom: 1px solid rgba(2, 73, 66, 0.4);
|
||||
font-size: 0.8rem;
|
||||
@@ -782,12 +1078,9 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.configGrid {
|
||||
.configGrid,
|
||||
.picks {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.bookLink {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user