Merge pull request #693 from esmaeelE/fix/osm-tile-proxy-pr649

feat(osm): fix PR #649 review requests
This commit is contained in:
Shadowbroker authored and GitHub committed 2026-11-13 19:33:12 -07:00
commit 69b8ba80db
10 files changed
+171 -13

No files matched your search

+1
View File
@@ -113,6 +113,7 @@ jobs:
tests/test_release_helper.py \
tests/test_liveuamap_scraper_opt_in.py \
tests/test_liveuamap_parser.py \
tests/test_osm_tiles.py \
tests/test_liveuamap_provider.py \
tests/test_liveuamap_docker_contract.py \
tests/test_xquik_news.py \
+2
View File
@@ -379,6 +379,7 @@ def _load_optional_router(module_name: str) -> APIRouter:
health_router = _load_optional_router("routers.health")
osm_tiles_router = _load_optional_router("routers.osm_tiles")
mesh_peer_sync_router = _load_optional_router("routers.mesh_peer_sync")
mesh_operator_router = _load_optional_router("routers.mesh_operator")
mesh_oracle_router = _load_optional_router("routers.mesh_oracle")
@@ -3850,6 +3851,7 @@ async def apply_no_store_to_sensitive_paths(request: Request, call_next):
# Register routers
# ---------------------------------------------------------------------------
app.include_router(health_router)
app.include_router(osm_tiles_router)
app.include_router(cctv_router)
app.include_router(radio_router)
app.include_router(sigint_router)
+92
View File
@@ -0,0 +1,92 @@
"""OpenStreetMap standard raster tile proxy.
Proxies ``GET /api/osm-tile/{z}/{x}/{y}.png`` to ``tile.openstreetmap.org`` so
the frontend can render a keyless OSM basemap without browsers calling the tile
server directly.
OSM tile usage policy
(https://operations.osmfoundation.org/policies/tiles/):
- identify the client with a descriptive User-Agent (per-install operator
handle, never a shared project-wide string)
- cache tiles instead of re-fetching on every pan / zoom
- keep request rates reasonable
"""
import logging
import httpx
from cachetools import TLRUCache
from fastapi import APIRouter, Path, Request
from fastapi.responses import Response
from limiter import limiter
from services.network_utils import outbound_user_agent
logger = logging.getLogger(__name__)
router = APIRouter()
# OpenStreetMap standard tile endpoint.
_OSM_TILE_BASE = "https://tile.openstreetmap.org"
# OSM tiles are served up to zoom 19 on the standard layer.
_OSM_MAX_ZOOM = 19
# In-memory tile cache keyed by "z/x/y". Tiles change infrequently, so a
# multi-day TTL keeps repeated pans/zooms from hitting the upstream.
_TILE_CACHE = TLRUCache(maxsize=2048, ttu=lambda _key, value, now: now + value[2])
# Per-request User-Agent identifying this install to the tile operator.
_OSM_USER_AGENT = outbound_user_agent("osm-tiles")
def _tile_bounds_valid(z: int, x: int, y: int) -> bool:
if z < 0 or z > _OSM_MAX_ZOOM:
return False
limit = 1 << z
return 0 <= x < limit and 0 <= y < limit
@router.get("/api/osm-tile/{z}/{x}/{y}.png")
@limiter.limit("180/minute")
async def osm_tile(
request: Request,
z: int = Path(..., ge=0, le=_OSM_MAX_ZOOM),
x: int = Path(..., ge=0),
y: int = Path(..., ge=0),
) -> Response:
"""Proxy a single OSM raster tile, cached per z/x/y."""
if not _tile_bounds_valid(z, x, y):
return Response(status_code=400)
cache_key = f"{z}/{x}/{y}"
cached = _TILE_CACHE.get(cache_key)
if cached is not None:
content, cache_control, _ = cached
return Response(content=content, media_type="image/png", headers={"Cache-Control": cache_control})
url = f"{_OSM_TILE_BASE}/{z}/{x}/{y}.png"
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(10, connect=3)) as client:
upstream = await client.get(url, headers={"User-Agent": _OSM_USER_AGENT})
except httpx.RequestError as exc:
logger.warning("OSM tile proxy request failed for %s: %s", url, exc)
return Response(status_code=502)
if upstream.status_code != 200:
retry_after = upstream.headers.get("Retry-After")
return Response(
status_code=upstream.status_code if upstream.status_code in (403, 404, 429) else 502,
headers={"Retry-After": retry_after} if retry_after else None,
)
if not upstream.content.startswith(b"\x89PNG\r\n\x1a\n"):
return Response(status_code=502)
cache_control = upstream.headers.get("Cache-Control", "public, max-age=604800")
directives = dict(
(key.strip(), value.strip(' "'))
for key, _, value in (part.strip().lower().partition("=") for part in cache_control.split(","))
)
max_age = directives.get("s-maxage", directives.get("max-age", "0"))
if max_age.isdecimal() and not {"no-store", "no-cache", "private"}.intersection(directives):
_TILE_CACHE[cache_key] = (upstream.content, cache_control, min(int(max_age), 604800))
return Response(content=upstream.content, media_type="image/png", headers={"Cache-Control": cache_control})
+32
View File
@@ -0,0 +1,32 @@
from unittest.mock import AsyncMock
import httpx
import pytest
from fastapi import FastAPI
from limiter import limiter
from routers import osm_tiles
@pytest.mark.asyncio
@pytest.mark.parametrize("status,expected,requests", [(200, 200, 1), (429, 429, 2)])
async def test_osm_proxy_caches_only_valid_tiles(monkeypatch, status, expected, requests):
app = FastAPI()
app.state.limiter = limiter
app.include_router(osm_tiles.router)
png = b"\x89PNG\r\n\x1a\nmock"
get = AsyncMock(return_value=httpx.Response(status, content=png, headers={"Cache-Control": "max-age=300"}))
monkeypatch.setattr(httpx.AsyncClient, "get", lambda self, *a, **kw: get(*a, **kw))
osm_tiles._TILE_CACHE.clear()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
path = "/api/osm-tile/2/1/1.png"
for _ in range(2):
response = await client.request("GET", path)
assert response.status_code == expected
if status == 200:
assert response.content == png
assert response.headers["cache-control"] == "max-age=300"
assert (await client.request("GET", "/api/osm-tile/2/4/1.png")).status_code == 400
assert get.await_count == requests
get.assert_awaited_with("https://tile.openstreetmap.org/2/1/1.png", headers={"User-Agent": osm_tiles._OSM_USER_AGENT})
osm_tiles._TILE_CACHE.clear()
+12 -10
View File
@@ -231,7 +231,7 @@ export default function Dashboard() {
// exposes the basemap to CSS so sensor filters can tame bright satellite imagery
useEffect(() => {
document.documentElement.setAttribute('data-basemap', activeStyle === 'SATELLITE' ? 'satellite' : 'map');
document.documentElement.setAttribute('data-basemap', activeStyle === 'DEFAULT' ? 'map' : activeStyle.toLowerCase());
}, [activeStyle]);
// The bottom fade on the HUD columns is a "more below" cue, so it only shows while a
@@ -544,14 +544,15 @@ export default function Dashboard() {
[],
);
const stylesList = ['DEFAULT', 'SATELLITE'];
const cycleStyle = () => {
setActiveStyle((prev) => {
const idx = stylesList.indexOf(prev);
const next = stylesList[(idx + 1) % stylesList.length] as MapStyle;
// Auto-toggle High-Res Satellite layer with SATELLITE style
setActiveLayers((l) => ({ ...l, highres_satellite: next === 'SATELLITE' }));
const order: MapStyle[] = ['DEFAULT', 'SATELLITE', 'OSM'];
const idx = order.indexOf(prev);
const next = order[(idx + 1) % order.length];
setActiveLayers((l) => ({
...l,
highres_satellite: next === 'SATELLITE',
}));
return next;
});
};
@@ -635,6 +636,7 @@ export default function Dashboard() {
<ErrorBoundary name="Map">
<MaplibreViewer
activeLayers={firstPaintActiveLayers}
activeStyle={activeStyle}
activeFilters={activeFilters}
effects={memoizedEffects}
onEntityClick={setSelectedEntity}
@@ -989,15 +991,15 @@ export default function Dashboard() {
<button
type="button"
onClick={cycleStyle}
title={`Switch basemap to ${activeStyle === 'SATELLITE' ? 'MAP' : 'SATELLITE'} (also under VIEW)`}
aria-label={`Basemap: ${activeStyle === 'SATELLITE' ? 'satellite' : 'map'}. Click to switch.`}
title={`Switch basemap to ${activeStyle === 'DEFAULT' ? 'SATELLITE' : activeStyle === 'SATELLITE' ? 'OSM' : 'MAP'} (also under VIEW)`}
aria-label={`Basemap: ${activeStyle === 'DEFAULT' ? 'map' : activeStyle.toLowerCase()}. Click to switch.`}
className="sb-style-cell group flex flex-col items-center w-[104px] -my-1 py-1 rounded-lg border border-transparent hover:border-cyan-500/40 hover:bg-cyan-500/10 transition-colors cursor-pointer"
>
<span className="text-[11px] text-[var(--text-muted)] font-mono tracking-[0.14em] group-hover:text-cyan-300">
{t('controls.style')} ⇄
</span>
<span className="text-[14px] text-cyan-400 font-mono font-bold">
{activeStyle === 'SATELLITE' ? 'SATELLITE' : 'MAP'}
{activeStyle === 'DEFAULT' ? 'MAP' : activeStyle}
</span>
</button>
+1
View File
@@ -156,6 +156,7 @@ export default function DisplayMenu({
options={[
{ id: 'DEFAULT' as MapStyle, label: 'MAP' },
{ id: 'SATELLITE' as MapStyle, label: 'SATELLITE' },
{ id: 'OSM' as MapStyle, label: 'OSM' },
]}
onChange={onMapStyleChange}
/>
+3 -2
View File
@@ -403,6 +403,7 @@ function buildPolymarketUrl(prediction: { slug?: string; title?: string } | null
const MaplibreViewer = ({
activeLayers,
activeStyle,
activeFilters,
onEntityClick,
flyToLocation,
@@ -457,8 +458,8 @@ const MaplibreViewer = ({
const basemapPalette = 'navy' as const;
const { cartoApiKey, loaded: basemapConfigLoaded } = useBasemapConfig();
const mapThemeStyle = useMemo<maplibregl.StyleSpecification | string>(
() => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey),
[theme, cartoApiKey],
() => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey, activeStyle),
[theme, cartoApiKey, activeStyle],
);
const initialViewState = useMemo<ViewState>(
@@ -44,7 +44,33 @@ export function cartoTileUrls(theme: BasemapTheme, cartoApiKey: string): string[
export function buildBasemapStyle(
theme: BasemapTheme,
cartoApiKey?: string | null,
mapStyle?: string,
): string | StyleSpecification {
if (mapStyle === 'OSM') {
return {
version: 8,
glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
sources: {
osm: {
type: 'raster',
tiles: ['/api/osm-tile/{z}/{x}/{y}.png'],
tileSize: 256,
maxzoom: 19,
attribution: OSM_ATTRIBUTION_HTML,
},
},
layers: [
{
id: 'osm-base',
type: 'raster',
source: 'osm',
minzoom: 0,
maxzoom: 22,
},
],
};
}
const key = (cartoApiKey || '').trim();
if (!key) return OPENFREEMAP_STYLE_URLS[theme];
+1 -1
View File
@@ -6,7 +6,7 @@ export const DASHBOARD_PREFS_STORAGE_KEY = 'sb_dashboard_prefs_v1';
export const DASHBOARD_PREFS_VERSION = 1;
export const LAYER_PREFERENCES_CHANGED_EVENT = 'sb:layer-preferences-changed';
export const MAP_STYLES = ['DEFAULT', 'SATELLITE'] as const;
export const MAP_STYLES = ['DEFAULT', 'SATELLITE', 'OSM'] as const;
export type MapStyle = (typeof MAP_STYLES)[number];
export const LAYER_SECTION_IDS = [
+1
View File
@@ -1332,6 +1332,7 @@ export interface MapEffects {
export interface MaplibreViewerProps {
data: DashboardData;
activeLayers: ActiveLayers;
activeStyle?: string;
activeFilters?: Record<string, string[]>;
effects?: MapEffects;
onEntityClick: (entity: SelectedEntity | null) => void;