diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1358619..11839310 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 \ diff --git a/backend/main.py b/backend/main.py index 92fbc54e..7338e044 100644 --- a/backend/main.py +++ b/backend/main.py @@ -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) diff --git a/backend/routers/osm_tiles.py b/backend/routers/osm_tiles.py new file mode 100644 index 00000000..de593508 --- /dev/null +++ b/backend/routers/osm_tiles.py @@ -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}) diff --git a/backend/tests/test_osm_tiles.py b/backend/tests/test_osm_tiles.py new file mode 100644 index 00000000..c661a193 --- /dev/null +++ b/backend/tests/test_osm_tiles.py @@ -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() diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index c2f73e0c..44117846 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -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() { {t('controls.style')} ⇄ - {activeStyle === 'SATELLITE' ? 'SATELLITE' : 'MAP'} + {activeStyle === 'DEFAULT' ? 'MAP' : activeStyle} diff --git a/frontend/src/components/DisplayMenu.tsx b/frontend/src/components/DisplayMenu.tsx index e48839ab..595f329e 100644 --- a/frontend/src/components/DisplayMenu.tsx +++ b/frontend/src/components/DisplayMenu.tsx @@ -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} /> diff --git a/frontend/src/components/MaplibreViewer.tsx b/frontend/src/components/MaplibreViewer.tsx index 57cc6950..49226745 100644 --- a/frontend/src/components/MaplibreViewer.tsx +++ b/frontend/src/components/MaplibreViewer.tsx @@ -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( - () => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey), - [theme, cartoApiKey], + () => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey, activeStyle), + [theme, cartoApiKey, activeStyle], ); const initialViewState = useMemo( diff --git a/frontend/src/components/map/styles/mapStyles.ts b/frontend/src/components/map/styles/mapStyles.ts index 7b409e58..3740f058 100644 --- a/frontend/src/components/map/styles/mapStyles.ts +++ b/frontend/src/components/map/styles/mapStyles.ts @@ -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]; diff --git a/frontend/src/lib/layerPreferences.ts b/frontend/src/lib/layerPreferences.ts index 71a3a613..b0d3f1ca 100644 --- a/frontend/src/lib/layerPreferences.ts +++ b/frontend/src/lib/layerPreferences.ts @@ -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 = [ diff --git a/frontend/src/types/dashboard.ts b/frontend/src/types/dashboard.ts index 1cb11540..e799008c 100644 --- a/frontend/src/types/dashboard.ts +++ b/frontend/src/types/dashboard.ts @@ -1332,6 +1332,7 @@ export interface MapEffects { export interface MaplibreViewerProps { data: DashboardData; activeLayers: ActiveLayers; + activeStyle?: string; activeFilters?: Record; effects?: MapEffects; onEntityClick: (entity: SelectedEntity | null) => void;