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/