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
+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