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") @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). """Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
`?bg=` selects the backdrop: `?bg=` selects the backdrop:
- aerial (default) — Esri World Imagery satellite at the circuit's coords - aerial (default) — Esri World Imagery satellite at the circuit's coords
- osm — OpenStreetMap Carto street-map 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) - none — plain black background (skip tile fetch)
""" """
png = posters_service.render_race_poster(grand_prix_name, season, bg=bg) rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
if not png: if not rendered:
raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}") raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}")
return FastAPIResponse( return poster_response(*rendered)
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
@app.get("/posters/season/{season}.png") @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.""" """Plex-ready 1000x1500 season poster (PNG). Cached on disk."""
png = posters_service.render_season_poster(season) return poster_response(*posters_service.render_season_poster(season))
return FastAPIResponse(
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png") @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. """Plex episode-thumb (1920x1080) for a specific session of a race weekend.
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying, `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, sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
post-sprint-qualifying, bonus. post-sprint-qualifying, bonus.
""" """
png = posters_service.render_session_thumb(grand_prix_name, season, session_slug) rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug)
if not png: if not rendered:
raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}") raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}")
return FastAPIResponse( return poster_response(*rendered)
content=png,
media_type="image/png",
headers={"Cache-Control": "public, max-age=31536000"},
)
@app.get("/kometa/formula-1-metadata.yml") @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) 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}") @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) layout = circuit_service.get_circuit_layout_by_ergast_data(grand_prix_name, season)
if not layout: 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 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 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 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 name normalization: Jolpica country → our country slug
country_map = { country_map = {
@@ -49,6 +50,7 @@ class ErgastService:
self._circuit_id_index = self._build_circuit_id_index() self._circuit_id_index = self._build_circuit_id_index()
self.cache_dir = cache_dir self.cache_dir = cache_dir
self._schedules: dict[int, tuple[float, list[dict]]] = {} # season → (fetched at, races) 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._fetch_lock = threading.Lock()
self._last_request = 0.0 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. """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 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 asked again after OPEN_SEASON_TTL. A failed fetch is never kept as a schedule, only its time: the
until it succeeds the schedule kept last is answered, or none.""" 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: with self._fetch_lock:
kept = self._schedules.get(season) or self._read_kept(season) 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 self._schedules[season] = kept
return kept[1] 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) races = self._ask_jolpica(season)
if races is None: if races is None:
self._failed_at[season] = time.monotonic()
return kept[1] if kept else [] return kept[1] if kept else []
self._failed_at.pop(season, None)
kept = (time.time(), races) kept = (time.time(), races)
self._schedules[season] = kept self._schedules[season] = kept
self._write_kept(season, kept) self._write_kept(season, kept)
return races 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]]: 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.""" """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' 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 logging
import math import math
import os import os
import threading
import urllib.request import urllib.request
from enum import Enum from enum import Enum
from pathlib import Path 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") logger.warning("No bundled font found — poster text will use PIL's default bitmap font")
self.cache_dir = Path("cache/posters") self.cache_dir = Path("cache/posters")
self.cache_dir.mkdir(parents=True, exist_ok=True) 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. # Falls back to DEFAULT_ZOOM when not found.
self._zoom_by_circuit = self._load_zoom_lookup() self._zoom_by_circuit = self._load_zoom_lookup()
@@ -320,14 +323,14 @@ class PostersService:
d = ImageDraw.Draw(img) d = ImageDraw.Draw(img)
# Subtle dark stroke under, then the bright white line, so the outline # Subtle dark stroke under, then the bright white line, so the outline
# stays legible whether the bg is the bright Mediterranean or a dark # 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=(0, 0, 0), width=10, joint="curve")
d.line(pts + [pts[0]], fill=WHITE, width=6, joint="curve") d.line(pts + [pts[0]], fill=WHITE, width=6, joint="curve")
return True return True
def _render_world_locator(self, lat: float, lon: float, size: int = 220) -> Optional[Image.Image]: 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. """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 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) viewer a "here's the region" anchor. A marker (red dot + white ring)
is drawn over the exact spot.""" is drawn over the exact spot."""
@@ -442,12 +445,22 @@ class PostersService:
# ------------------------------------------------------------------ race poster # ------------------------------------------------------------------ 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( def render_race_poster(
self, self,
grand_prix_name: str, grand_prix_name: str,
season: int, season: int,
bg: BackgroundStyle = BackgroundStyle.AERIAL, bg: BackgroundStyle = BackgroundStyle.AERIAL,
) -> Optional[bytes]: ) -> Optional[tuple[bytes, bool]]:
races = self.ergast._fetch_season_schedule(season) races = self.ergast._fetch_season_schedule(season)
race = next((r for r in races if r["raceName"] == grand_prix_name), None) race = next((r for r in races if r["raceName"] == grand_prix_name), None)
if not race: if not race:
@@ -465,7 +478,7 @@ class PostersService:
cache_key = f"{season}-{round_num:02d}-{layout.slug}-{bg.value}-{POSTER_RENDER}.png" cache_key = f"{season}-{round_num:02d}-{layout.slug}-{bg.value}-{POSTER_RENDER}.png"
cache_path = self.cache_dir / cache_key cache_path = self.cache_dir / cache_key
if cache_path.exists(): 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. # 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 # 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() data = buf.getvalue()
if bg is BackgroundStyle.NONE or map_bg is not None: 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 # A poster whose map failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data) self._keep(cache_path, data)
return data return data, bg is BackgroundStyle.NONE or map_bg is not None
# ------------------------------------------------------------------ session thumb (16:9) # ------------------------------------------------------------------ session thumb (16:9)
@@ -569,7 +582,7 @@ class PostersService:
ox, oy = left - tx0 * 256, top - ty0 * 256 ox, oy = left - tx0 * 256, top - ty0 * 256
return canvas.crop((ox, oy, ox + THUMB_W, oy + THUMB_H)) 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.""" """1920x1080 Plex episode-thumb. Aerial of the circuit + GP name + session label."""
label = SESSION_LABEL_BY_SLUG.get(session_slug) label = SESSION_LABEL_BY_SLUG.get(session_slug)
if not label: if not label:
@@ -587,7 +600,7 @@ class PostersService:
cache_key = f"thumb-{season}-{round_num:02d}-{layout.slug}-{session_slug}.png" cache_key = f"thumb-{season}-{round_num:02d}-{layout.slug}-{session_slug}.png"
cache_path = self.cache_dir / cache_key cache_path = self.cache_dir / cache_key
if cache_path.exists(): 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, # 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. # so the thumb shows the same place at the same zoom level.
@@ -655,8 +668,8 @@ class PostersService:
data = buf.getvalue() data = buf.getvalue()
if map_bg is not None: if map_bg is not None:
# A thumb whose aerial failed is served, not kept: the next ask renders it again # A thumb whose aerial failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data) self._keep(cache_path, data)
return data return data, map_bg is not None
# ------------------------------------------------------------------ kometa metadata # ------------------------------------------------------------------ kometa metadata
@@ -773,10 +786,10 @@ class PostersService:
ovr[x, y] = (0, 0, 0, alpha) ovr[x, y] = (0, 0, 0, alpha)
return overlay 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" cache_path = self.cache_dir / f"season-{season}.png"
if cache_path.exists(): if cache_path.exists():
return cache_path.read_bytes() return cache_path.read_bytes(), True
bg = self._fetch_season_background(season) bg = self._fetch_season_background(season)
if bg is None: if bg is None:
@@ -798,5 +811,5 @@ class PostersService:
data = buf.getvalue() data = buf.getvalue()
if bg is not None: if bg is not None:
# A poster whose photo failed is served, not kept: the next ask renders it again # A poster whose photo failed is served, not kept: the next ask renders it again
cache_path.write_bytes(data) self._keep(cache_path, data)
return data return data, bg is not None
+3 -1
View File
@@ -30,4 +30,6 @@ COPY examples/ ./examples/
EXPOSE 8000 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 service.REQUEST_INTERVAL = 0
return service 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() service = self.service()
with mock.patch.object(service, "_ask_jolpica", side_effect=[None, RACES]) as ask: 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), [])
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) self.assertEqual(ask.call_count, 2)
def test_a_season_that_is_over_is_read_from_disk(self): def test_a_season_that_is_over_is_read_from_disk(self):