From b55f9cd615e0ceba00674167ad744fd70acd30db Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 27 Nov 2026 10:31:39 +0100 Subject: [PATCH] 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 --- cdn-api.py | 35 ++++++++++--------- posters_service.py | 84 +++++++++++++++++++++++++++++++++++----------- 2 files changed, 85 insertions(+), 34 deletions(-) diff --git a/cdn-api.py b/cdn-api.py index 572fc2f..fbf6a93 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -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") diff --git a/posters_service.py b/posters_service.py index b8387cd..e6b853b 100644 --- a/posters_service.py +++ b/posters_service.py @@ -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/