feat(sentinel1): Sentinel-1 SAR STAC -> self-hosted TiTiler tile template
Add GET /api/map/sentinel1?bbox=... which queries Planetary Computer STAC (sentinel-1-grd, last 7d, most recent), signs the vv/hh COG with a SAS token, and returns a same-origin /titiler/... XYZ tile template. Cache keyed on quantized bbox + UTC day (20 min TTL). 429 -> 429 (Retry-After), no imagery -> 404, other upstream errors -> 502. Self-host TiTiler on the Pi (ghcr.io/developmentseed/titiler, arm64, 1G cap, host loopback 8001 -> container 8000) instead of titiler.xyz. nginx /titiler/ proxy snippet routes browser tiles to it; TITILER_PUBLIC_BASE and TITILER_INTERNAL_URL are env-driven (no hardcoded hostnames).
This commit is contained in:
parent
30a9c9e9b1
commit
5212aaa5cd
6 changed files with 346 additions and 5 deletions
|
|
@ -15,13 +15,13 @@ import asyncio
|
|||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
import httpx
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from config import OSINT_USER_AGENT
|
||||
from config import OSINT_USER_AGENT, TITILER_PUBLIC_BASE
|
||||
|
||||
logger = logging.getLogger("osint.live_layers")
|
||||
|
||||
|
|
@ -45,6 +45,15 @@ WFIGS_PERIMETERS = (
|
|||
)
|
||||
NHC_STORMS = "https://www.nhc.noaa.gov/CurrentStorms.json"
|
||||
|
||||
PC_STAC_SEARCH = "https://planetarycomputer.microsoft.com/api/stac/v1/search"
|
||||
PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentinel-1-grd"
|
||||
# Self-hosted TiTiler on the Pi, exposed same-origin through the osint.rpi.local
|
||||
# nginx vhost. Relative template — Leaflet resolves it against the page origin,
|
||||
# so the browser never touches a raw loopback port or titiler.xyz.
|
||||
TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}@1x"
|
||||
SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window
|
||||
SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer"
|
||||
|
||||
IEM_NEXRAD = "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png"
|
||||
GIBS_THERMAL = (
|
||||
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
|
||||
|
|
@ -110,6 +119,15 @@ def overlay_catalog() -> dict:
|
|||
"maxZoom": 9,
|
||||
"attribution": "NASA GIBS / EOSDIS",
|
||||
},
|
||||
"sentinel1_sar": {
|
||||
"id": "sentinel1_sar",
|
||||
"title": "Sentinel-1 SAR (Cloud-Penetrating)",
|
||||
"kind": "raster",
|
||||
"tileUrl": None, # filled from /api/map/sentinel1 (signed COG)
|
||||
"endpoint": "/api/map/sentinel1",
|
||||
"maxZoom": 14,
|
||||
"attribution": SENTINEL1_ATTRIBUTION,
|
||||
},
|
||||
"nws_alerts": {"id": "nws_alerts", "kind": "geojson", "endpoint": "/api/weather-alerts"},
|
||||
"wfigs_incidents": {"id": "wfigs_incidents", "kind": "points", "endpoint": "/api/fire-incidents"},
|
||||
"wfigs_perimeters": {"id": "wfigs_perimeters", "kind": "geojson", "endpoint": "/api/fire-perimeters"},
|
||||
|
|
@ -1136,3 +1154,116 @@ async def fetch_storms() -> list[dict]:
|
|||
return transform_nhc_storms(await _get_json(NHC_STORMS))
|
||||
|
||||
return await _ttl_get("nhc:storms", 300.0, _load)
|
||||
|
||||
|
||||
# ── Sentinel-1 SAR (Planetary Computer STAC → signed COG tile template) ────
|
||||
|
||||
class UpstreamRateLimited(Exception):
|
||||
"""Planetary Computer returned 429. Carries Retry-After for the client."""
|
||||
|
||||
def __init__(self, retry_after: str | None = None):
|
||||
self.retry_after = retry_after
|
||||
super().__init__("planetary computer rate limited")
|
||||
|
||||
|
||||
async def _post_json(
|
||||
url: str, json: dict | None = None, headers: dict | None = None,
|
||||
) -> Any:
|
||||
if _http is None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(),
|
||||
) as client:
|
||||
resp = await client.post(url, json=json, headers=headers)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
resp = await _http.post(url, json=json, headers=headers)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def _pc_call(coro: Awaitable[Any]) -> Any:
|
||||
"""Run a Planetary Computer call, mapping 429 → UpstreamRateLimited."""
|
||||
try:
|
||||
return await coro
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 429:
|
||||
raise UpstreamRateLimited(
|
||||
exc.response.headers.get("Retry-After")
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
def sign_cog_url(href: str, token: str) -> str:
|
||||
"""Append a SAS token to a PC blob URL (respect existing query string)."""
|
||||
sep = "&" if "?" in href else "?"
|
||||
return f"{href}{sep}token={quote(token, safe='')}"
|
||||
|
||||
|
||||
def sentinel1_tile_url(signed_cog: str) -> str:
|
||||
"""TiTiler XYZ template for a signed COG (Leaflet substitutes {z}/{x}/{y})."""
|
||||
params = urlencode({
|
||||
"url": signed_cog,
|
||||
"rescale": "0,500",
|
||||
"colormap_name": "cfastie",
|
||||
})
|
||||
return f"{TITILER_COG_TILES}?{params}"
|
||||
|
||||
|
||||
async def fetch_sentinel1(bbox: str) -> dict | None:
|
||||
"""Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready.
|
||||
|
||||
Returns the overlay tile-template dict, or ``None`` when no GRD imagery
|
||||
covers the bbox in the last 7 days (caller maps to 404). Queries Planetary
|
||||
Computer only when called; cached per quantized bbox + UTC day.
|
||||
"""
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
day = datetime.now(timezone.utc).date().isoformat()
|
||||
key = f"sentinel1:{day}:{bbox_cell_key(bbox)}"
|
||||
|
||||
async def _load() -> dict | None:
|
||||
now = datetime.now(timezone.utc)
|
||||
week_ago = now - timedelta(days=7)
|
||||
payload = {
|
||||
"collections": ["sentinel-1-grd"],
|
||||
"bbox": [minlon, minlat, maxlon, maxlat],
|
||||
"datetime": f"{week_ago.isoformat()}/{now.isoformat()}",
|
||||
"limit": 1,
|
||||
"sortby": [{"field": "datetime", "direction": "desc"}],
|
||||
}
|
||||
data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload))
|
||||
features = data.get("features") or []
|
||||
if not features:
|
||||
return None
|
||||
|
||||
feat = features[0]
|
||||
assets = feat.get("assets") or {}
|
||||
chosen_href: str | None = None
|
||||
polarization: str | None = None
|
||||
for pol in ("vv", "hh"):
|
||||
href = (assets.get(pol) or {}).get("href")
|
||||
if href:
|
||||
chosen_href = href
|
||||
polarization = pol
|
||||
break
|
||||
if not chosen_href:
|
||||
return None
|
||||
|
||||
sas = await _pc_call(_get_json(PC_SAS_TOKEN))
|
||||
token = (sas or {}).get("token")
|
||||
if not token:
|
||||
raise RuntimeError("planetarycomputer SAS token missing")
|
||||
signed = sign_cog_url(chosen_href, token)
|
||||
|
||||
props = feat.get("properties") or {}
|
||||
return {
|
||||
"id": "sentinel-1-sar",
|
||||
"kind": "raster",
|
||||
"tileUrl": sentinel1_tile_url(signed),
|
||||
"opacity": 0.8,
|
||||
"itemId": feat.get("id"),
|
||||
"datetime": props.get("datetime") or feat.get("datetime"),
|
||||
"polarization": polarization,
|
||||
"attribution": SENTINEL1_ATTRIBUTION,
|
||||
}
|
||||
|
||||
return await _ttl_get(key, float(SENTINEL1_TTL), _load)
|
||||
|
|
|
|||
Loading…
Reference in a new issue