Keep map tiles on disk and fetch them in parallel; send posters with an ETag

A race poster took 8.8 s, 78% of it fetching 40 map tiles one by one,
and every poster, thumb and locator of the same circuit fetched the same
tiles again. Tiles are now kept on disk in the cache volume for 30 days
(stored only once the stitch is no placeholder) and fetched in parallel,
at most 6 at once per Esri service and 2 for OpenStreetMap, as its tile
usage policy asks, across every render. Measured: a poster of a new
circuit 2.4 s, of a known one 0.8 s; a weekend's first thumb 1.4 s, each
further thumb 0.8 s (was about 12 s each). PNGs are saved without
optimize (1.6 s less per render, 2% larger).

A stored poster is sent with an ETag and a day's cache instead of a
year's, and an If-None-Match that matches gets a 304, so a poster whose
look changes reaches clients within a day.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
2026-11-27 10:31:39 +01:00
parent d9c6fdc46c
commit b55f9cd615
2 changed files with 85 additions and 34 deletions
+20 -15
View File
@@ -1,4 +1,6 @@
from fastapi import FastAPI, HTTPException, Response
import hashlib
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
@@ -98,18 +100,21 @@ 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"},
)
def poster_response(request: Request, png: bytes, kept: bool) -> Response:
"""A stored poster: clients keep it a day, then ask again with its ETag and get a 304 while it is
unchanged, so a poster whose look changed reaches them within a day, not a year. A poster whose map
or photo failed is kept by clients for five minutes, with no ETag, so they ask again soon."""
if not kept:
return FastAPIResponse(content=png, media_type="image/png", headers={"Cache-Control": "public, max-age=300"})
etag = '"' + hashlib.sha256(png).hexdigest()[:32] + '"'
headers = {"Cache-Control": "public, max-age=86400", "ETag": etag}
if etag in [tag.strip() for tag in request.headers.get("if-none-match", "").split(",")]:
return Response(status_code=304, headers=headers)
return FastAPIResponse(content=png, media_type="image/png", headers=headers)
@app.get("/posters/race/{grand_prix_name}/{season}.png")
def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
def get_race_poster(request: Request, 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:
@@ -122,17 +127,17 @@ def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = Bac
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 poster_response(*rendered)
return poster_response(request, *rendered)
@app.get("/posters/season/{season}.png")
def get_season_poster(season: int):
def get_season_poster(request: Request, season: int):
"""Plex-ready 1000x1500 season poster (PNG). Cached on disk."""
return poster_response(*posters_service.render_season_poster(season))
return poster_response(request, *posters_service.render_season_poster(season))
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png")
def get_session_thumb(grand_prix_name: str, season: int, session_slug: str):
def get_session_thumb(request: Request, 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,
@@ -143,7 +148,7 @@ def get_session_thumb(grand_prix_name: str, season: int, session_slug: str):
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 poster_response(*rendered)
return poster_response(request, *rendered)
@app.get("/kometa/formula-1-metadata.yml")
+65 -19
View File
@@ -19,7 +19,9 @@ import logging
import math
import os
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from enum import Enum
from pathlib import Path
from typing import Optional
@@ -53,24 +55,34 @@ TILE_PROVIDERS = {
"url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
"attribution": "Esri, Maxar, Earthstar Geographics",
"max_zoom": 19,
"concurrency": 6,
},
BackgroundStyle.OSM: {
"url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "© OpenStreetMap contributors",
"max_zoom": 19,
"concurrency": 2, # OpenStreetMap's tile usage policy: at most two connections
},
BackgroundStyle.DARK: {
"url": "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}",
"attribution": "Esri, HERE, Garmin, © OpenStreetMap contributors",
"max_zoom": 16,
"concurrency": 6,
},
BackgroundStyle.LIGHT: {
"url": "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}",
"attribution": "Esri, HERE, Garmin, © OpenStreetMap contributors",
"max_zoom": 16,
"concurrency": 6,
},
}
# Tiles are kept on disk under cache/tiles/<style>/<z>/<x>/<y> and used for this long: every poster,
# thumb and locator of a circuit draws on the same tiles (OpenStreetMap's policy asks for at least a week).
TILE_KEEP_SECONDS = 30 * 24 * 3600
# At most this many requests to one provider at once, over every render the service runs side by side.
TILE_SLOTS = {style: threading.BoundedSemaphore(provider["concurrency"]) for style, provider in TILE_PROVIDERS.items()}
# Part of every race poster's file name in the cache: raised when what a poster looks like changes,
# so posters rendered before (such as over CARTO's "API KEY REQUIRED" tiles) are rendered again.
POSTER_RENDER = "r2"
@@ -155,6 +167,7 @@ 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)
self.tile_dir = Path("cache/tiles")
# 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.
@@ -231,32 +244,65 @@ class PostersService:
200, and a poster over it is worse than one over black."""
provider = TILE_PROVIDERS[style]
canvas = Image.new("RGB", ((tx_hi - tx_lo) * 256, (ty_hi - ty_lo) * 256), BG)
bodies = set()
fetched = 0
for tx in range(tx_lo, tx_hi):
for ty in range(ty_lo, ty_hi):
x = tx % (2 ** zoom) if wrap_x else tx
if not (0 <= ty < 2 ** zoom):
continue
url = provider["url"].format(z=zoom, x=x, y=ty)
try:
wanted = [(tx, ty, tx % (2 ** zoom) if wrap_x else tx)
for tx in range(tx_lo, tx_hi) for ty in range(ty_lo, ty_hi) if 0 <= ty < 2 ** zoom]
def tile_body(x: int, y: int) -> tuple[Optional[bytes], bool]:
"""A tile's bytes and whether they came from the network (False: from disk)."""
path = self.tile_dir / style.value / str(zoom) / str(x) / str(y)
try:
if time.time() - path.stat().st_mtime < TILE_KEEP_SECONDS:
return path.read_bytes(), False
except OSError:
pass
url = provider["url"].format(z=zoom, x=x, y=y)
try:
with TILE_SLOTS[style]:
req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT})
with urllib.request.urlopen(req, timeout=10) as resp:
body = resp.read()
tile = Image.open(io.BytesIO(body)).convert("RGB")
canvas.paste(tile, ((tx - tx_lo) * 256, (ty - ty_lo) * 256))
bodies.add(hashlib.sha256(body).digest())
fetched += 1
except Exception as e:
logger.warning(f"Tile fetch failed {style.value} z={zoom} x={x} y={ty}: {e}")
return resp.read(), True
except Exception as e:
logger.warning(f"Tile fetch failed {style.value} z={zoom} x={x} y={y}: {e}")
return None, False
with ThreadPoolExecutor(max_workers=provider["concurrency"]) as pool:
bodies_in_order = list(pool.map(lambda t: tile_body(t[2], t[1]), wanted))
bodies = set()
fetched = 0
new_tiles = []
for (tx, ty, x), (body, from_network) in zip(wanted, bodies_in_order):
if body is None:
continue
try:
tile = Image.open(io.BytesIO(body)).convert("RGB")
except Exception as e:
logger.warning(f"Tile unreadable {style.value} z={zoom} x={x} y={ty}: {e}")
continue
canvas.paste(tile, ((tx - tx_lo) * 256, (ty - ty_lo) * 256))
bodies.add(hashlib.sha256(body).digest())
fetched += 1
if from_network:
new_tiles.append((x, ty, body))
if not fetched:
return None
if fetched > 1 and len(bodies) == 1:
logger.error(f"Every {style.value} tile at z={zoom} is the same picture: the provider answers a "
f"placeholder ({provider['url'].split('/')[2]}), no map drawn")
return None
# Kept only now: a placeholder never reaches the disk
for x, y, body in new_tiles:
self._keep_tile(style, zoom, x, y, body)
return canvas
def _keep_tile(self, style: BackgroundStyle, zoom: int, x: int, y: int, body: bytes) -> None:
path = self.tile_dir / style.value / str(zoom) / str(x) / str(y)
try:
path.parent.mkdir(parents=True, exist_ok=True)
self._keep(path, body)
except OSError as e:
logger.warning(f"Could not keep tile {path}: {e}")
def _fetch_map_background(self, lat: float, lon: float, zoom: int, style: BackgroundStyle) -> Optional[Image.Image]:
"""Stitch enough 256-px tiles around (lat, lon) to fill the full POSTER_W x POSTER_H."""
provider = TILE_PROVIDERS.get(style)
@@ -557,7 +603,7 @@ class PostersService:
self._checker_strip(draw, POSTER_H - CHECKER_H)
buf = io.BytesIO()
img.save(buf, "PNG", optimize=True)
img.save(buf, "PNG")
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
@@ -664,7 +710,7 @@ class PostersService:
draw.rectangle([x_margin, sess_y - 16, x_margin + 120, sess_y - 8], fill=RED)
buf = io.BytesIO()
img.save(buf, "PNG", optimize=True)
img.save(buf, "PNG")
data = buf.getvalue()
if map_bg is not None:
# A thumb whose aerial failed is served, not kept: the next ask renders it again
@@ -807,7 +853,7 @@ class PostersService:
self._checker_strip(draw, POSTER_H - CHECKER_H)
buf = io.BytesIO()
img.save(buf, "PNG", optimize=True)
img.save(buf, "PNG")
data = buf.getvalue()
if bg is not None:
# A poster whose photo failed is served, not kept: the next ask renders it again