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")