Back off a failed Jolpica ask; render posters off the event loop

Review round 1 (two findings):
- While Jolpica failed, every schedule read asked it again, up to four
  times per poster request, and the poster, thumb and grand-prix routes
  were async, so the pacing, a 429's pause and a timeout stalled every
  request. A failed ask is now remembered for ten minutes (the kept
  schedule, or none, is answered meanwhile), a schedule in memory is
  answered without waiting for an ask under way, and those routes are
  plain defs in the threadpool. A rendered picture is stored whole
  (written aside, then renamed), as two may now render it side by side.
- Bytecode was tracked: tests/__pycache__ (added with the tests) and
  models/__pycache__ that the cleanup missed. Untracked; .gitignore
  already names __pycache__/.

From the review's notes: a poster whose map or photo failed is sent with
a five-minute cache instead of a year's; uvicorn trusts the proxy's
forwarded headers, so /examples redirects to https, not http; stale
comments naming CARTO and the zoom lookup's key are corrected.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
2026-11-27 10:24:04 +01:00
parent ec94c69222
commit d9c6fdc46c
18 changed files with 79 additions and 45 deletions
+26 -24
View File
@@ -95,38 +95,44 @@ app.mount(
)
# The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for
# seconds, so it runs in the threadpool instead of holding up every other request on the event loop.
def poster_response(png: bytes, kept: bool) -> FastAPIResponse:
"""A poster the service stored is kept by clients for a year; one whose map or photo failed only
for five minutes, so they ask again once it can be rendered whole."""
return FastAPIResponse(
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000" if kept else "public, max-age=300"},
)
@app.get("/posters/race/{grand_prix_name}/{season}.png")
async def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
`?bg=` selects the backdrop:
- aerial (default) — Esri World Imagery satellite at the circuit's coords
- osm — OpenStreetMap Carto street-map at the circuit's coords
- dark — Esri Dark Gray Canvas
- light — Esri Light Gray Canvas
- none — plain black background (skip tile fetch)
"""
png = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
if not png:
rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
if not rendered:
raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}")
return FastAPIResponse(
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
return poster_response(*rendered)
@app.get("/posters/season/{season}.png")
async def get_season_poster(season: int):
def get_season_poster(season: int):
"""Plex-ready 1000x1500 season poster (PNG). Cached on disk."""
png = posters_service.render_season_poster(season)
return FastAPIResponse(
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
return poster_response(*posters_service.render_season_poster(season))
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png")
async def get_session_thumb(grand_prix_name: str, season: int, session_slug: str):
def get_session_thumb(grand_prix_name: str, season: int, session_slug: str):
"""Plex episode-thumb (1920x1080) for a specific session of a race weekend.
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying,
@@ -134,14 +140,10 @@ async def get_session_thumb(grand_prix_name: str, season: int, session_slug: str
sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
post-sprint-qualifying, bonus.
"""
png = posters_service.render_session_thumb(grand_prix_name, season, session_slug)
if not png:
rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug)
if not rendered:
raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}")
return FastAPIResponse(
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
return poster_response(*rendered)
@app.get("/kometa/formula-1-metadata.yml")
@@ -241,7 +243,7 @@ async def get_track_by_layout(
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response)
@app.get("/grand-prix/{grand_prix_name}/{season}/{image_format}")
async def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
layout = circuit_service.get_circuit_layout_by_ergast_data(grand_prix_name, season)
if not layout:
+17 -3
View File
@@ -34,6 +34,7 @@ class ErgastService:
REQUEST_INTERVAL = 0.3 # seconds between two requests: under the 4 a second
RETRIES = 3 # a throttled request (429) is asked again after a pause, at most this often
OPEN_SEASON_TTL = 6 * 3600 # a season not yet over is asked again after six hours
FAILED_BACKOFF = 600 # after a failed ask, a season is not asked again for ten minutes
# Country name normalization: Jolpica country → our country slug
country_map = {
@@ -49,6 +50,7 @@ class ErgastService:
self._circuit_id_index = self._build_circuit_id_index()
self.cache_dir = cache_dir
self._schedules: dict[int, tuple[float, list[dict]]] = {} # season → (fetched at, races)
self._failed_at: dict[int, float] = {} # season → when its last ask failed (monotonic)
self._fetch_lock = threading.Lock()
self._last_request = 0.0
@@ -73,21 +75,33 @@ class ErgastService:
"""The race schedule of a season: from memory, then from disk, then from Jolpica.
A season that is over never changes, so it is kept on disk for good; a season not yet over is
asked again after OPEN_SEASON_TTL. A failed fetch is never kept: the next call asks again, and
until it succeeds the schedule kept last is answered, or none."""
asked again after OPEN_SEASON_TTL. A failed fetch is never kept as a schedule, only its time: the
season is not asked again for FAILED_BACKOFF, and meanwhile the schedule kept last is answered, or
none. A schedule held in memory is answered without waiting for an ask under way."""
kept = self._schedules.get(season)
if kept and self._fresh(season, kept):
return kept[1]
with self._fetch_lock:
kept = self._schedules.get(season) or self._read_kept(season)
if kept and (season < date.today().year or time.time() - kept[0] < self.OPEN_SEASON_TTL):
if kept and self._fresh(season, kept):
self._schedules[season] = kept
return kept[1]
failed = self._failed_at.get(season)
if failed is not None and time.monotonic() - failed < self.FAILED_BACKOFF:
return kept[1] if kept else []
races = self._ask_jolpica(season)
if races is None:
self._failed_at[season] = time.monotonic()
return kept[1] if kept else []
self._failed_at.pop(season, None)
kept = (time.time(), races)
self._schedules[season] = kept
self._write_kept(season, kept)
return races
def _fresh(self, season: int, kept: tuple[float, list[dict]]) -> bool:
return season < date.today().year or time.time() - kept[0] < self.OPEN_SEASON_TTL
def _ask_jolpica(self, season: int) -> Optional[list[dict]]:
"""Ask Jolpica for a season's races, paced under its rate limit; None when it does not answer."""
url = f'{self.JOLPICA_BASE}/{season}.json?limit=100'
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+28 -15
View File
@@ -18,6 +18,7 @@ import json
import logging
import math
import os
import threading
import urllib.request
from enum import Enum
from pathlib import Path
@@ -154,7 +155,9 @@ class PostersService:
logger.warning("No bundled font found — poster text will use PIL's default bitmap font")
self.cache_dir = Path("cache/posters")
self.cache_dir.mkdir(parents=True, exist_ok=True)
# Pre-tuned zooms per circuit, keyed by our circuit slug (the slugified name in f1-locations.json).
# Pre-tuned zooms per circuit, keyed by the ASCII-slugified name in f1-locations.json and looked up
# by our circuit slug: they meet for ASCII names only. Unread today: every layout has a GeoJSON
# trace, and the image does not copy f1-locations.json.
# Falls back to DEFAULT_ZOOM when not found.
self._zoom_by_circuit = self._load_zoom_lookup()
@@ -320,14 +323,14 @@ class PostersService:
d = ImageDraw.Draw(img)
# Subtle dark stroke under, then the bright white line, so the outline
# stays legible whether the bg is the bright Mediterranean or a dark
# CartoDB tile.
# grey canvas tile.
d.line(pts + [pts[0]], fill=(0, 0, 0), width=10, joint="curve")
d.line(pts + [pts[0]], fill=WHITE, width=6, joint="curve")
return True
def _render_world_locator(self, lat: float, lon: float, size: int = 220) -> Optional[Image.Image]:
"""A small picture-in-picture map showing where on Earth this race is.
Uses CartoDB Dark Matter at zoom 5 — tight enough that the host country
Uses the dark background's tiles (Esri Dark Gray Canvas) at zoom 5 — tight enough that the host country
fills most of the inset, while neighbours and coastlines still give the
viewer a "here's the region" anchor. A marker (red dot + white ring)
is drawn over the exact spot."""
@@ -442,12 +445,22 @@ class PostersService:
# ------------------------------------------------------------------ race poster
@staticmethod
def _keep(cache_path: Path, data: bytes) -> None:
"""Store a rendered picture whole: two requests may render the same one side by side."""
partial = cache_path.with_name(f"{cache_path.name}.{threading.get_ident()}.partial")
partial.write_bytes(data)
partial.replace(cache_path)
# Every render_* answers (png, kept): kept is False when its map or photo failed, so the picture is
# served but not stored, and the caller tells clients not to keep it either.
def render_race_poster(
self,
grand_prix_name: str,
season: int,
bg: BackgroundStyle = BackgroundStyle.AERIAL,
) -> Optional[bytes]:
) -> Optional[tuple[bytes, bool]]:
races = self.ergast._fetch_season_schedule(season)
race = next((r for r in races if r["raceName"] == grand_prix_name), None)
if not race:
@@ -465,7 +478,7 @@ class PostersService:
cache_key = f"{season}-{round_num:02d}-{layout.slug}-{bg.value}-{POSTER_RENDER}.png"
cache_path = self.cache_dir / cache_key
if cache_path.exists():
return cache_path.read_bytes()
return cache_path.read_bytes(), True
# Fetch map background if requested; fall back to flat black if anything fails.
# One (lat, lon, zoom) for the map, the projected track and the locator, the zoom no deeper than
@@ -548,8 +561,8 @@ class PostersService:
data = buf.getvalue()
if bg is BackgroundStyle.NONE or map_bg is not None:
# A poster whose map failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data)
return data
self._keep(cache_path, data)
return data, bg is BackgroundStyle.NONE or map_bg is not None
# ------------------------------------------------------------------ session thumb (16:9)
@@ -569,7 +582,7 @@ class PostersService:
ox, oy = left - tx0 * 256, top - ty0 * 256
return canvas.crop((ox, oy, ox + THUMB_W, oy + THUMB_H))
def render_session_thumb(self, grand_prix_name: str, season: int, session_slug: str) -> Optional[bytes]:
def render_session_thumb(self, grand_prix_name: str, season: int, session_slug: str) -> Optional[tuple[bytes, bool]]:
"""1920x1080 Plex episode-thumb. Aerial of the circuit + GP name + session label."""
label = SESSION_LABEL_BY_SLUG.get(session_slug)
if not label:
@@ -587,7 +600,7 @@ class PostersService:
cache_key = f"thumb-{season}-{round_num:02d}-{layout.slug}-{session_slug}.png"
cache_path = self.cache_dir / cache_key
if cache_path.exists():
return cache_path.read_bytes()
return cache_path.read_bytes(), True
# Same per-circuit geo (lat, lon, bbox-derived zoom) as the race poster,
# so the thumb shows the same place at the same zoom level.
@@ -655,8 +668,8 @@ class PostersService:
data = buf.getvalue()
if map_bg is not None:
# A thumb whose aerial failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data)
return data
self._keep(cache_path, data)
return data, map_bg is not None
# ------------------------------------------------------------------ kometa metadata
@@ -773,10 +786,10 @@ class PostersService:
ovr[x, y] = (0, 0, 0, alpha)
return overlay
def render_season_poster(self, season: int) -> bytes:
def render_season_poster(self, season: int) -> tuple[bytes, bool]:
cache_path = self.cache_dir / f"season-{season}.png"
if cache_path.exists():
return cache_path.read_bytes()
return cache_path.read_bytes(), True
bg = self._fetch_season_background(season)
if bg is None:
@@ -798,5 +811,5 @@ class PostersService:
data = buf.getvalue()
if bg is not None:
# A poster whose photo failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data)
return data
self._keep(cache_path, data)
return data, bg is not None
+3 -1
View File
@@ -30,4 +30,6 @@ COPY examples/ ./examples/
EXPOSE 8000
CMD ["uvicorn", "cdn-api:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log"]
# The proxy (route-proxy) sets X-Forwarded-Proto and -For; trusting them makes a redirect (/examples → /examples/)
# keep https. Only the proxy reaches the port (module.json listens from the mesh).
CMD ["uvicorn", "cdn-api:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log", "--proxy-headers", "--forwarded-allow-ips", "*"]
Binary file not shown.
Binary file not shown.
+5 -2
View File
@@ -24,11 +24,14 @@ class ScheduleTest(unittest.TestCase):
service.REQUEST_INTERVAL = 0
return service
def test_a_failed_fetch_is_not_kept(self):
def test_a_failed_fetch_is_not_kept_and_not_asked_again_within_the_backoff(self):
service = self.service()
with mock.patch.object(service, "_ask_jolpica", side_effect=[None, RACES]) as ask:
self.assertEqual(service._fetch_season_schedule(2019), [])
self.assertEqual(service._fetch_season_schedule(2019), RACES)
self.assertEqual(service._fetch_season_schedule(2019), []) # within the backoff: not asked
self.assertEqual(ask.call_count, 1)
service.FAILED_BACKOFF = 0
self.assertEqual(service._fetch_season_schedule(2019), RACES) # past it: asked, and kept
self.assertEqual(ask.call_count, 2)
def test_a_season_that_is_over_is_read_from_disk(self):