RepoPulse: update "backend/app/main.py" and "backend/tests/test_frontend_routes.py"

Public changes compared with the previous published export:
2 files changed.

Affected areas:
- backend/app: 1 file
- tests: 1 file

Changed files:
- Updated: "backend/app/main.py"
- Added: "backend/tests/test_frontend_routes.py"

Export provenance/manifests refreshed; excluded from the change summary.

Publish curated RepoPulse source from 1201120636c6141d94a4aee81b48b5b001cea045
This commit is contained in:
Public Source Publisher committed 2026-11-20 05:43:52 +00:00
1 parent 787a2b1dc3
commit 131096340e
4 files changed
+84 -6

No files matched your search

+24 -2
View File
@@ -14,6 +14,7 @@ from fastapi.concurrency import run_in_threadpool
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.types import Scope
from .acquisition import GitAcquirer
@@ -524,10 +525,31 @@ def export_scan(scan_id: str, format: str = Query(default="html", pattern="^(htm
class _FrontendStaticFiles(StaticFiles):
"""Serve the SPA; content-hashed build assets are immutable and cached long-term."""
"""Serve the SPA; content-hashed build assets are immutable and cached long-term.
Client-side routes such as ``/repositories/{id}/findings`` have no file on disk. They
fall back to ``index.html`` so a refresh or a shared link opens the right view, while
API paths, build assets and anything that looks like a file keep an honest 404.
"""
@staticmethod
def _is_client_route(path: str) -> bool:
normalized = path.replace("\\", "/").strip("/")
if not normalized or normalized.split("/", 1)[0] in {"api", "assets", "health"}:
return False
return "." not in normalized.rsplit("/", 1)[-1]
async def get_response(self, path: str, scope: Scope) -> Response:
response = await super().get_response(path, scope)
try:
response = await super().get_response(path, scope)
except (StarletteHTTPException, OSError) as exc:
# Route segments such as "gitea:64" are not valid file names on every platform.
missing = isinstance(exc, OSError) or exc.status_code == 404
if not missing or scope.get("method") not in {"GET", "HEAD"} or not self._is_client_route(path):
if isinstance(exc, OSError):
raise StarletteHTTPException(status_code=404) from exc
raise
response = await super().get_response("index.html", scope)
if response.status_code == 200:
if path.replace("\\", "/").startswith("assets/"):
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
+51
View File
@@ -0,0 +1,51 @@
from __future__ import annotations
from pathlib import Path
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.main import _FrontendStaticFiles
def _client(tmp_path: Path) -> TestClient:
static = tmp_path / "static"
(static / "assets").mkdir(parents=True)
(static / "index.html").write_text("<!doctype html><div id=root></div>", encoding="utf-8")
(static / "assets" / "index-abc123.js").write_text("console.log(1)", encoding="utf-8")
(static / "favicon.svg").write_text("<svg/>", encoding="utf-8")
app = FastAPI()
@app.get("/api/v1/ping")
def ping() -> dict[str, str]:
return {"status": "ok"}
app.mount("/", _FrontendStaticFiles(directory=static, html=True), name="frontend")
return TestClient(app)
def test_client_routes_fall_back_to_the_spa_shell(tmp_path: Path) -> None:
client = _client(tmp_path)
for path in ("/repositories", "/activity", "/queue", "/settings", "/repositories/gitea%3A64/findings"):
response = client.get(path)
assert response.status_code == 200, path
assert "id=root" in response.text
assert response.headers["cache-control"] == "no-cache"
def test_api_assets_and_missing_files_keep_an_honest_404(tmp_path: Path) -> None:
client = _client(tmp_path)
assert client.get("/api/v1/ping").json() == {"status": "ok"}
assert client.get("/api/v1/unknown").status_code == 404
assert client.get("/assets/missing-chunk.js").status_code == 404
assert client.get("/robots.txt").status_code == 404
assert client.post("/repositories").status_code in {404, 405}
def test_hashed_assets_stay_immutable_and_files_are_served_directly(tmp_path: Path) -> None:
client = _client(tmp_path)
asset = client.get("/assets/index-abc123.js")
assert asset.status_code == 200
assert asset.headers["cache-control"] == "public, max-age=31536000, immutable"
assert client.get("/favicon.svg").headers["cache-control"] == "no-cache"
assert client.get("/").headers["cache-control"] == "no-cache"