diff --git a/cdn-api.py b/cdn-api.py index a72b537..572fc2f 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -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: diff --git a/ergast_service.py b/ergast_service.py index b3b8aa2..d579f0e 100644 --- a/ergast_service.py +++ b/ergast_service.py @@ -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' diff --git a/models/__pycache__/__init__.cpython-313.pyc b/models/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index c95cf42..0000000 Binary files a/models/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/models/__pycache__/circuit.cpython-313.pyc b/models/__pycache__/circuit.cpython-313.pyc deleted file mode 100644 index 9844ba3..0000000 Binary files a/models/__pycache__/circuit.cpython-313.pyc and /dev/null differ diff --git a/models/__pycache__/country.cpython-313.pyc b/models/__pycache__/country.cpython-313.pyc deleted file mode 100644 index da92b32..0000000 Binary files a/models/__pycache__/country.cpython-313.pyc and /dev/null differ diff --git a/models/__pycache__/locality.cpython-313.pyc b/models/__pycache__/locality.cpython-313.pyc deleted file mode 100644 index 5d6ecd9..0000000 Binary files a/models/__pycache__/locality.cpython-313.pyc and /dev/null differ diff --git a/models/__pycache__/model_builder.cpython-313.pyc b/models/__pycache__/model_builder.cpython-313.pyc deleted file mode 100644 index e725668..0000000 Binary files a/models/__pycache__/model_builder.cpython-313.pyc and /dev/null differ diff --git a/models/__pycache__/track_layout.cpython-313.pyc b/models/__pycache__/track_layout.cpython-313.pyc deleted file mode 100644 index c7ab71b..0000000 Binary files a/models/__pycache__/track_layout.cpython-313.pyc and /dev/null differ diff --git a/models/geo_json/__pycache__/__init__.cpython-313.pyc b/models/geo_json/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index eaa5f95..0000000 Binary files a/models/geo_json/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/models/geo_json/__pycache__/feature.cpython-313.pyc b/models/geo_json/__pycache__/feature.cpython-313.pyc deleted file mode 100644 index e1299e1..0000000 Binary files a/models/geo_json/__pycache__/feature.cpython-313.pyc and /dev/null differ diff --git a/models/geo_json/__pycache__/geo_json.cpython-313.pyc b/models/geo_json/__pycache__/geo_json.cpython-313.pyc deleted file mode 100644 index c4943bc..0000000 Binary files a/models/geo_json/__pycache__/geo_json.cpython-313.pyc and /dev/null differ diff --git a/models/geo_json/__pycache__/geometry.cpython-313.pyc b/models/geo_json/__pycache__/geometry.cpython-313.pyc deleted file mode 100644 index 7ff2d69..0000000 Binary files a/models/geo_json/__pycache__/geometry.cpython-313.pyc and /dev/null differ diff --git a/models/geo_json/__pycache__/properties.cpython-313.pyc b/models/geo_json/__pycache__/properties.cpython-313.pyc deleted file mode 100644 index 27c9bb2..0000000 Binary files a/models/geo_json/__pycache__/properties.cpython-313.pyc and /dev/null differ diff --git a/posters_service.py b/posters_service.py index 5d9fad6..b8387cd 100644 --- a/posters_service.py +++ b/posters_service.py @@ -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 diff --git a/service/Dockerfile b/service/Dockerfile index b249c89..9722848 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -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", "*"] diff --git a/tests/__pycache__/__init__.cpython-314.pyc b/tests/__pycache__/__init__.cpython-314.pyc deleted file mode 100644 index 6a59da6..0000000 Binary files a/tests/__pycache__/__init__.cpython-314.pyc and /dev/null differ diff --git a/tests/__pycache__/test_circuit_ids.cpython-314.pyc b/tests/__pycache__/test_circuit_ids.cpython-314.pyc deleted file mode 100644 index 0883e2c..0000000 Binary files a/tests/__pycache__/test_circuit_ids.cpython-314.pyc and /dev/null differ diff --git a/tests/test_schedules.py b/tests/test_schedules.py index fae7000..2c104b6 100644 --- a/tests/test_schedules.py +++ b/tests/test_schedules.py @@ -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):