From 048fe7ad5caf375d1d018a12f01220d6f8cb1155 Mon Sep 17 00:00:00 2001 From: esmaeelE Date: Mon, 2 Nov 2026 11:53:06 +0330 Subject: [PATCH 1/7] feat(osm): add OSM basemap style to map style cycle --- frontend/src/app/page.tsx | 16 +++++---- frontend/src/components/MaplibreViewer.tsx | 30 ++++++++++++++-- .../src/components/WorldviewLeftPanel.tsx | 2 ++ .../src/components/map/styles/mapStyles.ts | 36 ++++++++++++++++++- frontend/src/lib/layerPreferences.ts | 3 +- frontend/src/types/dashboard.ts | 2 ++ 6 files changed, 79 insertions(+), 10 deletions(-) diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 5bac2d2e..ea3d05d0 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -486,14 +486,16 @@ 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', + osm_basemap: next === 'OSM', + })); return next; }); }; @@ -508,6 +510,7 @@ export default function Dashboard() { sar: false, gibs_imagery: false, highres_satellite: false, + osm_basemap: false, sentinel_hub: false, viirs_nightlights: false, road_corridor_trends: false, @@ -542,6 +545,7 @@ export default function Dashboard() { ( - () => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey), - [theme, cartoApiKey], + () => buildBasemapStyle(theme === 'light' ? 'light' : 'dark', cartoApiKey, activeStyle), + [theme, cartoApiKey, activeStyle], ); const initialViewState = useMemo( @@ -2058,6 +2063,27 @@ const MaplibreViewer = ({ )} + {/* OpenStreetMap standard raster tiles — selectable basemap */} + {false && ( + + + + )} + {/* NASA GIBS MODIS Terra — daily satellite imagery overlay */} {activeLayers.gibs_imagery && gibsDate && ( ([ 'gibs_imagery', 'highres_satellite', + 'osm_basemap', 'sentinel_hub', 'viirs_nightlights', 'road_corridor_trends', diff --git a/frontend/src/components/map/styles/mapStyles.ts b/frontend/src/components/map/styles/mapStyles.ts index 56601195..7027361f 100644 --- a/frontend/src/components/map/styles/mapStyles.ts +++ b/frontend/src/components/map/styles/mapStyles.ts @@ -33,7 +33,7 @@ export function cartoTileUrls(theme: BasemapTheme, cartoApiKey: string): string[ const key = cartoApiKey.trim(); return CARTO_SUBDOMAINS.map( (s) => - `https://${s}.basemaps.cartocdn.com/rastertiles/${style}/{z}/{x}/{y}@2x.png?key=${encodeURIComponent(key)}`, + `https://` + s + `.basemaps.cartocdn.com/rastertiles/${style}/{z}/{x}/{y}@2x.png?key=${encodeURIComponent(key)}`, ); } @@ -44,7 +44,32 @@ 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, + 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]; @@ -65,3 +90,12 @@ export function buildBasemapStyle( export const darkStyle = buildBasemapStyle('dark'); export const lightStyle = buildBasemapStyle('light'); + +/** Standard OpenStreetMap raster tiles — selectable basemap (no API key). + * Proxied through backend to satisfy OSM tile usage policy (Referer header). */ +export const osmTiles = { + tiles: ['/api/osm-tile/{z}/{x}/{y}.png'], + tileSize: 256, + maxzoom: 19, + attribution: OSM_ATTRIBUTION_HTML, +}; diff --git a/frontend/src/lib/layerPreferences.ts b/frontend/src/lib/layerPreferences.ts index 71a3a613..3ab851a3 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 = [ @@ -50,6 +50,7 @@ export function getDefaultActiveLayers(): ActiveLayers { satellites: true, gibs_imagery: false, highres_satellite: false, + osm_basemap: false, sentinel_hub: false, viirs_nightlights: false, road_corridor_trends: false, diff --git a/frontend/src/types/dashboard.ts b/frontend/src/types/dashboard.ts index 552250f3..2fbc0135 100644 --- a/frontend/src/types/dashboard.ts +++ b/frontend/src/types/dashboard.ts @@ -1271,6 +1271,7 @@ export interface ActiveLayers { gps_jamming: boolean; gibs_imagery: boolean; highres_satellite: boolean; + osm_basemap: boolean; kiwisdr: boolean; psk_reporter: boolean; satnogs: boolean; @@ -1331,6 +1332,7 @@ export interface MapEffects { export interface MaplibreViewerProps { data: DashboardData; activeLayers: ActiveLayers; + activeStyle?: string; activeFilters?: Record; effects?: MapEffects; onEntityClick: (entity: SelectedEntity | null) => void; From 3285243b04e1b5f446a9b61beb73cb5a57f94d6e Mon Sep 17 00:00:00 2001 From: esmaeelE Date: Mon, 2 Nov 2026 12:57:54 +0330 Subject: [PATCH 2/7] change dockerfile for build locally on restricted location --- backend/Dockerfile_develop | 87 +++++++++++++++++++++++++++++++++++++ docker-compose.build.yml | 39 ++++++++++++++++- frontend/Dockerfile_develop | 56 ++++++++++++++++++++++++ note.md | 18 ++++++++ 4 files changed, 199 insertions(+), 1 deletion(-) create mode 100644 backend/Dockerfile_develop create mode 100644 frontend/Dockerfile_develop create mode 100644 note.md diff --git a/backend/Dockerfile_develop b/backend/Dockerfile_develop new file mode 100644 index 00000000..3eafe27f --- /dev/null +++ b/backend/Dockerfile_develop @@ -0,0 +1,87 @@ +# ======================================== +# Stage 1: Rust Library Builder +# ======================================== +FROM --platform=$BUILDPLATFORM rust:1.88-slim-bookworm AS rust-builder + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates git pkg-config libssl-dev build-essential \ + && rm -rf /var/lib/apt/lists/* + +ENV CARGO_NET_GIT_FETCH_WITH_CLI=true +ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse + +WORKDIR /build/privacy-core + +# Cache dependencies +COPY privacy-core/Cargo.toml privacy-core/Cargo.lock* ./ +RUN mkdir -p src && echo "fn main() {}" > src/lib.rs +RUN cargo build --release --lib + +# Real build +COPY privacy-core/src ./src +RUN cargo build --release --lib && ls -la target/release/libprivacy_core.so + + +# ======================================== +# Stage 2: Final Runtime Image +# ======================================== +FROM mcr.microsoft.com/playwright:v1.48.0-noble AS backend + +WORKDIR /app + +# === 1. System packages (cached very well - first layer after FROM) === +RUN apt-get update && apt-get install -y --no-install-recommends \ + python3 \ + python3-venv \ + python3-dev \ + python3-pip \ + tor \ + && rm -rf /var/lib/apt/lists/* \ + && ln -sf /usr/bin/python3 /usr/bin/python \ + && ln -sf /usr/bin/python3 /usr/local/bin/python \ + && ln -sf /usr/bin/python3 /usr/local/bin/python3 + +# === 2. UV installation === +ADD https://astral.sh/uv/install.sh /uv-installer.sh +RUN sh /uv-installer.sh && rm /uv-installer.sh +ENV PATH="/root/.local/bin:$PATH" + +# === 3. Environment variables === +ENV UV_PROJECT_ENVIRONMENT=/usr/local +ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +ENV TOR_SKIP_LAUNCH=1 + +# === 4. Python dependencies (excellent cache hit) === +COPY pyproject.toml /workspace/pyproject.toml +COPY uv.lock /workspace/uv.lock +COPY backend/pyproject.toml /workspace/backend/pyproject.toml + +RUN cd /workspace/backend && uv sync --frozen --no-dev --extra road-corridor + +# === 5. Node.js dependencies === +COPY backend/package*.json ./ +RUN npm ci --omit=dev + +# === 6. Application code (most frequent changes) === +COPY backend/ . + +# Final setup === +RUN mkdir -p /app/image-data /app/data /ms-playwright \ + && if [ -d /app/data ]; then cp -a /app/data/. /app/image-data/; fi \ + && chmod +x /app/docker-entrypoint.sh \ + && rm -rf /workspace + +# Copy Rust library +COPY --from=rust-builder /build/privacy-core/target/release/libprivacy_core.so /app/libprivacy_core.so +ENV PRIVACY_CORE_LIB=/app/libprivacy_core.so + +# Non-root user +RUN adduser --system --uid 1002 --home /app backenduser \ + && chown -R backenduser /app /ms-playwright \ + && chmod -R u+w /app + +USER backenduser + +EXPOSE 8000 +ENTRYPOINT ["/app/docker-entrypoint.sh"] +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--timeout-keep-alive", "120"] \ No newline at end of file diff --git a/docker-compose.build.yml b/docker-compose.build.yml index e4093909..0339a637 100644 --- a/docker-compose.build.yml +++ b/docker-compose.build.yml @@ -1,11 +1,48 @@ # Developer override — build images from source instead of pulling from GHCR. # Usage: docker compose -f docker-compose.yml -f docker-compose.build.yml build +# services: +# backend: +# build: +# context: . +# dockerfile: ./backend/Dockerfile +# +# frontend: +# build: +# context: ./frontend +# +# +# +# Developer override — build images from source instead of pulling from GHCR. +# Usage: docker compose -f docker-compose.yml -f docker-compose.build.yml build +# +# services: backend: build: context: . - dockerfile: ./backend/Dockerfile + # dockerfile: ./backend/Dockerfile + dockerfile: ./backend/Dockerfile_develop + + # add for internet restriction + args: + HTTP_PROXY: "http://192.168.100.25:10808" + HTTPS_PROXY: "http://192.168.100.25:10808" + NO_PROXY: "localhost,127.0.0.1,::1" + environment: + HTTP_PROXY: "http://192.168.100.25:10808" + HTTPS_PROXY: "http://192.168.100.25:10808" + NO_PROXY: "localhost,127.0.0.1,::1" frontend: build: context: ./frontend + dockerfile: ./Dockerfile_develop + + args: + HTTP_PROXY: "http://192.168.100.25:10808" + HTTPS_PROXY: "http://192.168.100.25:10808" + NO_PROXY: "localhost,127.0.0.1,::1" + environment: + HTTP_PROXY: "http://192.168.100.25:10808" + HTTPS_PROXY: "http://192.168.100.25:10808" + NO_PROXY: "localhost,127.0.0.1,::1" \ No newline at end of file diff --git a/frontend/Dockerfile_develop b/frontend/Dockerfile_develop new file mode 100644 index 00000000..27ddf96a --- /dev/null +++ b/frontend/Dockerfile_develop @@ -0,0 +1,56 @@ +FROM node:20-alpine AS base + +# ====================== DEPENDENCIES ====================== +FROM base AS deps +RUN apk add --no-cache libc6-compat + +WORKDIR /app + +# Copy only package files first (best caching) +COPY package.json package-lock.json ./ + +# Install dependencies +RUN npm ci --frozen-lockfile + +# ====================== BUILDER ====================== +FROM base AS builder +WORKDIR /app + +# Copy dependencies from previous stage +COPY --from=deps /app/node_modules ./node_modules + +# Copy source code (this layer will be invalidated most often) +COPY . . + +ENV NEXT_TELEMETRY_DISABLED=1 + +# NEXT_PUBLIC_* vars must exist at build time +ARG NEXT_PUBLIC_API_URL="" +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL + +RUN npm run build + +# ====================== RUNNER ====================== +FROM base AS runner + +WORKDIR /app + +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 + +# Create non-root user +RUN addgroup --system --gid 1001 nodejs +RUN adduser --system --uid 1001 nextjs + +# Copy built standalone output + static files +COPY --from=builder --chown=nextjs:nodejs /app/public ./public +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static + +USER nextjs + +EXPOSE 3000 +ENV PORT=3000 +ENV HOSTNAME="0.0.0.0" + +CMD ["node", "server.js"] \ No newline at end of file diff --git a/note.md b/note.md new file mode 100644 index 00000000..d8a0c325 --- /dev/null +++ b/note.md @@ -0,0 +1,18 @@ +Run on 0.0.0.0 +```bash +BIND=0.0.0.0 docker compose -f docker-compose.yml -f docker-compose.build.yml up -d +``` + + +Build for development + +```bash +docker compose -f docker-compose.yml -f docker-compose.build.yml build +``` + + +Down + +```bash +docker compose -f docker-compose.yml -f docker-compose.build.yml down -v +``` \ No newline at end of file From 3133b48796fbba6b4c7c5b5ab0260d25883efff2 Mon Sep 17 00:00:00 2001 From: esmaeelE Date: Mon, 2 Nov 2026 15:30:24 +0330 Subject: [PATCH 3/7] change docker-compose to use changed Dockerfile --- docker-compose.build.yml | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/docker-compose.build.yml b/docker-compose.build.yml index 0339a637..9d49abf9 100644 --- a/docker-compose.build.yml +++ b/docker-compose.build.yml @@ -21,28 +21,31 @@ services: build: context: . # dockerfile: ./backend/Dockerfile + # include playwright dockerfile: ./backend/Dockerfile_develop # add for internet restriction - args: - HTTP_PROXY: "http://192.168.100.25:10808" - HTTPS_PROXY: "http://192.168.100.25:10808" - NO_PROXY: "localhost,127.0.0.1,::1" - environment: - HTTP_PROXY: "http://192.168.100.25:10808" - HTTPS_PROXY: "http://192.168.100.25:10808" - NO_PROXY: "localhost,127.0.0.1,::1" + # args: + # HTTP_PROXY: "http://192.168.100.25:10808" + # HTTPS_PROXY: "http://192.168.100.25:10808" + # NO_PROXY: "localhost,127.0.0.1,::1" + # environment: + # HTTP_PROXY: "http://192.168.100.25:10808" + # HTTPS_PROXY: "http://192.168.100.25:10808" + # NO_PROXY: "localhost,127.0.0.1,::1" frontend: build: context: ./frontend - dockerfile: ./Dockerfile_develop + dockerfile: ./Dockerfile + # dockerfile: ./Dockerfile_develop - args: - HTTP_PROXY: "http://192.168.100.25:10808" - HTTPS_PROXY: "http://192.168.100.25:10808" - NO_PROXY: "localhost,127.0.0.1,::1" - environment: - HTTP_PROXY: "http://192.168.100.25:10808" - HTTPS_PROXY: "http://192.168.100.25:10808" - NO_PROXY: "localhost,127.0.0.1,::1" \ No newline at end of file + # add for internet restriction + # args: + # HTTP_PROXY: "http://192.168.100.25:10808" + # HTTPS_PROXY: "http://192.168.100.25:10808" + # NO_PROXY: "localhost,127.0.0.1,::1" + # environment: + # HTTP_PROXY: "http://192.168.100.25:10808" + # HTTPS_PROXY: "http://192.168.100.25:10808" + # NO_PROXY: "localhost,127.0.0.1,::1" From 1030ee85e8389b34450b9c65d980dc43aa9fbddc Mon Sep 17 00:00:00 2001 From: esmaeelE Date: Sat, 7 Nov 2026 17:12:55 +0330 Subject: [PATCH 4/7] =?UTF-8?q?feat(osm):=20fix=20PR=20#649=20review=20req?= =?UTF-8?q?uests=20=E2=80=94=20add=20backend=20tile=20proxy,=20remove=20di?= =?UTF-8?q?sabled=20OSM=20Source=20block,=20clean=20unused=20imports,=20re?= =?UTF-8?q?vert=20cartoTileUrls=20concatenation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/main.py | 2 + backend/routers/osm_tiles.py | 86 +++++++++++++++++++ frontend/src/components/MaplibreViewer.tsx | 24 ------ .../src/components/map/styles/mapStyles.ts | 11 +-- 4 files changed, 89 insertions(+), 34 deletions(-) create mode 100644 backend/routers/osm_tiles.py diff --git a/backend/main.py b/backend/main.py index 0c9f03a4..02149a26 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") @@ -3846,6 +3847,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..ef94995b --- /dev/null +++ b/backend/routers/osm_tiles.py @@ -0,0 +1,86 @@ +"""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 + +from cachetools import TTLCache +from fastapi import APIRouter, Path +from fastapi.responses import Response + +from services.network_utils import fetch_with_curl, 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: TTLCache = TTLCache(maxsize=2048, ttl=7 * 24 * 60 * 60) + +# 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") +async def osm_tile( + 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: + status, content, content_type = cached + return Response(content=content, media_type=content_type, status_code=status) + + url = f"{_OSM_TILE_BASE}/{z}/{x}/{y}.png" + try: + upstream = fetch_with_curl( + url, + timeout=20, + headers={"User-Agent": _OSM_USER_AGENT}, + ) + except Exception as exc: # pragma: no cover - network failure path + logger.warning("OSM tile proxy request failed for %s: %s", url, exc) + return Response(status_code=502) + + status = upstream.status_code or 502 + content = getattr(upstream, "content", b"") or b"" + content_type = ( + upstream.headers.get("Content-Type", "image/png") + if hasattr(upstream, "headers") + else "image/png" + ) + + # Only cache successful responses — rate limits and errors must propagate. + if status == 200 and content: + _TILE_CACHE[cache_key] = (status, content, content_type) + + return Response(content=content, media_type=content_type, status_code=status) diff --git a/frontend/src/components/MaplibreViewer.tsx b/frontend/src/components/MaplibreViewer.tsx index 677e039b..76879d55 100644 --- a/frontend/src/components/MaplibreViewer.tsx +++ b/frontend/src/components/MaplibreViewer.tsx @@ -20,9 +20,6 @@ import { CARTO_ATTRIBUTION_HTML, OPENFREEMAP_ATTRIBUTION_HTML, OSM_ATTRIBUTION_HTML, - darkStyle, - lightStyle, - osmTiles, } from '@/components/map/styles/mapStyles'; import { useBasemapConfig } from '@/hooks/useBasemapConfig'; @@ -2063,27 +2060,6 @@ const MaplibreViewer = ({ )} - {/* OpenStreetMap standard raster tiles — selectable basemap */} - {false && ( - - - - )} - {/* NASA GIBS MODIS Terra — daily satellite imagery overlay */} {activeLayers.gibs_imagery && gibsDate && ( - `https://` + s + `.basemaps.cartocdn.com/rastertiles/${style}/{z}/{x}/{y}@2x.png?key=${encodeURIComponent(key)}`, + `https://${s}.basemaps.cartocdn.com/rastertiles/${style}/{z}/{x}/{y}@2x.png?key=${encodeURIComponent(key)}`, ); } @@ -90,12 +90,3 @@ export function buildBasemapStyle( export const darkStyle = buildBasemapStyle('dark'); export const lightStyle = buildBasemapStyle('light'); - -/** Standard OpenStreetMap raster tiles — selectable basemap (no API key). - * Proxied through backend to satisfy OSM tile usage policy (Referer header). */ -export const osmTiles = { - tiles: ['/api/osm-tile/{z}/{x}/{y}.png'], - tileSize: 256, - maxzoom: 19, - attribution: OSM_ATTRIBUTION_HTML, -}; From 3f1c882159ca2f148bb3d25db33803b49a402784 Mon Sep 17 00:00:00 2001 From: esmaeelE Date: Mon, 9 Nov 2026 10:05:19 +0330 Subject: [PATCH 5/7] fix: resolve merge conflict in MaplibreViewer.tsx --- frontend/src/components/MaplibreViewer.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/frontend/src/components/MaplibreViewer.tsx b/frontend/src/components/MaplibreViewer.tsx index 7e08e9d7..a8ee21fe 100644 --- a/frontend/src/components/MaplibreViewer.tsx +++ b/frontend/src/components/MaplibreViewer.tsx @@ -34,10 +34,7 @@ import { OSM_ATTRIBUTION_HTML, } from '@/components/map/styles/mapStyles'; import { useBasemapConfig } from '@/hooks/useBasemapConfig'; -<<<<<<< HEAD - -import * as maplibregl from 'maplibre-gl'; -maplibregl.setWorkerUrl('/maplibre-gl-worker.mjs'); +import maplibregl from 'maplibre-gl'; import { AlertTriangle, Radio, Activity, Play, Satellite, ExternalLink, Info } from 'lucide-react'; import WikiImage from '@/components/WikiImage'; import FishingDestinationRoute from '@/components/map/FishingDestinationRoute'; From bfa46e75bb6e29c17e8d6305562e9267975228a1 Mon Sep 17 00:00:00 2001 From: esmaeelE <22000310+esmaeelE@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:50:57 +0330 Subject: [PATCH 6/7] fix(map): restore maplibre namespace import and worker URL The merge-conflict resolution (3f1c882) reverted upstream d7a7595 "Patch runtime dependencies and migrate MapLibre worker integration", switching to a default import that maplibre-gl does not provide. - back to namespace import: maplibre-gl has no default export (TS1192) - restore maplibregl.setWorkerUrl('/maplibre-gl-worker.mjs'), which next.config.ts copies from node_modules into public/ at build time --- frontend/src/components/MaplibreViewer.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/MaplibreViewer.tsx b/frontend/src/components/MaplibreViewer.tsx index a8ee21fe..49226745 100644 --- a/frontend/src/components/MaplibreViewer.tsx +++ b/frontend/src/components/MaplibreViewer.tsx @@ -34,7 +34,8 @@ import { OSM_ATTRIBUTION_HTML, } from '@/components/map/styles/mapStyles'; import { useBasemapConfig } from '@/hooks/useBasemapConfig'; -import maplibregl from 'maplibre-gl'; +import * as maplibregl from 'maplibre-gl'; +maplibregl.setWorkerUrl('/maplibre-gl-worker.mjs'); import { AlertTriangle, Radio, Activity, Play, Satellite, ExternalLink, Info } from 'lucide-react'; import WikiImage from '@/components/WikiImage'; import FishingDestinationRoute from '@/components/map/FishingDestinationRoute'; From 68d462b70bb08bc829ae086f11b5cac139fdad17 Mon Sep 17 00:00:00 2001 From: BigBodyCobain <43977454+BigBodyCobain@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:26:18 -0700 Subject: [PATCH 7/7] Keep OSM basemap responsive and retain standard Docker builds --- .github/workflows/ci.yml | 1 + backend/Dockerfile_develop | 87 ------------------- backend/routers/osm_tiles.py | 54 +++++++----- backend/tests/test_osm_tiles.py | 32 +++++++ docker-compose.build.yml | 42 +-------- frontend/Dockerfile_develop | 56 ------------ frontend/src/app/page.tsx | 10 +-- frontend/src/components/DisplayMenu.tsx | 1 + .../src/components/WorldviewLeftPanel.tsx | 2 - .../src/components/map/styles/mapStyles.ts | 1 + frontend/src/lib/layerPreferences.ts | 1 - frontend/src/types/dashboard.ts | 1 - note.md | 18 ---- 13 files changed, 70 insertions(+), 236 deletions(-) delete mode 100644 backend/Dockerfile_develop create mode 100644 backend/tests/test_osm_tiles.py delete mode 100644 frontend/Dockerfile_develop delete mode 100644 note.md 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/Dockerfile_develop b/backend/Dockerfile_develop deleted file mode 100644 index 3eafe27f..00000000 --- a/backend/Dockerfile_develop +++ /dev/null @@ -1,87 +0,0 @@ -# ======================================== -# Stage 1: Rust Library Builder -# ======================================== -FROM --platform=$BUILDPLATFORM rust:1.88-slim-bookworm AS rust-builder - -RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates git pkg-config libssl-dev build-essential \ - && rm -rf /var/lib/apt/lists/* - -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true -ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse - -WORKDIR /build/privacy-core - -# Cache dependencies -COPY privacy-core/Cargo.toml privacy-core/Cargo.lock* ./ -RUN mkdir -p src && echo "fn main() {}" > src/lib.rs -RUN cargo build --release --lib - -# Real build -COPY privacy-core/src ./src -RUN cargo build --release --lib && ls -la target/release/libprivacy_core.so - - -# ======================================== -# Stage 2: Final Runtime Image -# ======================================== -FROM mcr.microsoft.com/playwright:v1.48.0-noble AS backend - -WORKDIR /app - -# === 1. System packages (cached very well - first layer after FROM) === -RUN apt-get update && apt-get install -y --no-install-recommends \ - python3 \ - python3-venv \ - python3-dev \ - python3-pip \ - tor \ - && rm -rf /var/lib/apt/lists/* \ - && ln -sf /usr/bin/python3 /usr/bin/python \ - && ln -sf /usr/bin/python3 /usr/local/bin/python \ - && ln -sf /usr/bin/python3 /usr/local/bin/python3 - -# === 2. UV installation === -ADD https://astral.sh/uv/install.sh /uv-installer.sh -RUN sh /uv-installer.sh && rm /uv-installer.sh -ENV PATH="/root/.local/bin:$PATH" - -# === 3. Environment variables === -ENV UV_PROJECT_ENVIRONMENT=/usr/local -ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright -ENV TOR_SKIP_LAUNCH=1 - -# === 4. Python dependencies (excellent cache hit) === -COPY pyproject.toml /workspace/pyproject.toml -COPY uv.lock /workspace/uv.lock -COPY backend/pyproject.toml /workspace/backend/pyproject.toml - -RUN cd /workspace/backend && uv sync --frozen --no-dev --extra road-corridor - -# === 5. Node.js dependencies === -COPY backend/package*.json ./ -RUN npm ci --omit=dev - -# === 6. Application code (most frequent changes) === -COPY backend/ . - -# Final setup === -RUN mkdir -p /app/image-data /app/data /ms-playwright \ - && if [ -d /app/data ]; then cp -a /app/data/. /app/image-data/; fi \ - && chmod +x /app/docker-entrypoint.sh \ - && rm -rf /workspace - -# Copy Rust library -COPY --from=rust-builder /build/privacy-core/target/release/libprivacy_core.so /app/libprivacy_core.so -ENV PRIVACY_CORE_LIB=/app/libprivacy_core.so - -# Non-root user -RUN adduser --system --uid 1002 --home /app backenduser \ - && chown -R backenduser /app /ms-playwright \ - && chmod -R u+w /app - -USER backenduser - -EXPOSE 8000 -ENTRYPOINT ["/app/docker-entrypoint.sh"] -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--timeout-keep-alive", "120"] \ No newline at end of file diff --git a/backend/routers/osm_tiles.py b/backend/routers/osm_tiles.py index ef94995b..de593508 100644 --- a/backend/routers/osm_tiles.py +++ b/backend/routers/osm_tiles.py @@ -14,11 +14,13 @@ OSM tile usage policy import logging -from cachetools import TTLCache -from fastapi import APIRouter, Path +import httpx +from cachetools import TLRUCache +from fastapi import APIRouter, Path, Request from fastapi.responses import Response -from services.network_utils import fetch_with_curl, outbound_user_agent +from limiter import limiter +from services.network_utils import outbound_user_agent logger = logging.getLogger(__name__) @@ -31,7 +33,7 @@ _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: TTLCache = TTLCache(maxsize=2048, ttl=7 * 24 * 60 * 60) +_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") @@ -45,7 +47,9 @@ def _tile_bounds_valid(z: int, x: int, y: int) -> bool: @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), @@ -57,30 +61,32 @@ async def osm_tile( cache_key = f"{z}/{x}/{y}" cached = _TILE_CACHE.get(cache_key) if cached is not None: - status, content, content_type = cached - return Response(content=content, media_type=content_type, status_code=status) + 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: - upstream = fetch_with_curl( - url, - timeout=20, - headers={"User-Agent": _OSM_USER_AGENT}, - ) - except Exception as exc: # pragma: no cover - network failure path + 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) - status = upstream.status_code or 502 - content = getattr(upstream, "content", b"") or b"" - content_type = ( - upstream.headers.get("Content-Type", "image/png") - if hasattr(upstream, "headers") - else "image/png" + 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(",")) ) - - # Only cache successful responses — rate limits and errors must propagate. - if status == 200 and content: - _TILE_CACHE[cache_key] = (status, content, content_type) - - return Response(content=content, media_type=content_type, status_code=status) + 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/docker-compose.build.yml b/docker-compose.build.yml index 9d49abf9..e4093909 100644 --- a/docker-compose.build.yml +++ b/docker-compose.build.yml @@ -1,51 +1,11 @@ # Developer override — build images from source instead of pulling from GHCR. # Usage: docker compose -f docker-compose.yml -f docker-compose.build.yml build -# services: -# backend: -# build: -# context: . -# dockerfile: ./backend/Dockerfile -# -# frontend: -# build: -# context: ./frontend -# -# -# -# Developer override — build images from source instead of pulling from GHCR. -# Usage: docker compose -f docker-compose.yml -f docker-compose.build.yml build -# -# services: backend: build: context: . - # dockerfile: ./backend/Dockerfile - # include playwright - dockerfile: ./backend/Dockerfile_develop - - # add for internet restriction - # args: - # HTTP_PROXY: "http://192.168.100.25:10808" - # HTTPS_PROXY: "http://192.168.100.25:10808" - # NO_PROXY: "localhost,127.0.0.1,::1" - # environment: - # HTTP_PROXY: "http://192.168.100.25:10808" - # HTTPS_PROXY: "http://192.168.100.25:10808" - # NO_PROXY: "localhost,127.0.0.1,::1" + dockerfile: ./backend/Dockerfile frontend: build: context: ./frontend - dockerfile: ./Dockerfile - # dockerfile: ./Dockerfile_develop - - # add for internet restriction - # args: - # HTTP_PROXY: "http://192.168.100.25:10808" - # HTTPS_PROXY: "http://192.168.100.25:10808" - # NO_PROXY: "localhost,127.0.0.1,::1" - # environment: - # HTTP_PROXY: "http://192.168.100.25:10808" - # HTTPS_PROXY: "http://192.168.100.25:10808" - # NO_PROXY: "localhost,127.0.0.1,::1" diff --git a/frontend/Dockerfile_develop b/frontend/Dockerfile_develop deleted file mode 100644 index 27ddf96a..00000000 --- a/frontend/Dockerfile_develop +++ /dev/null @@ -1,56 +0,0 @@ -FROM node:20-alpine AS base - -# ====================== DEPENDENCIES ====================== -FROM base AS deps -RUN apk add --no-cache libc6-compat - -WORKDIR /app - -# Copy only package files first (best caching) -COPY package.json package-lock.json ./ - -# Install dependencies -RUN npm ci --frozen-lockfile - -# ====================== BUILDER ====================== -FROM base AS builder -WORKDIR /app - -# Copy dependencies from previous stage -COPY --from=deps /app/node_modules ./node_modules - -# Copy source code (this layer will be invalidated most often) -COPY . . - -ENV NEXT_TELEMETRY_DISABLED=1 - -# NEXT_PUBLIC_* vars must exist at build time -ARG NEXT_PUBLIC_API_URL="" -ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL - -RUN npm run build - -# ====================== RUNNER ====================== -FROM base AS runner - -WORKDIR /app - -ENV NODE_ENV=production -ENV NEXT_TELEMETRY_DISABLED=1 - -# Create non-root user -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 nextjs - -# Copy built standalone output + static files -COPY --from=builder --chown=nextjs:nodejs /app/public ./public -COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ -COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static - -USER nextjs - -EXPOSE 3000 -ENV PORT=3000 -ENV HOSTNAME="0.0.0.0" - -CMD ["node", "server.js"] \ No newline at end of file diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 51dbe65f..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 @@ -552,7 +552,6 @@ export default function Dashboard() { setActiveLayers((l) => ({ ...l, highres_satellite: next === 'SATELLITE', - osm_basemap: next === 'OSM', })); return next; }); @@ -568,7 +567,6 @@ export default function Dashboard() { sar: false, gibs_imagery: false, highres_satellite: false, - osm_basemap: false, sentinel_hub: false, viirs_nightlights: false, road_corridor_trends: false, @@ -993,15 +991,15 @@ export default function Dashboard() { 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/WorldviewLeftPanel.tsx b/frontend/src/components/WorldviewLeftPanel.tsx index dd7583d7..19228a7c 100644 --- a/frontend/src/components/WorldviewLeftPanel.tsx +++ b/frontend/src/components/WorldviewLeftPanel.tsx @@ -43,7 +43,6 @@ import { Droplets, Radar, MapPin, - Map, Truck, RefreshCw, } from 'lucide-react'; @@ -703,7 +702,6 @@ function SdrTracker({ const TOGGLE_ALL_EXCLUDED_LAYERS = new Set([ 'gibs_imagery', 'highres_satellite', - 'osm_basemap', 'sentinel_hub', 'viirs_nightlights', 'road_corridor_trends', diff --git a/frontend/src/components/map/styles/mapStyles.ts b/frontend/src/components/map/styles/mapStyles.ts index 289f6f66..3740f058 100644 --- a/frontend/src/components/map/styles/mapStyles.ts +++ b/frontend/src/components/map/styles/mapStyles.ts @@ -49,6 +49,7 @@ export function buildBasemapStyle( if (mapStyle === 'OSM') { return { version: 8, + glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf', sources: { osm: { type: 'raster', diff --git a/frontend/src/lib/layerPreferences.ts b/frontend/src/lib/layerPreferences.ts index 3ab851a3..b0d3f1ca 100644 --- a/frontend/src/lib/layerPreferences.ts +++ b/frontend/src/lib/layerPreferences.ts @@ -50,7 +50,6 @@ export function getDefaultActiveLayers(): ActiveLayers { satellites: true, gibs_imagery: false, highres_satellite: false, - osm_basemap: false, sentinel_hub: false, viirs_nightlights: false, road_corridor_trends: false, diff --git a/frontend/src/types/dashboard.ts b/frontend/src/types/dashboard.ts index aa5fa03b..e799008c 100644 --- a/frontend/src/types/dashboard.ts +++ b/frontend/src/types/dashboard.ts @@ -1272,7 +1272,6 @@ export interface ActiveLayers { gps_jamming: boolean; gibs_imagery: boolean; highres_satellite: boolean; - osm_basemap: boolean; kiwisdr: boolean; psk_reporter: boolean; satnogs: boolean; diff --git a/note.md b/note.md deleted file mode 100644 index d8a0c325..00000000 --- a/note.md +++ /dev/null @@ -1,18 +0,0 @@ -Run on 0.0.0.0 -```bash -BIND=0.0.0.0 docker compose -f docker-compose.yml -f docker-compose.build.yml up -d -``` - - -Build for development - -```bash -docker compose -f docker-compose.yml -f docker-compose.build.yml build -``` - - -Down - -```bash -docker compose -f docker-compose.yml -f docker-compose.build.yml down -v -``` \ No newline at end of file