feat: cache-header für pwa-dateien

- index.html, sw.js und Manifest mit no-cache, damit Updates ankommen
- gehashte Assets mit max-age=31536000, immutable; Icons einen Tag
- Manifest mit Content-Type application/manifest+json

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 11:46:17 +01:00
1 parent 0ad6d248cf
commit 9cf163c295
2 files changed
+59 -2

No files matched your search

+20 -2
View File
@@ -74,6 +74,20 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
task.cancel() task.cancel()
# Hashed build output never changes; everything else must be revalidated so updates arrive
_IMMUTABLE = "public, max-age=31536000, immutable"
_REVALIDATE = "no-cache"
_MEDIA_TYPES = {".webmanifest": "application/manifest+json"}
def _cache_control(relative: str) -> str:
if relative.startswith("assets/") or relative.startswith("workbox-"):
return _IMMUTABLE
if relative.startswith("icons/"):
return "public, max-age=86400"
return _REVALIDATE # index.html, sw.js, manifest.webmanifest
def _register_frontend(app: FastAPI, static_dir: Path) -> None: def _register_frontend(app: FastAPI, static_dir: Path) -> None:
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html.""" """Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
root = static_dir.resolve() root = static_dir.resolve()
@@ -85,12 +99,16 @@ def _register_frontend(app: FastAPI, static_dir: Path) -> None:
raise HTTPException(status_code=404) raise HTTPException(status_code=404)
candidate = (root / path).resolve() candidate = (root / path).resolve()
if path and candidate.is_relative_to(root) and candidate.is_file(): if path and candidate.is_relative_to(root) and candidate.is_file():
return FileResponse(candidate) return FileResponse(
candidate,
media_type=_MEDIA_TYPES.get(candidate.suffix),
headers={"Cache-Control": _cache_control(path)},
)
# Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes # Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes
segments = path.split("/") segments = path.split("/")
if "." in segments[-1] or any(seg.startswith(".") for seg in segments): if "." in segments[-1] or any(seg.startswith(".") for seg in segments):
raise HTTPException(status_code=404) raise HTTPException(status_code=404)
return FileResponse(index_file, headers={"Cache-Control": "no-cache"}) return FileResponse(index_file, headers={"Cache-Control": _REVALIDATE})
def create_app() -> FastAPI: def create_app() -> FastAPI:
+39
View File
@@ -0,0 +1,39 @@
import pytest
@pytest.fixture
def built(static_dir):
"""Minimal stand-in for the frontend build output."""
(static_dir / "assets").mkdir()
(static_dir / "icons").mkdir()
(static_dir / "index.html").write_text("<html>spa</html>")
(static_dir / "sw.js").write_text("self.addEventListener('fetch', () => {})")
(static_dir / "workbox-abc123.js").write_text("// workbox")
(static_dir / "manifest.webmanifest").write_text('{"name": "LAN-Clipboard"}')
(static_dir / "assets" / "index-abc123.js").write_text("console.log(1)")
(static_dir / "icons" / "icon-192.png").write_bytes(b"\\x89PNG")
@pytest.mark.parametrize("path", ["/", "/clips/1", "/index.html", "/sw.js"])
def test_entry_points_are_revalidated(built, client, path):
assert client.get(path).headers["cache-control"] == "no-cache"
@pytest.mark.parametrize("path", ["/assets/index-abc123.js", "/workbox-abc123.js"])
def test_hashed_files_are_immutable(built, client, path):
assert client.get(path).headers["cache-control"] == "public, max-age=31536000, immutable"
def test_icons_are_cached_for_a_day(built, client):
assert client.get("/icons/icon-192.png").headers["cache-control"] == "public, max-age=86400"
def test_manifest_content_type(built, client):
response = client.get("/manifest.webmanifest")
assert response.status_code == 200
assert response.headers["content-type"].startswith("application/manifest+json")
assert response.headers["cache-control"] == "no-cache"
def test_service_worker_is_javascript(built, client):
assert "javascript" in client.get("/sw.js").headers["content-type"]